var angular = require('angular');
require('../modules');
require('../services/LinkerTreeDirectService');
require('../../../commons/services/Timer');
require('../../../commons/directives/sinoBreadcrumb');
require('ngIonic');
require('../services/userDeptList');
require('../../../commons/services/AppConfig');

angular
  .module('linker')
  .controller('AllUsersCtrl', AllUsersCtrl);
/** @ngInject */
function AllUsersCtrl($scope, Timer,
  $ionicScrollDelegate, LinkerTreeDirectService, type, $state, userDeptList,
  linkerConfig, CoreAppConfig) {
  $scope.topDeptId = linkerConfig.topDeptId;
  $scope.type = type;

  var ctrl = this,
    currentLoadingDept = null;

  ctrl.loadingState = 1;
  ctrl.fetchUserAndDept = fetchUserAndDept;
  ctrl.getDetail = getDetail;
  ctrl.refresh = refresh;

  ctrl.topDeptId = linkerConfig.topDeptId;

  $scope.$on('$ionicView.afterLeave', function() {
    currentLoadingDept = linkerConfig.topDeptId;
    $scope.$broadcast('linkerTreeLeave', '');
  });

  $scope.$on('$ionicView.beforeEnter', function() {
    fetchUserAndDept();
  });

  function fetchUserAndDept(deptId) {
    deptId = deptId || currentLoadingDept || linkerConfig.topDeptId;
    currentLoadingDept = deptId;
    if(!ctrl.refreshing) {
      ctrl.loadingState = 1;
    }
    return LinkerTreeDirectService.getSubUserDept(deptId, {type: type})
      .then(function(dept) {
        if (currentLoadingDept !== deptId) {
          return;
        }
        filterJuUser(dept);
        ctrl.dept = dept;
        ctrl.loadingState = dept.users.length > 0 || dept.depts.length > 0? 2 : 4;
      }, function() {
        //必须是最新的数据才要，不是最新的，丢弃
        if (currentLoadingDept === deptId) {
          ctrl.loadingState = 3;
        }
      });
  }

  /**
   * 进入自己部门
   */
  function getDetail(node) {
    node.users = node.depts = [];
    ctrl.fetchUserAndDept(node.deptId);
  }

  function refresh() {
    ctrl.refreshing = true;
    fetchUserAndDept().then(function() {
      Timer.delay(function() {
        ctrl.refreshing = false;
      }, 500);
    });
  }

  /**
   * 国家局不显示局领导
   */
  function filterJuUser(dept) {
    var appId = CoreAppConfig.getAppId();

    if (appId === 'gjjoa' && dept.deptId === '001') {
      dept.users = [];
    }

    return dept;
  }
}
