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

module.controller('LinkerTreeCtrl', function($scope, Timer,
  $ionicScrollDelegate, LinkerTreeService, type, $state, userDeptList,
  linkerConfig, CoreAppConfig) {

  var deptNavs = $scope.deptNavs = [],
    currentLoadingDept = null,
    positions = {};
  $scope.loadingError = false;
  $scope.load = false;
  $scope.refreshing = false;

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

  $scope.$on('$ionicView.afterLeave', function() {
    deptNavs = $scope.deptNavs = [];
    currentLoadingDept = linkerConfig.topDeptId;
    positions = {};
  });

  function addDeptNav(node) {
    var deptId = node.deptId || node.id,
      deptNavsCount = deptNavs.length,
      prevDept = deptNavsCount > 0? deptNavs[deptNavsCount - 1] : null,
      prevDeptId = prevDept? prevDept.deptId || prevDept.deptId : null;
    node.text = node.deptName;
    if (deptId === linkerConfig.topDeptId) {
      $scope.topDept = node;
    } else if (prevDeptId !== deptId) {
      deptNavs.push(node);
    }
  }

  /**
   * 获取人员部门列表
   */
  var getUserTree = function(deptId) {
    currentLoadingDept = deptId;

    var taskId = Timer.delay(function() {
      $scope.loading = true;
    }, 200);

    return LinkerTreeService.getSubUserDept(deptId, {type: type})
    .then(function(dept) {
      if (currentLoadingDept !== dept.deptId) {
        return;
      }

      $scope.currentDept = filterJuUser(dept);;

      addDeptNav(dept);

      $ionicScrollDelegate.$getByHandle('deptuserTreeScrollView').scrollTo(0, positions[deptId] || 0);
      $scope.loadingError = false;
    }, function() {
      $scope.loadingError = true;
      $scope.currentDept = {
        deptId: deptId
      };
    })['finally'](function() {
      Timer.clear(taskId);
      $scope.loading = false;
    });
  };

  $scope.getDetail  = function(node) {
    getUserTree(node.deptId);
  };

  $scope.onScroll = function(scrollTop) {
    var deptId = $scope.currentDept.deptId || $scope.currentDept.deptId;
    positions[deptId] = scrollTop;
  };

  $scope.reloading = function() {
    return userDeptList.refresh().then(function() {
      getUserTree(currentLoadingDept);
    });
  };

  $scope.$watch(function() {
    var currentDept = $scope.currentDept;
    $scope.hasData = currentDept && ((currentDept.users && currentDept.users.length > 0) ||
      (currentDept.depts && currentDept.depts.length > 0));
    return $scope.hasData;
  });

  $scope.refresh = function() {
    $scope.refreshing = true;
    return userDeptList.sync().then(function() {
      getUserTree(currentLoadingDept).then(function() {
        Timer.delay(function() {
          $scope.refreshing = false;
        }, 500);
      });
    });
  };

  getUserTree(linkerConfig.topDeptId);

  /**
   * 国家局不显示局领导
   */
  function filterJuUser(dept) {
    var appId = CoreAppConfig.getAppId();
    if(!dept.users || appId !== 'gjjoa') {return dept;}

    var _users = [], user, re, deptIds = [];
    for(var i = 0, len = dept.users.length; i < len; i++) {
      user = dept.users[i];
      deptIds = user.deptId.split(',');//一人多岗
      re = _.find(deptIds, function(deptId) {
        return deptId === '001';
      });
      if(!re){
        _users.push(user);
      }
    }
    dept.users = _users;
    return dept;

  }
});
