var angular = require('angular');
var _ = require('jsUtil');
require('./LinkerCache');

var module = angular.module('linker.services');

module.factory('LinkerTreeService', function(LinkerCache, $q) {

  /**
   * 获取指定id的部门的人员树
   *
   * @param {String} deptId 部门id
   * @param {Config} config 获取配置信息
   *
   * @return {Promise}
   */
  function getSubUserDept(deptId, config) {
    return $q.all([LinkerCache.getDept(deptId), LinkerCache.getSubUserDept(deptId)]).then(function(values) {
      var userDepts = values[1];
      var dept = values[0];
      var users = [], depts = [];
      if (config.type === 'user') {
        _.each(userDepts[0], function(user) {
          users.push(user);
        });
      }

      _.each(userDepts[1], function(dept) {
        depts.push(dept);
      });

      dept.users = users;
      dept.depts = depts;
      return filter(config.filterFn, dept);
    });
  }

  function filter(filterFn, dept) {
    var result = dept,
      filterResult;
    if (filterFn && typeof filterFn === 'function') {
      filterResult = filterFn(dept);
      if (filterResult) { result = filterResult; } // 若果有返回值的使用返回值，如果没有就用result。
    }
    return result;
  }

  return {
    getSubUserDept: getSubUserDept
  };
});
