var Service = require('Service');
var utils = require('utils');
var Org = require('../../dao/org');
var Dep_User = require('../../dao/dep_user');
var util = require('util');

/**
 * 添加用户所在部门
 */
var AddDep = function() { 
  Service.call(this);
};

util.inherits(AddDep, Service);

module.exports = AddDep;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
AddDep.prototype.process =  function(req, res, cb) {
  if(!req.userId) {
    this.onLogicError(1, '请提供用户编号！', req, res, cb);
    return;
  }
  if(!utils.isInt(req.userId)) {
    this.onLogicError(2, '请提供正确的用户编号！', req, res, cb);
    return;
  }
  if(!req.depId) {
    this.onLogicError(3, '请选择用户所在的部门！', req, res, cb);
    return;
  }
  if(!utils.isInt(req.depId)) {
    this.onLogicError(4, '请提供正确的部门编号！', req, res, cb);
    return;
  }

  var user_id = parseInt(req.userId);
  var dep_id = parseInt(req.depId);

  var self = this;
  req.session.cache.rexists("dep_user", {user_id: user_id, dep_id: dep_id}, function(err, isExists){
    if(err) {
      self.onLogicError(5, err.message, req, res, cb);
      return;
    }
    if(isExists) {
      if(cb) {
        cb(req, res);
      } else {
        self.end(res);
      }
      return;
    }
    var daoDepUser = new Dep_User(self);
    daoDepUser.create({
      org_id: req.session.orgId, 
      dep_id: dep_id,
      user_id: user_id,
      creater_id: req.session.userId, 
      createtime: new Date()}, function() {
        var orgDao = new Org(self);
        orgDao.setLastUpdate(req.session.orgId, function(lastUpdate) { 
          req.session.cache.radd("dep_user", 
            {user_id: user_id, dep_id: dep_id}, function(err2){
            if(err2) {
              self.onLogicError(6, err.message, req, res, cb);
              return;
            }
            if(cb) {
              cb(req, res);
            } else {
              self.end(res);
            }
          });
        });
    });
  });
};