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

angular
  .module('linker')
  .controller('SelfDeptCtrl', SelfDeptCtrl);

/** @ngInject */
function SelfDeptCtrl($scope, LinkerTreeDirectService,
  Timer, LinkerService, type, $q, linkerConfig) {
  var ctrl = this,
    currentLoadingDept = null, // 当前正在加载的部门
    myTopDept = { //模拟的顶级部门
      deptId: '000',
      deptName: '我的部门'
    };


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

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

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

  function init() {
    return getCurrentUserDept().then(function(currentUserOfDept) {
      if(currentUserOfDept.length === 1) { // 非一人多岗
        ctrl.topDeptId = currentUserOfDept[0].deptId;
        return fetchUserAndDept(currentUserOfDept[0].deptId);
      } else { // 一人多岗
        ctrl.dept = formCurrentUserAndDept(currentUserOfDept);
        ctrl.topDeptId = myTopDept.deptId;
      }
    });
  }

  //获取当前登录人的所属的部门
  function getCurrentUserDept() {
    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;
      });
      ctrl.loadingState = currentUser.length > 0 || currentUser.length > 0? 2 : 4;

      return sort(allItems);
    }, function() {
      ctrl.loadingState = 3;
    });
  }

  // 当前登录人的子部门的排序，部门id小的在前面
  function sort(depts) {
    return depts.sort(function(a,b) {
      if(a.deptId < b.deptId) {
        return -1;
      }else if(a.deptId == b.deptId) {
        return 0;
      }else {
        return 1;
      }
    });
  }

  // 根据当前人的一人多岗，来拼部门
  function formCurrentUserAndDept(currentUserOfDept) {
    var _myTopDept = myTopDept;
    _myTopDept.depts = [];
    _.each(currentUserOfDept, function(dept) {
      _myTopDept.depts.push(dept);
    });

    ctrl.loadingState = 2;
    return _myTopDept;
  }


  function fetchUserAndDept(deptId) {
    deptId = deptId || currentLoadingDept || myTopDept.deptId;
    currentLoadingDept = deptId;
    if(!ctrl.refreshing) {
      ctrl.loadingState = 1;
    }
    if(deptId === myTopDept.deptId) { // 返回“我的部门”
      return init();
    }
    return LinkerTreeDirectService.getSubUserDept(deptId, {type: type}) .then(function(dept) {
      if (currentLoadingDept !== deptId) { return; }
      ctrl.currenrtDept = filter(dept);
      ctrl.dept = dept;
      ctrl.loadingState = dept.users.length > 0 || dept.depts.length > 0? 2 : 4;
      }, function() {//必须是最新的数据才要，不是最新的，丢弃
      if (currentLoadingDept === deptId) {
        ctrl.loadingState = 3;
      }
    });
  }

  // 如果子部门是顶级部门的话，那么过来掉子部门
  function filter(dept) {
    if(dept.deptId === linkerConfig.topDeptId) {
      dept.depts = [];
    }
    return dept;
  }

  /**
   * 进入子部门
   */
  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);
    });
  }
}
