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

/**
 * 删除用户所在部门
 */
var DeleteDep = function() { 
  Service.call(this);
};

util.inherits(DeleteDep, Service);

module.exports = DeleteDep;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
DeleteDep.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.get("user", user_id, function(err, user){
    if(err) {
      self.onLogicError(5, err.message, req, res, cb);
      return;
    }
    if(!req.notVerify){
      if(user.deps.length==1 && user.deps[0]==dep_id) {
        self.onLogicError(6, '删除失败，用户至少要属于一个部门！', req, res, cb);
        return;
      }
    }
    var daoDepUser = new Dep_User(self);
    daoDepUser.delete('user_id='+user_id+' and dep_id='+dep_id
      +' and org_id='+req.session.orgId, function() {
      var orgDao = new Org(self);
      orgDao.setLastUpdate(req.session.orgId, function(lastUpdate) { 
        req.session.cache.rdel("dep_user", 
          {user_id: user_id, dep_id: dep_id}, function(err2){
          if(err2) {
            self.onLogicError(7, err.message, req, res, cb);
            return;
          }
          if(cb) {
            cb(req, res);
          } else {
            self.end(res);
          }
        });
      });
    });
  });
};