var Service = require('Service');
var util = require('util');
var User = require('../../dao/user');
var Dep = require('../../dao/dep');

/**
 * 导入用户信息
 */
var Import = function() { 
  Service.call(this);
  this.enableTransaction = false;
  this.userList = [];
  this.curUserIndex = 0;
  this.userDao = new User(this);
  this.depDao = new Dep(this);
  this.depIndex = 1;
  this.newDeps = [];
  this.newUsers = [];
  this.roleAll = null;
};

util.inherits(Import, Service);

module.exports = Import;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
Import.prototype.process =  function(req, res) {
  if(!req.path) {
    this.onLogicError(1, '请提供文件路径！');
    return;
  }

  var self = this;
  this.importExcel(req, req.path, function(resFile){
    if(resFile.code!=0) {
      self.onLogicError(resFile.code, resFile.message);
      return;
    }
    for(var i=0;i<resFile.data.length;i++) {
      if(i<2 || resFile.data[i].length<4) continue;
      var row = resFile.data[i];
      var user = {};
      if(row[0] && row[1]) user.bureauName = (row[0]+'').replace(/ /g,'');
      if(row[1]) user.depName = (row[1]+'').replace(/ /g,'');
      if(row[0] && !row[1]) user.depName = (row[0]+'').replace(/ /g,'');
      user.name = (row[2]+'').replace(/ /g,'');
      user.sex = (row[3]+'').replace(/ /g,'');
      user.post = '';
      if(row.length>4 && row[4]) user.post = (row[4]+'').replace(/ /g,'');
      user.mobile = '';
      if(row.length>5 && row[5]) user.mobile = (row[5]+'').replace(/ /g,'');
      user.email = '';
      if(row.length>6 && row[6]) user.email = (row[6]+'').replace(/ /g,'');
      if(row.length>7 && row[7]) user.loginname = (row[7]+'').replace(/ /g,'');
      if(row.length>8 && row[8]) user.code = (row[8]+'').replace(/ /g,'');
      
      
      if(row.length>9 && row[9]) user.tel_short = (row[9]+'').replace(/ /g,'');
      if(row.length>10 && row[10]) user.tel_work = (row[10]+'').replace(/ /g,'');
      if(row.length>11 && row[11]) user.tel_home = (row[11]+'').replace(/ /g,'');
      if(row.length>12 && row[12]) user.tel_other = (row[12]+'').replace(/ /g,'');
      
      user.only_app_center = 0;
      user.disable_app_center = 0;
      user.disable_taskmsg = 0;
      user.disable_address_book = 0;
      user.disable_work_circle = 0;
      self.userList.push(user);
    }
    if(self.userList.length==0) {
      self.onLogicError(3, '文件中没有找到用户信息！');
      return;
    }

    req.isImport = true;
    var args = {};
    req.session.cache.getCurOrg(function(org) {
      req.org = org;
      req.disable_chpwd = org.disable_chpwd;
      self.addUser(req, res);
    });
  });
};

Import.prototype.addUser =  function(req, res) {
  var self = this;
  if(this.curUserIndex==this.userList.length) {
    if(this.newUsers.length > 0 || this.newDeps.length > 0){
      var params = [];
      for(var i=0;i<this.newUsers.length;i++) {
        var userNew = this.newUsers[i];
        params.push({
          modelName: 'user',
          key: userNew.id,
          value: userNew
        });
      }
      for(var i=0;i<this.newDeps.length;i++) {
        var depNew = this.newDeps[i];
        params.push({
          modelName: 'dep',
          key: depNew.id,
          value: depNew
        });
      }
      req.session.cache.mset(params, function(err) {
        if(err) {
          self.onError(err);
          return;
        }
        self.end(res);
      });
    }else{
      self.end(res);
    }
    return;
  }
  var user = this.userList[this.curUserIndex];
  this.curUserIndex++;
  req.sex = 0;
  if(user.sex=='女') req.sex = 1;
  if(user.loginname)  {
    req.loginname = user.loginname; 
  } else {
    req.loginname = user.name;
  }
  req.post = null;
  if(user.post) req.post = user.post;
  req.mobile = null;
  if(user.mobile) req.mobile = user.mobile;
  req.email = null;
  if(user.email) req.email = user.email;
  req.createGroup = req.org.create_group;
  if(user.tel_short) req.tel_short = user.tel_short;
  if(user.tel_work) req.tel_work = user.tel_work;
  if(user.tel_home) req.tel_home = user.tel_home;
  if(user.tel_other) req.tel_other = user.tel_other;

  if(user.bureauName && user.bureauName!=req.org.name && user.bureauName!=user.depName) {
    this.depDao.query({fields: 'id', where: 'name="'+user.bureauName
      +'" and org_id='+req.session.orgId+' and status=0'}, function(rowsOrg) {
      //如果单位不存在就创建该单位
      if(rowsOrg.length==0) {
        req.code = self.depIndex+'';
        self.depIndex++;
        req.name = user.bureauName;
        req.parentId = 0;
        self.pipe(require('../dep/add'), req, res, function(reqD, resD) {
          self.newDeps.push({id:resD.id, name:req.name, code:req.code, parent_id:req.parentId});
          self.addDepAndUser(req, res, user, res.id);
        });
      } else {
        self.addDepAndUser(req, res, user, rowsOrg[0].id);
      }
    });
  } else {
    this.addDepAndUser(req, res, user, 0);
  }
};

Import.prototype.addDepAndUser =  function(req, res, user, parentId) {
  var self = this;
  this.depDao.query({fields: 'id', where: 'name="'+user.depName+'" and parent_id='
    +parentId+' and org_id='+req.session.orgId+' and status=0'}, function(rowsDep) {
    //如果部门不存在就创建该部门
    if(rowsDep.length==0) {
      req.code = self.depIndex+'';
      self.depIndex++;
      req.name = user.depName;
      req.parentId = parentId;
      self.pipe(require('../dep/add'), req, res, function(reqD, resD) {
        self.newDeps.push({id:resD.id, name:req.name, code:req.code, parent_id:req.parentId});
        req.depId = resD.id+'';
        if(user.code) {
          req.code = user.code;
        } else {
          req.code = (1000+self.curUserIndex)+'';
        }
        req.name = user.name;
        self.pipe(require('./add'), req, res, function(reqU, resU) {
          if(resU.user) self.newUsers.push(resU.user);
          if(resU.roleAll) self.roleAll = resU.roleAll;
          self.addUser(req, res);
        });
      });
    } else {
      req.depId = rowsDep[0].id + '';
      if(user.code) {
        req.code = user.code;
      } else {
        req.code = (1000+self.curUserIndex)+'';
      }
      req.name = user.name;
      self.pipe(require('./add'), req, res, function(reqU, resU) {
        if(resU.user) self.newUsers.push(resU.user);
        if(resU.roleAll) self.roleAll = resU.roleAll;
        self.addUser(req, res);
      });
    }
  });
};