var Service = require('Service');
var util = require('util');

/**
 * 获得组织结构树
 */
var GetOrgTree = function() { 
  Service.call(this);
  this.connectDb = false;
  this.checkAuthority = false;
};

util.inherits(GetOrgTree, Service);

module.exports = GetOrgTree;

/**
 * 处理服务请求
 * @param  {Object} req 服务请求对象
 * @param  {Object} res 服务响应对象
 */
GetOrgTree.prototype.process =  function(req, res) {
  var getUsers = false;
  if(req.getUsers) getUsers = true;

  res.orgName = req.session.orgName;
  res.deps = [];
  res.rootDeps = [];
  var self = this;
  req.session.cache.getList('dep', null, function(err, deps) {
    if(err) {
      self.onError(err);
      return;
    }
    for(var i=0;i<deps.length;i++) {
      var dep = deps[i];
      if(dep.parent_id==0) res.rootDeps.push(dep.id);
      if(getUsers) {
        res.deps.push([dep.id,dep.code,dep.name,dep.users,dep.subDeps]);
      } else {
        res.deps.push([dep.id,dep.code,dep.name,dep.subDeps]);
      }
    }
  
    if(getUsers) {
      res.users = [];
      req.session.cache.getList('user', null, function(err2, users) {
        if(err2) {
          self.onError(err2);
          return;
        }
        for(var i=0;i<users.length;i++) {
          var user = users[i];
          res.users.push([user.id,user.code,user.name]);
        }
        self.end(res);
      });
      return;
    }
    self.end(res);
  });
};