var Service = require('Service');
var utils = require('utils');
var Role_User = require('../../dao/role_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, cb) {
  if(!req.roleId) {
    this.onLogicError(1, '请提供角色编号！');
    return;
  }
  if(!utils.isInt(req.roleId)) {
    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 Role_User(this);
  dao.delete('role_id='+req.roleId+' and user_id in ('
    +this.arrUserId.join(',')+') and org_id='
    +req.session.orgId, function() {
    self.add(dao, req, res, cb);
  });
};

AddUser.prototype.add = function(dao, req, res, cb) {
  var self = this;
  dao.execute('insert into sys_role_user(org_id,role_id,user_id,'
    +'creater_id,createtime,is_admin) select '+req.session.orgId
    +','+req.roleId+',id,'+req.session.userId+',sysdate(),0 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) { 
      req.session.cache.radd('role_user', {role_id:parseInt(req.roleId),
        user_id:self.arrUserId}, function(err) {
        if(err) {
          self.onError(err);
          return;
        }
        if(cb) {
          cb(req, res);
        } else {
          self.end(res);
        }
      });
    });
  });
};