var angular = require('angular'),
  _ = require('jsUtil');
require('../modules');
require('./LinkerRemoteService');

angular
  .module('linker.services')
  .factory('LinkerTreeDirectService', LinkerTreeDirectService);

/** @ngInject */
function LinkerTreeDirectService(LinkerRemoteService, $q) {
  var remote = LinkerRemoteService;
  return {
    getSubUserDept: getSubUserDept,
    getUsersOfDept: getSubUser,
    getDeptsOfDept: getSubDept
  };

  /**
   * 获取指定id的部门的人员树
   *
   * @param {String} deptId 部门id
   * @param {Config} config 获取配置信息
   *
   * @return {Promise}
   */
  function getSubUserDept(deptId, config) {
    return $q.all([remote.getDept(deptId), getUserDept(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 getUserDept(deptId) {
    return $q.all([getSubUser(deptId), getSubDept(deptId)]);
  }

  /**
  * 获取指定部门下面的人员信息
  *
  * @param {String} 部门ID
  */
  function getSubUser(deptId) {
    return remote.getSubUser(deptId).then(function(users) {
      var subUsers = [];
      _.each(users, function(user) {
        if (!user.deptId) { return; }
        var deptIds = user.deptId.split(',');
        for (var i = 0, size = deptIds.length; i < size; i++) {
          if (deptIds[i] === deptId) {
            if (user.orderNo) {
              user.orderValue = parseInt(user.orderNo.split(',')[i]);
            }
            subUsers.push(user);
          }
        }
      });
      return subUsers;
    });
  }

  /**
  * 获取指定部门下面的部门信息
  *
  * @param {String} 部门ID
  */
  function getSubDept(deptId) {
    return remote.getSubDept(deptId).then(function(depts) {
      var subDepts = [];
      _.each(depts, function(dept) {
        if (dept.superId === deptId) {
          subDepts.push(dept);
        }
      });
      return subDepts;
    });
  }

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