var Service = require('Service');
var utils = require('utils');
var UserSubDep = require('../../dao/user_subdep');
var Org = require('../../dao/org');
var util = require('util');

/**
 * 删除用户管辖部门
 */
var DeleteSubDep = function() { 
  Service.call(this);
};

util.inherits(DeleteSubDep, Service);

module.exports = DeleteSubDep;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
DeleteSubDep.prototype.process =  function(req, res) {
  if(!req.userId) {
    this.onLogicError(1, '请提供用户编号！');
    return;
  }
  if(!utils.isInt(req.userId)) {
    this.onLogicError(2, '请提供正确的用户编号！');
    return;
  }
  if(!req.depId) {
    this.onLogicError(3, '请提供部门编号！');
    return;
  }
  var depIds = utils.strToIntArray(req.depId);
  if(depIds.length==0) {
    this.onLogicError(4, '请提供部门编号！');
    return;
  }
  
  var self = this;
  var dao = new UserSubDep(this);
  dao.delete('user_id='+req.userId+' and dep_id in ('+depIds.join()
    +') and org_id='+req.session.orgId, function() {
    var orgDao = new Org(self);
    orgDao.setLastUpdate(req.session.orgId, function(lastUpdate) { 
      req.session.cache.rdel("user_dep", {user_id: parseInt(req.userId), 
        dep_id: depIds}, function(err){
        if(err) {
          self.onLogicError(4, err.message, req, res);
          return;
        }
        self.end(res);
      });
    });
  });
};