var angular = require('angular');
require('jsUtil');
require('../modules');
require('../../../commons/services/Timer');
require('../../../commons/directives/$toast');
require('../services/LinkerSearch');
require('../services/userDeptList');
require('../directives/linkerNav');
require('../services/LinkerTreeService');
require('../services/FavoriteLinkerService');
require('../services/mulCallAsynchronousResult');
require('../services/throttleService');

angular
  .module('linker.controllers')
  .controller('LinkerCtrl', LinkerCtrl);

/** @ngInject */
function LinkerCtrl($scope, LinkerSearch,
  $timeout, $ionicScrollDelegate, $toast, userListOfSameDept,
  LinkerTreeService, Timer, $state, userDeptList, linkerConfig,
  FavoriteLinkerService, ConfigApp, $q, mulCallAsynchronousResult, throttleService) {

  $scope.loading = false;
  $scope.favoriteLinkerLoading = 1;
  FavoriteLinkerService.sync().then(function() {
    $scope.favoriteLinkerLoading = 2;
  }, function() {
    $scope.favoriteLinkerLoading = 3;
  });//常用联系人初始化

  $scope.goSelfDept = goSelfDept;
  $scope.goAllDept = goAllDept;
  $scope.goAllDeptRemote = goAllDeptRemote;//用于测试
  $scope.onRefresh = onRefresh;
  $scope.favoritedSameDept = favoritedSameDept;

  $scope.$on('$ionicView.beforeEnter', function() {
    $scope.onScrollState = false;
    userDeptList.sync();
  });

  /**
   * 延时显示批量导入的按钮
   */
  Timer.delay(function() {
    $scope.inited = true;
  }, 200);

  $scope.favoriteLinker = $scope.itemConfig = FavoriteLinkerService.favoriteLinker;

  $scope.itemConfig.getLinkerNavFn = function(position) {
    var item = $scope.favoriteLinker.items[position];
    var letter = item.userNamePinyin[0].substring(0, 1).toUpperCase();
    return letter;
  };

  $scope.onScroll = function() {
    if ($scope.onScrollState) { return; }
    $scope.$broadcast('linkernav.linkerListScrollView.scroll');
    $scope.$emit('linkernav.linkerListScrollView.scroll');
  };

  $scope.$on('linkernav.touch.change', function($event, linkerNav) {
    $scope.$broadcast('linkernav.infochange', linkerNav);
    $scope.$emit('linkernav.infochange', linkerNav);
  });

  $scope.$on('linkernav.itemposition.change', function($event, position) {
    var item = $scope.favoriteLinker.items[position],
      firstWord = item.userName.substring(0, 1);
    $scope.$broadcast('linkernav.infochange', firstWord);
    $scope.$emit('linkernav.infochange', firstWord);
  });

  /**
   * 搜索联系人。
   * @param  {String} searchText 搜索词
   */
  $scope.$watch('search.text', function(searchText) {
    $scope.searchItems = [];
    $scope.search_loading = null;
    queryFn(searchText);
  });

  var queryFn = throttleService.throttle(mulCallAsynchronousResult
    .mcar(query, function(value) {
      if(value === 'less') {
        $scope.search_loading = 3;
      } else {
        $scope.searchItems = value || [];
        $scope.search_loading = 2;
        $ionicScrollDelegate.$getByHandle('searchLinkerScroll').scrollTop();
      }
    }, function() {
      $scope.search_loading = 4;
      $scope.searchItems = [];
    }), 500, true, true);

  function query(searchText) {
    if(searchText) {
      searchText = searchText.trim().toLocaleLowerCase();
    }
    if (searchText) {
      searchText = searchText.trim().toLocaleLowerCase();
      if (searchText && !(searchText.length == 1 && (/^[A-Za-z]+$/).test(searchText))) {
        $scope.search_loading = 1;
        return LinkerSearch.query(searchText);
      }
    }
    return $q.when('less');//空格 or 一个字母
  }

  function goSelfDept() {
    $scope.onScrollState = true;
    $state.go('linker-linkerSelfDept');
  };

  function goAllDept() {
    $scope.onScrollState = true;
    var url = !ConfigApp.allUersGetMethod ? 'linker-linkerAllusers' : 'linker-linkerAllusersRemote';
    $state.go(url);
  };

  //用于测试
  function goAllDeptRemote() {
    $state.go('linker-linkerAllusersRemote');
  }

  /**
   * 刷新常用联系人
   */
  function onRefresh() {
     FavoriteLinkerService.refresh(true).then(function() {
      $scope.favoriteLinkerLoading = 2;
    }, function() {
      if($scope.favoriteLinker && $scope.favoriteLinker.items.length > 0) {
        $scope.favoriteLinkerLoading = 2;
      } else {
        $scope.favoriteLinkerLoading = 3;
      }

    }).finally(function() {
      $scope.$broadcast('scroll.refreshComplete');
    });
  };

  /**
   * 收藏本部门联系人
   */
  function favoritedSameDept() {
    var selfDeptMans = userListOfSameDept.items;
    var linmanUserIds = [];
    selfDeptMans.forEach(function(item, index, array) {
      var temp = array[index];
      linmanUserIds.push(temp.userId);
    });
    return FavoriteLinkerService.add(linmanUserIds).then(function() {
      $toast.showLongCenter('本部门联系人已收藏');
    }, function() {
      $toast.showLongCenter('收藏本部门联系人失败，请检查网络连接。');
    });
  };

}
