var Service = require('Service');
var utils = require('utils');
var User = require('../../dao/user');
var Org = require('../../dao/org');
var Dep_User = require('../../dao/dep_user');
var RoleDao = require('../../dao/role');
var RoleUserDao = require('../../dao/role_user');
var util = require('util');

/**
 * 添加用户
 */
var Add = function() { 
  Service.call(this);
  this.arrDepId = [];      //部门数组
  this.depCount = 0;  //部门总数
  this.depIndex = 0;  //部门索引
  this.roleAll = null;
};

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;
  }
  var reg = /^([a-zA-Z0-9]{2,10})$/;
  if(!reg.test(req.code)){
    this.onLogicError(1, '用户编码格式无效，只能是字母或数字，长度：2-10！', req, res);
    return; 
  }
  if(!req.name) {
    this.onLogicError(2, '请提供用户姓名！', req, res, cb);
    return;
  }
  reg = /^([a-zA-Z0-9\u4E00-\u9FA5\uFE30-\uFFA0]{2,10})$/;
  if(!reg.test(req.name)){
    this.onLogicError(2, '用户姓名格式无效，只能是汉字、字母或数字，长度：2-10！', req, res);
    return; 
  }
  if(!req.loginname) {
    this.onLogicError(3, '请提供登录名！', req, res, cb);
    return;
  }
  reg = /^([_a-zA-Z0-9\u4E00-\u9FA5\uFE30-\uFFA0]{4,20})$/;
  if(!reg.test(req.loginname)){
    this.onLogicError(3, '登录名格式无效，只能是字母、数字、下划线或汉字，长度：4-20！', req, res);
    return; 
  }
  if(!req.sex && req.sex!=0) {
    this.onLogicError(5, '请提供用户性别！', req, res, cb);
    return;
  }
  if(!req.dep && !req.depId) {
    this.onLogicError(6, '请选择用户所在的部门！', req, res, cb);
    return;
  }
  if(req.dep) req.depId = req.dep.id;
  if(!utils.isInt(req.depId)) {
    this.onLogicError(6, '请提供正确的部门编号！', req, res, cb);
    return;
  }
  if(req.mobile && !utils.isPhone(req.mobile)) {
    this.onLogicError(7, '请提供正确的手机号！', req, res, cb);
    return;
  }
  
  var self = this;
  server.lcManager.checkUserCount(req, function(code, err) {
    if(code!=0) {
      self.onLogicError(8, err, req, res, cb);
      return;
    }
    self.addMobile(req, res, cb);
  });
};

Add.prototype.addMobile =  function(req, res, cb) {
  var self = this;
  var dao = new User(this);
  req.session.cache.getList('user', {fields:'id',where:'#{loginname}=="'
    +req.loginname+'"'},function(err, users){
    if(err) {
      self.onLogicError(6, err.message, req, res, cb);
      return;
    }
    if(users.length>0) {
      if(cb) {
        res.id = users[0].id;
        req.id = users[0].id;
        //req.nickname = req.name;
        self.pipe(require('./update'), req, res, function(req1, res1) {
          //req.nickname = null;
          cb(req1, res1);
        });
      } else {
        self.onLogicError(8, '用户名已经存在！', req, res, cb);
      }
      return;
    }
    if(req.mobile){
      req.session.cache.getList('user', {fields:'id',where:'#{mobile}=="'
        +req.mobile+'"'},function(err2, users2){
        if(err2) {
          self.onLogicError(6, err2.message, req, res, cb);
          return;
        }
        if(!req.isImport && users2.length > 0) {
          self.onLogicError(1, '手机号已存在！', req, res, cb);
          return;
        }
        self.getOrgInfo(req, res, cb);
      });
    } else {
      self.getOrgInfo(req, res, cb);
    }
  });
};

Add.prototype.getOrgInfo = function(req, res, cb) {
  var self = this;
  req.session.cache.getCurOrg(function(org){
    if(!org) {
      self.onLogicError(8, '未找到组织信息！', req, res, cb);
      return;
    }
    self.addUser(req, res, org, cb);
  });
};

