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

/**
 * 创建部门
 */
var Add = function() { 
  Service.call(this);
};

util.inherits(Add, Service);

module.exports = Add;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
Add.prototype.process =  function(req, res, cb) {
  if(!req.code) {
    this.onLogicError(1, '请提供部门编码！', req, res, cb);
    return;
  }
  if(!req.name) {
    this.onLogicError(2, '请提供部门名称！', req, res, cb);
    return;
  }

  var parent_id = 0;
  if(req.parentDep) {
    parent_id = parseInt(req.parentDep.id);
  } else if(req.parentId) {
    parent_id = parseInt(req.parentId);
  }
  var fullname = req.fullname;
  if(!fullname) fullname = req.name;
  
  var self = this;
  req.session.cache.exists("dep", "#{parent_id}=="+parent_id
    +" && #{name}=='"+req.name+"'", function(err, isExists) {
    if(err) {
      self.onLogicError(3, err.message, req, res, cb);
      return;
    }
    if(isExists && !req.isFromOA) {
      self.onLogicError(4, '该部门已经存在！', req, res, cb);
      return;
    }
    var dep = {};
    dep.code = req.code;
    dep.name = req.name;
    dep.parent_id = parent_id;
    dep.fullname = fullname;
    dep.org_id = req.session.orgId;
    dep.status = 0;
    dep.description = req.description;
    dep.creater_id = req.session.userId;
    dep.createtime = new Date();
        
    var dao = new Dep(self);
    dao.create(dep, function(ret) {
        var orgDao = new Org(self);
        orgDao.setLastUpdate(req.session.orgId, function(lastUpdate) { 
          //删除不需要缓存的字段
          delete dep.fullname;
          delete dep.org_id;
          delete dep.status;
          delete dep.description;
          delete dep.creater_id;
          delete dep.createtime;
          //将部门添加到缓存
          dep.id = ret.insertId;
          dep.users = new Array();
          dep.subDeps = new Array();

          res.id = dep.id;
          if(!req.isImport) {
            req.session.cache.set("dep", dep.id, dep, false, function(err) {
              if(err) {
                self.onLogicError(3, err.message, req, res, cb);
                return;
              }
              if(cb) {
                cb(req, res);
              } else {
                self.end(res);
              }
            });
          } else {
            if(cb) {
              cb(req, res);
            } else {
              self.end(res);
            }
          }
        });
    });
  });
};