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

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

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

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

      if (result) {
        items.push(dept);
      }

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

    return items;
  };

  /** 根据deptId获取部门全部名称 */
  deptList.queryFullDeptName = function(deptId) {
    var dept;
    for(var i = 0, len = this.allItems.length; i < len; i++) {
      dept = this.allItems[i];
      if(dept.deptId === deptId) {
        return dept;
      }
    }
    return;
  };

  deptList.sync = function() {
    var oldVersion = -1,
      syncData,
      result,
      hasChange = true;
    return deptList.getVersion()
    .then(function(_oldVersion) {
      oldVersion = _oldVersion;
      return LinkerService.queryAllDepts(oldVersion);
    })
    .then(function(data) {
      if (oldVersion === data.version && oldVersion !== -1) { hasChange = false; }
      syncData = data;
      return hasChange && deptList.updateDepts(data.depts);
    })
    .then(function(ids) {
      result = ids;
      return hasChange && localforage.setItem('linker.deptList.version', syncData.version);
    })
    .then(function() {
      return result;
    }, function(error) {
      console.log('同步部门数据时出错，请联系管理员解决这个问题。错误信息：' + error);
    });
  };

  deptList.updateDepts = function(depts) {
    return LinkerCache.updateDept(depts)
    .then(function() {
      var syncDeptIds = _.map(depts, function(dept){
        return dept.deptId;
      });
      return deptList.updateIds(deptList.ids.concat(syncDeptIds));
    });
  };

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

  /**
   * 刷新部门数据
   * @deprecated 即将关闭此方法，等待后端的版本化用户数据的实现。
   * @return {Promise}
   */
  deptList.refresh = function() {
    if (refresh) {
      return;
    }
    refresh = true;
    return LinkerService.queryAllDepts(-1).then(function(content) {
      return LinkerCache.updateDept(content.depts).then(function() {
        var deptIds = _.map(content.depts, function(dept){
            return dept.deptId;
        });
        return deptList.updateIds(deptIds);
      });
    });
  };

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

  return deptList;
});
