var angular = require('angular');
require('jsUtil');
require('../modules');
require('../../../commons/services/Timer');
require('../services/userDeptList');
require('../services/LinkerService');
require('../services/userDeptList');

var module = angular.module('linker.controllers');

module.controller('LinkerSelfDeptCtrl', function($scope, userListOfSameDept, $state,
  LinkerService, $q, Timer, userDeptList) {
  $scope.load = false;
  $scope.refreshing = false;
  $scope.$on('$ionicView.beforeEnter', function() {
    getAllItems().then(function(data) {
      $scope.depts = data;
    });
  });

  userListOfSameDept.applyIds();

  var getAllItems = function() {
    return LinkerService.getCurrentUser().then(function(currentUser) {
      var allItems = [];
      _.each(currentUser.deptId.split(','), function(value) {
        allItems.push({
          deptId: value
        });
      });
      _.each(currentUser.deptName.split(','), function(value, key) {
        allItems[key].deptName = value;
      });
      return allItems;
    });
  };

  $q.all([getAllItems(), userListOfSameDept.loadFromCache()]).then(function(data) {
    $scope.userListOfSameDept = userListOfSameDept;
    $scope.depts = data[0];
  });

  $scope.hasDept = function(deptIds, cruDeptId) {
    var has = false;
    _.each(deptIds.split(','), function(deptId) {
      if (deptId === cruDeptId) {
        has = true;
      }
    });
    return has;
  };

  /**
   * 只显示真实用户
   */
  $scope.filterLinker = function(user) {
    return user.note === "1";
  };

  $scope.goBack = function() {
    $state.go('core-linker');
  };

  $scope.refresh = function() {
    $scope.refreshing = true;
    userDeptList.sync().then(function() {
      $q.all([getAllItems(), userListOfSameDept.loadFromCache()]).then(function(data) {
        $scope.userListOfSameDept = userListOfSameDept;
        $scope.depts = data[0];
        Timer.delay(function() {
          $scope.refreshing = false;
        }, 500);
      });
    });
  };
});