Add.prototype.addUser = function(req, res, org, cb) {
  var user = {};
  user.org_id = req.session.orgId;
  user.code = req.code;
  user.name = req.name;
  user.loginname = req.loginname;
  user.password = org.default_pwd;
  user.mobile = req.mobile;
  user.sex = req.sex;
  user.head_id = 0;
  user.nickname = req.name;
  if(req.nickname) user.nickname = req.nickname;
  if(req.post) user.post = req.post;
  if(req.tel_short) user.tel_short = req.tel_short;
  if(req.tel_work) user.tel_work = req.tel_work;
  if(req.tel_home) user.tel_home = req.tel_home;
  if(req.tel_other) user.tel_other = req.tel_other;
  user.status = 0;
  user.creater_id = req.session.userId; 
  user.createtime = new Date();
  
  //任讯客户端有关设置
  user.only_app_center = 0;
  user.disable_app_center = 0;
  user.disable_taskmsg = 0;
  user.disable_address_book = 0;
  user.disable_work_circle = 0;
  user.disable_chpwd = 0;
  user.disk_limit = null;
  user.file_size_limit = null;
  user.create_group = org.create_group;
  user.look_all = org.look_all;
  user.look_self_bureau = org.look_self_bureau;
  user.look_self_dep = org.look_self_dep;
  user.look_leader = org.look_leader;
  user.look_under = org.look_under;
  user.not_bind_device = 0;
  user.bind_ca = 0;
  
  var self = this;
  var dao = new User(this);
  dao.create(user, function(ret) {
    user.id = ret.insertId;
    //user.imStatus = 'offline';
    user.head_id = 0;
    user.deps = [];
    user.roles = [];
    user.subDeps = [];
    user.groups = [];
    delete user.status;
    delete user.creater_id;
    delete user.createtime;
    self.addRoleUser(user, req, res, cb);
  });
};

Add.prototype.addRoleUser = function(user, req, res, cb) {
  var self = this;
  var roleDao = new RoleDao(this);
  roleDao.query({fields:'*', where:'org_id='+req.session.orgId
    +' and name="所有人"'}, function(rows) {
    if(rows.length===0) {
      self.addDepUser(user,req,res,cb);
    }else{
      var roleUser = {};
      roleUser.org_id = req.session.orgId;
      roleUser.user_id = user.id;
      roleUser.role_id = rows[0].id;
      roleUser.creater_id = req.session.userId;
      roleUser.createtime = new Date();
      var roleUserDao = new RoleUserDao(self);
      roleUserDao.create(roleUser, function(ret) {
        self.roleAll = rows[0].id;
        self.addDepUser(user,req,res,cb);
      });
    }
  });
};

Add.prototype.addDepUser = function(user, req, res, cb) {
  var self = this;
  var daoDepUser = new Dep_User(this);
  daoDepUser.create({
    org_id: req.session.orgId, 
    dep_id: req.depId,
    user_id: user.id,
    creater_id: req.session.userId, 
    createtime: new Date()}, function() {
    var orgDao = new Org(self);
    orgDao.setLastUpdate(req.session.orgId, function(lastUpdate) { 
      res.id = user.id;
      if(!req.isImport) {
        req.session.cache.set('user', user.id, user, false, function(err){
          if(err) {
            self.onLogicError(6, err.message, req, res, cb);
            return;
          }
          req.session.cache.radd('dep_user', {dep_id:req.depId,user_id:user.id},function(err2){
            if(err2) {
              self.onLogicError(6, err2.message, req, res, cb);
              return;
            }
            if(self.roleAll) {
              req.session.cache.radd('role_user', {role_id:self.roleAll,user_id:user.id},function(err3){
                if(err3) {
                  self.onLogicError(6, err3.message, req, res, cb);
                  return;
                }
                if(cb) {
                  cb(req, res);
                } else {
                  self.end(res);
                }
              });
            } else {
              if(cb) {
                cb(req, res);
              } else {
                self.end(res);
              }
            }
          });
        });
      } else {
        if(cb) {
          res.user = user;
          if(self.roleAll) res.roleAll = self.roleAll;
          cb(req, res);
        } else {
          self.end('end');
        }
      }
    });
  });
};