var Service = require('Service');
var util = require('util');
var utils = require('utils');
var DepDao = require('../../dao/dep');

/**
 * 获得管辖部门列表
 */
var GetSubDepList = function() { 
  Service.call(this);
  this.enableTransaction = false;
};

util.inherits(GetSubDepList, Service);

module.exports = GetSubDepList;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
GetSubDepList.prototype.process =  function(req, res) {
  if(!req.userId) {
    this.onLogicError(1, '请提供用户编号！');
    return;
  }
  if(!utils.isInt(req.userId)) {
    this.onLogicError(2, '请提供正确的用户编号！');
    return;
  }

  var self = this;
  var depDao = new DepDao(this);
  depDao.query({
  	fields: 'id,code,name,fullname,description',
    where: 'id in (select dep_id from sys_user_subdep where user_id='
      +req.userId+' and org_id='+req.session.orgId+') and org_id='
      +req.session.orgId+' and status=0'
  }, function(rows) { 	
    res.deps = [];
    for(var i=0;i<rows.length;i++) {
      //if(!(rows[i].id in req.session.org.deps)) continue;
      var dep = {};
      dep.depId = rows[i].id;
      dep.code = rows[i].code;
      dep.name = rows[i].name;
      dep.fullname = rows[i].fullname;
      dep.description = rows[i].description;
      dep.path = rows[i].name;
      //self.setDepPath(req, dep);
      res.deps.push(dep);
    }
    self.end(res);
  });
};

GetSubDepList.prototype.setDepPath =  function(req, dep) {
  var depTmp = dep;
  var parent_id = req.session.org.deps[depTmp.depId].parent_id;
  while(parent_id>0) {
    depTmp = req.session.org.deps[parent_id];
    dep.name = depTmp.name + '-'+dep.name;
    parent_id = depTmp.parent_id;
  }
};