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

require('../modules');
require('./LinkerCache');
require('./linkerConfig');

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

/** @ngInject */
function LinkerRemoteService($http, $q, LinkerCache, linkerConfig) {
  var MAX_PAGE_SIZE = 1400000000,
    PAGE_SIZE = 20; //查询人员最多返回20条记录。
  var queryUserPromiseCache = {}; // 用于防止获取同一user的请求重复。

  return {
    queryUserById: queryUserById,
    queryDeptById: queryDeptById,
    getUserInfoByIds: getUserInfoByIds,
    queryFavorite: queryFavorite,
    queryFavoriteUsers: queryFavoriteUsers,
    queryAllUsers: queryAllUsers,
    queryAllDepts: queryAllDepts,
    deleteFavoriteById: deleteFavoriteById,
    favoriteUserById: favoriteUserById,
    getDeptTreeByDeptId: getDeptTree,
    getSubUser: getSubUser,
    getSubDept: getSubDept,
    getDept: getDept,
    query: query
  };

  /**
   * 根据联系人id获取联系人详情。
   * @param  {String} userId 联系人id
   */
  function queryUserById(userId) {
    if (userId === '1') {
      return $q.when({
        userId: userId,
        userName: 'admin'
      });
    }
    return LinkerCache.get(userId).then(function(user) {
      if (user) {
        return user;
      } else if (userId) {
        if(queryUserPromiseCache[userId]) {
          return queryUserPromiseCache[userId];
        } else {
          var promise = queryUserByIdRemote(userId);
          queryUserPromiseCache[userId] = promise;
          return promise;
        }
      } else {
        return null;
      }
    });
  }

  function queryUserByIdRemote(userId) {
    return $http.get('/base-user/user/' + userId).then(function(response) {
      return response.data;
    }).then(function(user) {
      return LinkerCache.updateUser(user);
    }).then(function(users) {
      return (users && users.length > 0) ? users[0] : {userId: userId};
    })['finally'](function() {
      delete queryUserPromiseCache[userId];
    });
  }

  /**
   * 根据部门id查询部门信息
   * @param  {String} deptId 部门id
   * @return {Promise}
   */
  function queryDeptById(deptId) {
    return $http.get('/base-user/list/dept?ids='+ deptId).then(function(response) {
      return response.data;
    });
  }

  /**
   * 根据用户id获取用户信息。
   * @param  {Array<String>|String} ids 用户id
   */
  function getUserInfoByIds(ids) {
    return $http.get('/resultTree/user?ids=' + ids).then(function(response) {
      return response.data;
    });
  }

  /**
   * 获取收藏的联系人列表
   */
  function queryFavorite(userId) {
    var pageNo = 0,
      url = '/mobileoffice/user/favorite?userId=' + userId + '&page.size='
        + MAX_PAGE_SIZE + '&page.pn=' + pageNo;

    return $http.get(url).then(function(response) {
      return response.data.content;
    });
  }

  function queryFavoriteUsers(userId) {
    var pageNo = 0,
      url = '/mobileoffice/user/favorite?userId=' + userId + '&format=full'
        + '&page.size='+ MAX_PAGE_SIZE + '&page.pn=' + pageNo;

    return $http.get(url).then(function(response) {
      return response.data.content;
    });
  }

  /**
   *
   * 获取全部联系人。
   * @param  {String} version 版本号
   */
  function queryAllUsers(version) {
    var fliter = linkerConfig.fliterAllUsers,
      pageNo = 0, url;
    if(!!fliter) {
      url = '/base-user/user?' + fliter + '&page.size=' + MAX_PAGE_SIZE + '&page.pn=' + pageNo + '&version=' + version;
    } else {
      url = '/base-user/user?page.size=' + MAX_PAGE_SIZE + '&page.pn=' + pageNo + '&version=' + version;
    }
    return $http.get(url).then(function(response) {
      var meta = response.data.meta || {};
      var content = {
        users: response.data.content,
        version: meta.version,
        userIds: meta.userIds
      };
      return content;
    });
  }

  /**
   * 获取全部部门。
   * @param  {String} version 版本号
   */
  function queryAllDepts(version) {
    var pageNo = 0,
      fliter = linkerConfig.filterAllDepts,
      url;
    if(fliter) {
      url = '/base-user/depts?' + fliter + '&page.size=' + MAX_PAGE_SIZE + '&page.pn=' + pageNo + '&version=' + version;
    } else {
      url = '/base-user/depts?page.size=' + MAX_PAGE_SIZE + '&page.pn=' + pageNo + '&version=' + version;
    }

    return $http.get(url).then(function(response) {
      var meta = response.data.meta || {};
      var content = {
        depts: response.data.content,
        version: meta.version
      };
      return content;
    });
  }

  /**
   * 将联系人从收藏列表中删除。
   * @param  {String} userId 联系人id
   */
  function deleteFavoriteById(currentUserId, linkermanUserId) {
    return $http({
      method: 'DELETE',
      url: '/mobileoffice/user/favorite/' + linkermanUserId + '/' + currentUserId
    }).then(function(response) {
      return response.data;
    });
  }

  /**
   * 将联系人添加到收藏列表
   * @param  {String} userId 当前登录用户Id
   * @param {Array<String>} linkermanUserIds 待收藏的联系人id
   */
  function favoriteUserById(userId, linkermanUserIds) {
    return $http({
      method: 'POST',
      url: '/mobileoffice/user/favorite',
      params: {
        userId: userId
      },
      data: linkermanUserIds
    }).then(function(response) {
      return response.data;
    });
  }

  /**
   * 获取部门人员树
   * @param  {String} deptId 部门Id
   */
  function getDeptTree(deptId) {
    return $http({
      method: 'GET',
      url: '/base-user/tree/user',
      params: {
        deptId: deptId
      }
    }).then(function(response) {
      return response.data;
    });
  }

  /**
   * 获取指定部门下的人员信息
   * @param  {String} deptId 指定部门id
   * @return {Promise}
   */
  function getSubUser(deptId) {
    if(!deptId) { return;}
    var pageNo = 0,
      filter = '$filter=deptId:' + deptId + ' and note:1',
      url = '/base-user/user?' + filter + '&page.size=' + MAX_PAGE_SIZE +
    '&page.pn=' + pageNo;

    return $http.get(url).then(function(response) {
      return response.data.content;
    });
  }

  function getSubDept(deptId) {
    if(!deptId) {return;}
    var pageNo = 0,
      filter = '$filter=deptId:' + deptId + ';1',
      url = '/base-user/depts?' + filter + '&page.size=' + MAX_PAGE_SIZE +
    '&page.pn=' + pageNo;

    return $http.get(url).then(function(response) {
      return filterDept(response.data.content);
    });
  }

  function filterDept(depts) {
    var _depts = [];
    _.each(depts, function(dept) {
      if(dept.fromUnit != '3') {
        _depts.push(dept);
      }
    });
    return _depts;
  }

  function getDept(deptIds) {
    if(!deptIds) {return;}
    var _deptId = deptIds;
    if(_.isArray(deptIds)) {
      var _deptIds = [];
      _.each(deptIds, function(deptId) {
        _deptIds.push(deptId);
      });
      _deptId = _deptIds.join(',');
    }

    var filter = '$filter=deptId:' +_deptId,
      url = '/base-user/depts?' + filter + '&page.size=' + MAX_PAGE_SIZE +
    '&page.pn=0';

    return $http.get(url).then(function(response) {
      return response.data.content[0];
    });
  }

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

    var filter = '$filter=text:' + condition,
      url = '/base-user/user?' + filter + '&page.size=' + PAGE_SIZE;
    return $http.get(url).then(function(response) {
      return response.data.content;
    });
  }
}
