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

/**
 * 获得用户列表
 */
var GetList = function() { 
  Service.call(this);
  this.enableTransaction = false;
};

util.inherits(GetList, Service);

module.exports = GetList;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
GetList.prototype.process =  function(req, res) {
  var self = this;
  var where = '(status=0 or status=2) and org_id='+req.session.orgId;
  if(req.depId) {
    var depIds = utils.strToIntArray(req.depId);
    if(depIds.length>0) {
      where += ' and id in (select user_id from sys_dep_user '
        +'where org_id='+req.session.orgId+' and dep_id in ('
        +depIds.join()+'))';
      self.export(req, res, where);
      return;
    }
  }
  this.export(req, res, where);
//   if(req.keyword) {
//     where += ' and (code like "%'+req.keyword+'%" or name like "%'+req.keyword
//       +'%" or loginname like "%'+req.keyword+'%" or post like "%'+req.keyword+'%")';
//   }
//   
};

GetList.prototype.export =  function(req, res, where) {
  var self = this;
  var items = [];
  items.push({"key":"code", "value":"用户代码"});
  items.push({"key":"name", "value":"姓名"});
  items.push({"key":"loginname", "value":"登录名"});
  items.push({"key":"post", "value":"职务"});
  items.push({"key":"sex", "value":"性别"});
  items.push({"key":"mobile", "value":"移动电话"});
  items.push({"key":"tel_short", "value":"内部小号"});
  items.push({"key":"tel_work", "value":"办公电话"});
  items.push({"key":"tel_home", "value":"家庭电话"});
  items.push({"key":"tel_other", "value":"其他电话"});
  items.push({"key":"email", "value":"电子信箱"});
  
  var col = JSON.parse(req.columns);
  //拼接查询字段
  var sql = '';
  for(var i=0;i<col.length;i++){
    for(var j=0;j<items.length;j++){
      if(col[i] == items[j].value){
        if(sql) sql += ',';
        sql += items[j].key;
      }
    }
  }
  var userDao = new User(this);
  userDao.query({where: where,fields: sql,order: 'code ASC,id ASC'}, function(rows) {
    var datas = [];
    datas.push(col);
    var list = sql.split(',');
    for(var i=0;i<rows.length;i++) {
      var row = [];
      for(var j=0;j<list.length;j++){
        if(list[j] == "sex"){
          row.push(rows[i][list[j]] == "0" ? "男" : "女");
        }else{
          row.push(rows[i][list[j]]);
        }
      }
      datas.push(row);
    }
    //datas.push(["查询条件:手机"+req.mobile+"地址"+req.provinceName+req.cityName+req.districtName]);

    var args = {};
    args.data = datas;
    args.appCode = 'userInfo';
    args.fileName = '用户信息'+(new Date()).format('_yyyyMMddhhmmss')+'.xlsx';
    self.exportExcel(req, args, function(resIM) {
      self.end(resIM);
    });
  });  
};