var Service = require('Service');
var utils = require('utils');
var Dep = require('../../dao/dep');
var Org = require('../../dao/org');
var util = require('util');

/**
 * 修改部门信息
 */
var Update = function() { 
  Service.call(this);
};

util.inherits(Update, Service);

module.exports = Update;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
Update.prototype.process =  function(req, res, cb) {
  if(!req.id) {
    this.onLogicError(1, '请提供部门编号！', req, res, cb);
    return;
  }
  if(!utils.isInt(req.id)) {
    this.onLogicError(2, '请提供正确的部门编号！');
    return;
  }
  if(!req.code) {
    this.onLogicError(3, '请提供部门编码！', req, res, cb);
    return;
  }
  if(!req.name) {
    this.onLogicError(4, '请提供部门名称！', req, res, cb);
    return;
  }
  if(req.parentDep && req.id == parseInt(req.parentDep.id)){
    this.onLogicError(5, '不能把当前部门设置为自己的上级部门！', req, res, cb);
    return;
  }
  var parent_id = 0;
  if(req.parentDep && utils.isInt(req.parentDep.id)) parent_id = parseInt(req.parentDep.id);
  var fullname = req.fullname;
  if(!fullname) fullname = req.name;
  
  var self = this;
  var self = this;
  req.session.cache.exists("dep", "#{parent_id}=="+parent_id
    +" && #{name}=='"+req.name+"' && #{id}!="+req.id, function(err, isExists) {
    if(err) {
      self.onLogicError(5, err.message, req, res, cb);
      return;
    }
    if(isExists && !req.isFromOA) {
      self.onLogicError(6, '该部门已经存在！', req, res, cb);
      return;
    }
    var depNew = {
      code: req.code,
      name: req.name, 
//       status:req.status,
      fullname: fullname, 
      parent_id: parent_id,
      description: req.description
    };
    var dao = new Dep(self);
    //判断该部门下是否存在子部门或人员，如果存在不可修改
    dao.update(depNew, {where: 'id='+req.id+' and org_id='+req.session.orgId}, function(ret) {
      var orgDao = new Org(self);
      orgDao.setLastUpdate(req.session.orgId, function(lastUpdate) { 
        req.session.cache.set("dep", req.id, depNew, true, function(err2) {
          if(err2) {
            self.onLogicError(6, err2.message, req, res, cb);
            return;
          }
          if(cb) {
            cb(req, res);
          } else {
            self.end(res);
          }
        });
      });
    });
  });
};