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

/**
 * 添加用户
 */
var AddUser = function () {
  Service.call(this);
  this.arrUserId; //用户数组
};

util.inherits(AddUser, Service);

module.exports = AddUser;

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

  var self = this;
  var dao = new Dep_User(this);
  dao.delete('dep_id=' + req.depId + ' and user_id in (' + this.arrUserId.join(',') +
    ') and org_id=' + req.session.orgId,
    function () {
      self.add(dao, req, res);
    });
};

AddUser.prototype.add = function (dao, req, res) {
  var self = this;
  var userId = parseInt(this.arrUserId[this.userIndex]);
  dao.execute('insert into sys_dep_user(org_id,dep_id,user_id,' +
    'creater_id,createtime) select ' + req.session.orgId + ',' + req.depId +
    ',id,' + req.session.userId + ',sysdate() from sys_user where org_id=' +
    req.session.orgId + ' and id in (' + this.arrUserId.join(',') + ')', null,
    function () {
      var orgDao = new Org(self);
      orgDao.setLastUpdate(req.session.orgId, function (lastUpdate) {
        self.requestIMService('sys/service/cache/addDepUser', {
          depId: req.depId,
          userIdList: req.userIdList
        }, req, function (resIM) {
          if (resIM.code != 0) {
            self.onError(resIM);
            return;
          }
          self.end(res);
        });
      });
    });
};