var angular = require('angular');
require('../modules');

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

module.factory('TreeService', function($ionicModal, $q) {

  /**
  * 人员部门树的服务类
  *
  * @param scope {Object<$scope>} 作用于对象，该人员部门树作用的页面对象
  * @param treeConfig {Object<TreeConfig>}  人员部门树配置对象
  *
  * TreeConfig : {
  *    modalTitle: 人员部门树页面head显示信息
  *     topDeptId: '顶级部门'  默认'001'
  *    type: 'user',  部门人员树 user-人员树, dept-部门树
  *    moreSelect: false, 是否多选
  *    selectType: { //暂时只能选择user或者dept
  *      'user': true, '是否可以选择人员'
  *      'dept': false  '是否可以选择部门'
  *    },
  *    default: {
  *      'userIds': [],
  *      'deptIds': []
  *    },
  *    filterFn: {Function} 过滤函数, 若果是selectType 是user 回调函数中有user, supDepts,
  *       如果是selectTyope是dept， 回调函数，supDepts
  *      
  *  }
  */
  function TreeService(treeConfig, scope) {
    if(!treeConfig.filterFn) {
      treeConfig.filterFn = function() { return true; };
    }
    this.treeConfig = treeConfig;
    this.$scope = this.createTreeScope(treeConfig, scope);
  }

  TreeService.prototype = {
    createTreeScope: function(config, scope) {
      scope.treeConfig = config;

      scope.close = function() {
        if (scope.modal) {
          scope.modal.remove();
        }
      };

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

      return scope;
    },

    /**
    * 弹出部门人员树
    */
    show: function() {
      var deferred = $q.defer(),
        self = this;
      this.deferred = deferred;
      $ionicModal.fromTemplateUrl('views/tree/modal/treeModule.tpl.html',{
        scope: this.$scope,
        animation: 'slide-in-up'
      }).then(function(modal) {
        self.$scope.modal = modal;
        modal.show();
      }, this.deferred.reject);

      return this.deferred.promise;
    }
  };

  return TreeService;
});
