var util = require('util');
var fs= require('fs');
var Service = require('Service');
var utils = require('utils');
var AppAttachDao = require('../../dao/app_attach');
var UserDao = require('../../dao/user');

/**
 * 管理员设置用户头像
 * */
var SetHeadManage = function() {
  Service.call(this);
  this.checkAuthority = false;
  this.attachDao = new AppAttachDao(this);
};

util.inherits(SetHeadManage, Service);

module.exports = SetHeadManage;

SetHeadManage.prototype.process =  function(req, res) {
  if(!req.user_id){
    this.onLogicError(1, "请提供用户编号！");
    return;
  }
  if(!utils.isInt(req.user_id)) {
    this.onLogicError(2, '请提供正确的用户编号！');
    return;
  }
  if(!req.head) {
    this.onLogicError(3, '请提供头像！');
    return;
  }
  
  req.fileCode = req.head.code;
  req.fileSize = req.head.size;
  
  var self = this;
  self.attachDao.execute('delete from sys_app_attach where org_id='+req.session.orgId
    +' and app_data_id='+req.user_id+' and app_code="sys.userHead"', null, function(ret) {
    self.addAttach(req, res);
  });
};

SetHeadManage.prototype.addAttach =  function(req, res) {
  var self = this;
  var obj = {};
  obj.app_data_id = req.user_id;
  //在UploadAttachByHttp服务里，如果app_code='sys.userHead'会自动修改缓存里当前用户的头像编号
  //但在系统设置里，当前用户修改的可能是别人的头像
  //为了避免出现修改错误，在系统设置的用户头像设置页面里app_code的值为'sys.userHead.m'
  //保存后要将附件内的这个字段值修改回来
  obj.app_code = 'sys.userHead';  
  this.attachDao.update(obj, {where: 'code=? and org_id='+req.session.orgId,
    params:[req.fileCode]}, function() {
    self.attachDao.query({fields:'id', where:'org_id='+req.session.orgId+' and code=?',
      params:[req.fileCode]}, function(rows) {
      req.headId = rows[0].id;
      var userDao = new UserDao(self);
      userDao.update({head_id:req.headId},
        {where:'org_id='+req.session.orgId+' and id='+req.user_id}, function() {
        res.head_id = req.headId;
        req.session.cache.set('user', req.user_id, 
          {head_id:req.headId}, true, function(err){
          if(err) {
            self.onLogicError(3, err.message);
            return;
          }
          self.end(res);
        });
      });
    });
  });
};