var Service = require('../../../../common/Service');
var utils = require('../../../../common/utils');
var util = require('util');

/**
 * 获得子部门和人员列表
 */
var GetSubDepAndUsers = function () {
  Service.call(this);
};

util.inherits(GetSubDepAndUsers, Service);

module.exports = GetSubDepAndUsers;

/**
 * 处理服务请求
 * @param {Object} req 服务请求对象
 * @param {Object} res 服务响应对象
 */
GetSubDepAndUsers.prototype.process = function (req, res) {
  if (!req.depId) {
    this.onLogicError(1, '请提供部门编号！');
    return;
  }
  var org = req.session.org;
  var dep = org.deps[req.depId];
  if (!dep) {
    this.onLogicError(1, '请提供正确的部门编号！');
    return;
  }
  res.deps = [];
  for (var i = 0; i < dep.subDeps.length; i++) {
    var subDep = org.deps[dep.subDeps[i]];
    if (subDep) {
      res.deps.push({
        id: subDep.id,
        name: subDep.name,
        code: subDep.code
      });
    }
  }
  res.deps.sort(utils.compare("code"));
  res.users = [];
  for (var i = 0; i < dep.users.length; i++) {
    var user = org.users[dep.users[i]];
    if (user) {
      var leftInfo = '';
      if (org.user_cell_left_info == 'nickname') leftInfo = user.nickname;
      if (org.user_cell_left_info == 'loginname') leftInfo = user.loginname;
      var rightInfo = '';
      if (org.user_cell_right_info == 'mobile') rightInfo = user.mobile;
      if (org.user_cell_right_info == 'tel_short') rightInfo = user.tel_short;
      if (org.user_cell_right_info == 'tel_work') rightInfo = user.tel_work;
      if (org.user_cell_right_info == 'email') rightInfo = user.email;
      if (org.user_cell_right_info == 'post') rightInfo = user.post;
      if (org.user_cell_right_info == 'net_status') {
        rightInfo = '离线';
        if (user.imStatus == 'online') rightInfo = '在线';
      }
      var bottomInfo = '';
      if (org.user_cell_bottom_info == 'mobile') bottomInfo = user.mobile;
      if (org.user_cell_bottom_info == 'tel_short') bottomInfo = user.tel_short;
      if (org.user_cell_bottom_info == 'tel_work') bottomInfo = user.tel_work;
      if (org.user_cell_bottom_info == 'email') bottomInfo = user.email;
      if (org.user_cell_bottom_info == 'post') bottomInfo = user.post;
      if (org.user_cell_bottom_info == 'motto') bottomInfo = user.motto;
      res.users.push({
        id: user.id,
        name: user.name,
        code: user.code,
        head_id: user.head_id,
        sex: user.sex,
        leftInfo: leftInfo,
        rightInfo: rightInfo,
        bottomInfo: bottomInfo
      });
    }
  }
  res.users.sort(utils.compare("code"));
  this.end(res);
};