var angular = require('angular');
require('../modules');
require('../../../commons/services/PageableCacheArray');
require('./LinkerRemoteService');
require('./LinkerCache');
require('../../../commons/services/localforage');
require('./deptList');
var module = angular.module('linker.services');

module.factory('userList', function(
  PageableCacheArray, LinkerCache, LinkerRemoteService,
  $rootScope, localforage, $q, deptList) {
  var userList = new PageableCacheArray('linker.userList'),
    refresh = false;
  /**
   * @override
   */
  userList.loadAllItems = function() {
    var self = this;
    self.allItems = [];
    return LinkerCache.get(this.ids).then(function(users) {
      self.allItems = users;
      return users;
    });
  };

  /**
   * 查询用户。最多返回20条记录。
   *
   * @param  {[String]} condition 查询条件
   * @return {Array} 返回查询记录
   */
  userList.query = function(condition) {
    var items = [];

    _.any(this.allItems, function(user){
      var result = false;
      for (var i = 0, len = user.querySources.length; i < len; i++) {
        if (user.querySources[i].indexOf(condition) >= 0) {
          result = true;
          break;
        }
      }

      if (result) {
        var dept = deptList.queryFullDeptName(user.noteDeptId);
        if(dept) {
          user.noteFullDeptName = dept.deptFullName;
        }
        items.push(user);
      }


      return result && items.length > 20;
    });

    return items;
  };

  /**
   * 查询用户。最多返回20条记录。
   *
   * @param  {[String]} condition 查询条件
   * @return {Array} 返回查询记录
   */
  userList.queryDept = function(condition) {
    return deptList.query(condition);
  };

  /**
   * 同步用户数据
   *
   * @return {Promise}
   */
  userList.sync = function() {
    var oldVersion = -1,
      syncData,
      result,
      hasChange = true;
    return userList.getVersion()
    .then(function(version) {
      oldVersion = version;
      return LinkerRemoteService.queryAllUsers(version);
    })
    .then(function(data) {
      if (oldVersion === data.version && oldVersion !== -1) { hasChange = false; }
      syncData = data;
      return hasChange && deptList.updateUsers(data.users);
    })
    .then(function(ids) {
      result = ids;
      return hasChange && localforage.setItem('linker.userList.version', syncData.version);
    })
    .then(function() {
      return result;
    }, function(error) {
      console.log('同步人员数据时出错，请联系管理员解决这个问题。错误信息：' + error);
    });
  };

  userList.getVersion = function() {
    return localforage.getItem('linker.userList.version').then(function(version) {
      return isNaN(parseInt(version))? -1 : version;
    });
  };

  deptList.updateUsers = function(users) {
    return LinkerCache.updateUser(users)
    .then(function() {
      var syncUserIds = _.map(users, function(user){
        return user.userId;
      });
      return userList.updateIds(userList.ids.concat(syncUserIds));
    });
  };

  userList.clear = function() {
    return $q.all([
      localforage.setItem('linker.userList.version', -1),
      userList.updateIds([]),
      LinkerCache.clearUser()]);
  };

  /**
   * 刷新用户数据
   * @deprecated 即将关闭此方法，等待后端的版本化用户数据的实现。
   * @return {Promise}
   */
  userList.refresh = function() {
    if (refresh) {
      return;
    }
    refresh = true;
    return LinkerRemoteService.queryAllUsers(-1).then(function(content) {
      return LinkerCache.updateUser(content.users).then(function() {
        var userIds = _.map(content.users, function(user){
          return user.userId;
        });
        return userList.updateIds(userIds);
      });
    });
  };

  /**
   * 获取指定id的用户。
   *
   * @param  {Array<String>|String} userId 一个或者一组用户id
   *
   * @return {Promise}
   */
  userList.get = function(userId) {
    var isArray = _.isArray(userId);
    return LinkerCache.get(userId).then(function(users) {
      var noCachedUsers = diff(users, userId);
      if (noCachedUsers.length > 0) {
        return LinkerRemoteService.getUserInfoByIds(noCachedUsers).then(function(newUsers) {
          return LinkerCache.updateUser(newUsers);
        }).then(function(newUsers) {
          return isArray? sort(userId, newUsers.concat(users)) : newUsers[0];
        });
      }
      return users;
    });
  };

  /**
  * 同步获取指定用户的数组
  *
  * @param {String|Array<String>} 一个或者一组用户的ids
  * @return {Array<User>}
  */
  userList.getUserSync = function(userId) {
    return LinkerCache.getUserSync(userId);
  };

  /**
  * 同步获取指定部门的数组
  *
  * @param {String|Array<String>} 一个或者一组部门的ids
  * @return {Array<Dept>}
  */
  userList.getDeptSync = function(deptId) {
    return LinkerCache.getDeptSync(deptId);
  };

  /**
   * 获取一组或者一个部门信息
   *
   * @param {Array<String> | String}
   *
   * @return {Promise}
   */
  userList.getDept = function(deptId) {
    return LinkerCache.getDept(deptId);
  };

  function sort(userIds, users) {
    var userMap = {};
    _.each(users, function(user){
      userMap[user.userId] = user;
    });
    return _.map(userIds, function(userId) {
      return userMap[userId];
    });
  }

  function diff(users, userIds) {
    var userId, result = [];
    userIds = _.isArray(userIds)? userIds : [userIds];
    if (!users) {
      return userIds;
    } else {
      users = _.isArray(users)? _.map(users, function(user){return user.userId;}) : [users.userId];

      for (var i = 0, len = userIds.length; i < len; i++) {
        userId = userIds[i];
        if (_.indexOf(users, userId) === -1) {
          result.push(userId);
        }
      }
    }

    return result;
  }

  $rootScope.userList = userList;

  return userList;
});
