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

/**
 * 导入用户电话信息
 */
var ImportPhone = 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;
};

util.inherits(ImportPhone, Service);

module.exports = ImportPhone;

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

  /*var path = process.cwd()+'/'+((app.config.attach && app.config.attach.dir)?app.config.attach.dir:'files')+'/tmp/upload_'+req.path;
  console.log('正在解析人员名单：'+path);
  var obj = xlsx.parse(path);
  fs.unlinkSync(path);
  //console.log(obj);
  if(obj.length==0) {
    this.onLogicError(2, '数据文件格式不正确！');
    return;
  }
  */
  //第一个工作表的数据
  var self = this;
  this.importExcel(req, req.path, function (resFile) {
    if (resFile.code != 0) {
      self.onLogicError(resFile.code, resFile.message);
      return;
    }
    var data = resFile.data;
    for (var i = 0; i < data.length; i++) {
      if (i < 1 || data[i].length < 2) continue;
      var row = data[i];
      var user = {};
      user.name = (row[0] + '').replace(/ /g, '');
      user.mobile = (row[1] + '').replace(/ /g, '');
      console.log(user);
      self.userList.push(user);
    }
    if (self.userList.length == 0) {
      self.onLogicError(3, '文件中没有找到用户信息！');
      return;
    }

    self.addUser(req, res);
  });
};

ImportPhone.prototype.addUser = function (req, res) {
  var self = this;
  if (this.curUserIndex == this.userList.length) {
    this.requestIMService('sys/service/cache/updateUsers', {
      users: this.userList
    }, req, function (resIM) {
      if (resIM.code != 0) {
        self.onError(resIM);
        return;
      }
      self.end(res);
    });
    return;
  }
  var user = this.userList[this.curUserIndex];
  this.curUserIndex++;
  var dao = new User(this);
  dao.query({
    where: 'name="' + user.name + '" and org_id=' + req.session.orgId,
    fields: 'id'
  }, function (rows) {
    if (rows.length > 0) {
      if (rows.length > 1) logger.log('web', '人员姓名重复：' + user.name, null, null);
      dao.update({
        mobile: user.mobile
      }, {
        where: 'name="' + user.name + '" and org_id=' + req.session.orgId
      }, function () {
        user.id = rows[0].id;
        self.addUser(req, res);
      });
    } else {
      self.addUser(req, res);
    }
  });
};