var angular = require('angular');
require('../services/TreeDeptUserService');
require('../modules');
require('../../linker/services/userList');
require('../../../commons/directives/sinoLoadingHint');
var _ = require('jsUtil');

var module = angular.module('tree');

module.controller('TreeCtrl', function($scope, $ionicScrollDelegate, 
  TreeDeptUserService, userList, $timeout, linkerConfig) {
  var treeDeptUserService = new TreeDeptUserService($scope.treeConfig);
  var currentLoadingDept = null,
    positions = {};
  $scope.selectedIds = []; // 被选中的项
  $scope.loadingState = 1;

  function init() {
    if ($scope.treeConfig.selectType.user) {
      $scope.selectedIds = $scope.treeConfig.default.userIds || [];
    }
    if ($scope.treeConfig.selectType.dept) {
      $scope.selectedIds = $scope.treeConfig.default.deptIds || [];
    }
    setFooterGroup();
  }
  init();

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

  /**
   * 获取人员部门列表
   */
  var getUserTree = function(deptId) {
    try {
      $timeout(function() {
        currentLoadingDept = deptId;
        var dept = treeDeptUserService.getSubUserDept(deptId);
        if (currentLoadingDept !== dept.deptId || !isNotEmptyDept(dept)) {
          return;
        }
        $scope.currentDept = dept;
        $scope.loadingState = 2;
        addDeptNav(dept);
        
        $ionicScrollDelegate.$getByHandle('deptuserTreeScrollView')
          .scrollTo(0, positions[deptId] || 0);
      });
    } catch(e) {
      $scope.loadingstate = 3;
      $scope.currentDept = {
        deptId: deptId
      };
    }
  };

  function isNotEmptyDept(dept) {
    return dept && ((dept.users && dept.users.length > 0) || (dept.depts && dept.depts.length > 0));
  }

  $scope.canSelectDept = function(node) {
    return treeDeptUserService.notTreeDeptIds.indexOf('|' + node.deptId + '|') === -1;
  };

  $scope.canSelectUser = function(node) {
    return treeDeptUserService.notTreeUserIds.indexOf('|' + node.userId + '|') === -1;
  };

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

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

  /* 选择checkBox的方法 */
  $scope.select = function(node, id) {
    selectBox(node, id);
    $scope.$emit('selectNode', getSelectedNodes());
  };

  function selectBox(node, id) {
    $scope.treeConfig.default.userIds = [];
    $scope.treeConfig.default.deptIds = [];
    var selectIndex = $scope.selectedIds.indexOf(id);
    if (selectIndex > -1) {
      delete $scope.selectedIds.splice(selectIndex, 1);
    } else {
      if (!$scope.treeConfig.moreSelect) {
        $scope.selectedIds.splice(0);
      }
      $scope.selectedIds.push(id)
    }
    setFooterGroup();
  }

  function setFooterGroup() {
    $scope.footerGroupConfig = {
      getItem: function() {
        var item = {};
        _.each(getSelectedNodes(), function(node, key) {
          if ($scope.treeConfig.selectType.user) {
            item[key] = node.userName;
          }
          if ($scope.treeConfig.selectType.dept) {
            item[key] = node.deptName;
          }
        });
        return item;
      },

      updateItem: function(item) {
        $scope.selectedIds = _.filter($scope.selectedIds, function(id, key) {
          return item[id];
        });
        $scope.$emit('selectNode', getSelectedNodes());
      }
    };
  }

  function getSelectedNodes() {
    var selectNodes = [];
    if (!$scope.selectedIds) { return selectNodes; }
    if ($scope.treeConfig.selectType.user) {
      selectNodes = userList.getUserSync($scope.selectedIds);
    }
    if ($scope.treeConfig.selectType.dept) {
      selectNodes = userList.getDeptSync($scope.selectedIds);
    }
    return nodesToNodeObject(selectNodes);
  }

  function nodesToNodeObject(nodes) {
    var nodeObject = {};
    if (!_.isArray(nodes)) { return nodeObject; }
    _.each(nodes, function(node) {
      if ($scope.treeConfig.selectType.user) {
        nodeObject[node.userId] = node;
      }
      if ($scope.treeConfig.selectType.dept) {
        nodeObject[node.deptId] = node;
      }
    });
    return nodeObject;
  }

  getUserTree(linkerConfig.topDeptId);
});
