var angular = require('angular'),
  _ = require('jsUtil');

require('../modules');
require('./userList');
require('./LinkerRemoteService');

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

/** @ngInject */
function LinkerSearch(userList, LinkerRemoteService, ConfigApp, $q) {
  return {
    query: query,
    showDeptName: showDeptName, //用于测试
    orgDeptNames: orgDeptNames //用于测试
  };

  /**
   * 查询用户。最多返回20条记录。
   *
   * @param  {[String]} condition 查询条件
   * @return {Array} 返回查询记录
   */
  function query(condition) {
    if(!ConfigApp.allUersGetMethod) {
      return queryCache(condition);
    } else {
      return queryRemote(condition);
    }
  }

  function queryCache(condition) {
    var users = userList.query(condition);
    return $q.when(orgDeptNames(users));
  }

  function queryRemote(condition) {
    return LinkerRemoteService.query(condition).then(function(users) {
      return orgDeptNames(users);
    });
  }

  function orgDeptNames(users) {
    if(!users || users.length === 0 || !_.isArray(users)) {return ;}
    var fullDeptName;
    for(var i = 0, len = users.length; i < len; i++) {
      fullDeptName = users[i].noteFullDeptName;
      users[i].fullDeptName = showDeptName(fullDeptName);
    }
    return users;
  }

  function showDeptName(deptName) {
    if(!deptName) {return;}

    var array = deptName.split('/'),
      _fullDeptName = array.slice(2, array.length);

    if(_fullDeptName.length == 0) {return;}

    if(_fullDeptName.length < 3) {
      return _fullDeptName.join('/');
    } else {
      var len = _fullDeptName.length - 1;
      return _fullDeptName[0] + '/.../' + _fullDeptName[len];
    }
  }
}
