var angular = require('angular');
require('../modules');
require('../services/FavoriteLinkerService');
require('../services/userList');
require('../services/userListOfSameDept');
require('../services/LinkerService');

var module = angular.module('linker.directives.linkercards');

function LinkerSelectorList() {
  this.linkerMap = {};
  this.linkers = [];
}

LinkerSelectorList.prototype = {
  get: function(userId) {
    if (this.linkerMap[userId]) {
      return this.linkerMap[userId];
    } else {
      var linker = {
        userId: userId
      };
      this.linkers.push(linker);
      this.linkerMap[userId] = linker;
      return linker;
    }
  },

  getSelectors: function() {
    return _.map(_.filter(this.linkers, function(linker) {
      return linker.selected;
    }), function(linker) {
      return linker.userId;
    });
  },

  unSelectAll: function() {
    _.each(this.linkers, function(linker) {
      linker.selected = false;
    });
  }
};

module.directive('linkerCards', function() {
  return {
    restrict: 'EA',
    replace: true,
    templateUrl: 'views/linker/directives/linkercards.tpl.html',
    scope: {
      canCheck: '=?canCheck',
      chooseLinkerOptions: '=?chooseLinkerOptions',
      loading: '=loading'
    },
    controller: 'LinkerCardsCtrl'
  };
});

module.controller('LinkerCardsCtrl', function(
  $scope, $state, $ionicModal, LinkerService, $ionicScrollDelegate,
  userList, userListOfSameDept, $timeout, FavoriteLinkerService) {
  $scope.linkerList = FavoriteLinkerService.favoriteLinker;
  $scope.userList = userList;
  $scope.userListOfSameDept = userListOfSameDept;
  $scope.linkerSelectorList = new LinkerSelectorList();
  $scope.sendLinkers = [];
  $scope.checkedLinkersDelegateScroll = $ionicScrollDelegate.$getByHandle('checkedLinkersDelegateScroll');

  $scope.getItemHeight = function(linker) {
    this._linker = linker?$scope.linkerSelectorList.get(linker.userId):{};
    return 51;
  };

  /**
   * 联系人的选中状态发生变化，触发该函数。
   * @param  {Object} item 联系人
   */
  $scope.onItemValueChange = function() {
    userList.get($scope.linkerSelectorList.getSelectors())
      .then(function(users) {
        $scope.sendLinkers = users;
        $scope.checkedLinkersDelegateScroll.scrollBottom();
        if ($scope.chooseLinkerOptions && $scope.chooseLinkerOptions.onCheckedUsersChange) {
          $scope.chooseLinkerOptions.onCheckedUsersChange(users);
        }
      });
  };

  /**
   * 查看联系人详情。
   * @param  {String} userId 人员id
   */
  $scope.toLinkerDetail = function(item) {
    if($scope.chooseLinkerOptions && $scope.chooseLinkerOptions.onLinkerClick) {
      $scope.chooseLinkerOptions.onLinkerClick(item);
    } else {
      $scope.userId = item.userId;

      $ionicModal.fromTemplateUrl('views/linker/modal/linkerdetail.modal.tpl.html', function(modal) {
        $scope.linkerModal = modal;
        $scope.linkerModal.show();
      }, {
        scope: $scope,
        animation: 'slide-in-up'
      });
    }
  };

  /**
   * 搜索联系人。
   * @param  {String} searchText 搜索词
   */
  $scope.$watch('search.text', function(searchText) {
    if (searchText) {
      searchText = searchText.trim().toLocaleLowerCase();
      if (searchText) {
        $timeout(function() {
          $scope.searchItems = userList.query(searchText);
          $ionicScrollDelegate.$getByHandle('searchLinkerScroll').scrollTop();
        }, 500);
        return;
      }
    }

    $scope.searchItems = [];
  });

  /**
   * 切换显示卡。
   * @param  {String} cardName 要切换的显示卡名称
   */
  $scope.changeCard = function(cardName) {
    $scope.showCard = cardName;
    if ($scope.showCard === 'favorite') {
      $scope.currentList = FavoriteLinkerService.favoriteLinker;;
    } else if ($scope.showCard === 'local') {
      $scope.currentList = userListOfSameDept;
    } else if ($scope.showCard === 'entire') {
      $scope.currentList = userList;
    }

    $timeout(function() {
      $scope.$broadcast('scroll.infiniteScrollComplete');
      $scope.$broadcast('scroll.resize');
    });
  };

  /**
   * 刷新联系人列表。
   */
  $scope.onRefresh = function() {
    $scope.loading = true;
    $scope.currentList.reset()['finally'](function() {
      $scope.loading = false;
      $scope.$broadcast('scroll.refreshComplete');
      $scope.$broadcast('scroll.resize');
    });
  };

  $scope.removeFromLinkers = function(user) {
    $scope.linkerSelectorList.get(user.userId).selected = false;
    $scope.onItemValueChange();
  };

  $scope.clearCheckLiners = function() {
    $scope.linkerSelectorList.unSelectAll();
    $scope.sendLinkers = [];
    $scope.onItemValueChange();
  };

  /**
   * 加载更多。
   */
  $scope.loadMore = function() {
    $scope.loading = true;
    return $scope.currentList.loadMore()['finally'](function() {
      $scope.loading = false;
      $scope.$broadcast('scroll.infiniteScrollComplete');
      $scope.$broadcast('scroll.resize');
    });
  };
  /**
   * 转换部门名称
   * @param  {String} deptName
   * @return {String} 返回转化后的deptName
   */
  $scope.transferDeptName = function(deptName) {
    if ($scope.showCard === 'favorite' || $scope.showCard === 'entire') {
      return deptName.indexOf('/') === -1 ? '' : filterDeptName(deptName);
    } else {
      deptName = filterDeptName(deptName);
      return deptName.indexOf('/') === -1 ? '' : filterDeptName(deptName);
    }
  };

  /**
   * 截取部门名称，从第一个/向后截取。比如，‘福建省气象局/龙岩市局/长汀县气象局’，返回‘龙岩市局/长汀县气象局’
   * @param  {String} deptName 部门名称
   */
  function filterDeptName(deptName) {
    deptName = deptName.substring(deptName.indexOf('/') + 1, deptName.length);
    return deptName.indexOf(',') === -1 ? deptName : deptName.substring(0, deptName.indexOf(','));
  }

  $scope.loading = true;
  $scope.changeCard('favorite');
  $scope.onRefresh();
  FavoriteLinkerService.refresh();
});
