var angular = require('angular');
require('../modules');
require('../../tree/app');
require('ngIonic');
var module = angular.module('linker.directives');

/**
 * sino-dept-select指令用来让用户可以选择部门。
 * 
 * 示例：
 *
 * ```
 * <sino-dept-select
 *   modal-title="选择会签单位"
 *   ng-modal="modal.deptIds"
 *   dept-name="deptNames"
 *   multiple
 *   ng-readonly="readonly"
 *   top-dept-id="001"
 *   filterFn="filterDept(dept, superDepts)">
 * </sino-dept-select>
 * ```
 * 
 * 属性：
 *
 * * ***modal-title***: 部门选择框头部的标题
 * * ***ng-modal***: 指定与所选部门的deptId关联的表达式
 * * ***dept-name***: 指定与所选部门的deptName关联的表达式
 * * ***filter-fn***: 指定过滤部门树的过滤器函数。不指定filterFn，则显示整棵部门树。组件内部会调用此函数用来判断哪些部门可以选择，函数可以接受两个参数，即dept代表过滤的部门，superDepts代表所有的父级部门。
 * * ***ng-readonly***: 指定该表单控件是否为只读的。在只读状态下，不可修改选中的部门。
 * * ***top-dept-id***: 指定部门树最顶级的部门id。默认为001。
 * * ***multiple***: 指定该表单选择控件是否为多选。如果是多选，则可以选择多个部门。默认为单选。
 * 
 */
module.directive('sinoDeptSelect', function($ionicModal, $parse, linkerConfig) {
  return {
    restrict: 'E',
    template: '<div class="sino-dept-select">' +
      '<p class="sino-dept-select-content">' +
        '{{deptName}}<select ng-focus="openSelectDeptModal()" style="display:none;"></select>' +
      '</p>' +
      '<i class="icon ion-ios-person-outline"></i>' +
    '</div>',
    require: '?ngModel',
    replace: true,
    scope: {
      deptName: '=?',
      filterFn: '&'
    },
    link: function(scope, element, attrs, ngModelCtrl) {
      if (!ngModelCtrl) {
        return;
      }
      var modalOpening = false;

      function isMultiple() {
        var config = attrs.multiple;
        return attrs.hasOwnProperty('multiple') &&
          config !== 'false' && config != '0';
      }

      function createOpenDeptTreeConfig() {
        var modelValue = ngModelCtrl.$modelValue,
          filterFn = attrs.filterFn? function(dept, superDepts) {
            return scope.filterFn({
              dept: dept,
              superDepts: superDepts
            });
          } : function() {
            return true;
          },
          deptIds = modelValue && modelValue.substring?
            modelValue.split(',') : modelValue;

        var config = {
          modalTitle: attrs.modalTitle,
          topDeptId: attrs.topDeptId || linkerConfig.topDeptId,
          type: 'dept',
          moreSelect: isMultiple(),
          selectType: {
            'user': false,
            'dept': true
          },'default': {
            'deptIds': deptIds
          },
          filterFn: filterFn
        };
        return config;
      }

      function createModalScope() {
        var modalScope = scope.$new();
        modalScope.treeConfig = createOpenDeptTreeConfig();
        modalScope.close = function() {
          if (modalScope.modal) {
            modalScope.modal.hide();
            modalScope.modal.remove();
          }
          modalOpening = false;
        };

        modalScope.$on('$destroy', function() {
          modalScope.close();
        });

        modalScope.$on('selectNode', function(event, depts) {
          var ids = [],
            names = [];

          for (var deptId in depts) {
            if (depts.hasOwnProperty(deptId)) {
              ids.push(deptId);
              names.push(depts[deptId].deptName);
            }
          }
          ngModelCtrl.$setViewValue(ids.join(','));
          scope.deptName = names.join(',');
          event.stopPropagation();
        });

        return modalScope;
      }

      scope.openSelectDeptModal = function() {
        if (attrs.readonly || modalOpening) {
          return;
        }
        modalOpening = true;
        var modalScope = createModalScope();
        $ionicModal.fromTemplateUrl('views/tree/modal/treeModule.tpl.html', {
          scope: modalScope,
          animation: 'slide-in-up'
        }).then(function(modal) {
          modalScope.modal = modal;
          modal.show();
        });
      };

      element.on('click', function() {
        scope.openSelectDeptModal();
      });
    }
  };
});
