var angular = require('angular');
require('../modules');
require('../../../commons/services/CommonService');
require('../../../commons/services/Timer');

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

var selectors = {
  'selectdept': {
    templateUrl: 'views/flow/sendFlow.tpl.html',
    attributeName: 'wfoperationMap'
  },
  'flowinstance': {
    templateUrl: 'views/flow/flowStaffList.tpl.html',
    attributeName: 'deptUserMap'
  },
  'selectoption': {
    templateUrl: 'views/flow/flowRoles.tpl.html',
    attributeName: 'wfleveid'
  },
  'selectJob': {
    templateUrl: 'views/flow/selectJob.tpl.html',
    attributeName: 'deptid'
  }
};

module.factory('SelectorModal', function($rootScope, $q, CommonService) {

  function SelectorModal(workflowResponse) {
    this.workflowResponse = workflowResponse;
    this.$scope = this.createSelectorModalScope();
    this.config = selectors[workflowResponse.flag];
  }

  SelectorModal.prototype = {
    createSelectorModalScope: function() {
      var self = this,
        $scope = $rootScope.$new();

      $scope.onSelected = function(cancel) {
        if (cancel) {
          self.deferred.resolve('cancel');
          self.modal.remove();
          return;
        }
        if (self.workflowResponse[self.config.attributeName]) {
          self.deferred.resolve(self.workflowResponse);
        } else {
          self.deferred.reject();
        }
        return self.deferred.promise;
      };

      $scope.data = this.workflowResponse;
      return $scope;
    },

    /**
     * 显示选择modal。
     * @return {Promise}
     */
    show: function() {
      var self = this,
        deferred = $q.defer();
      this.deferred = deferred;
      CommonService.createModal(this.config.templateUrl, this.$scope, true)
      .then(function(modal) {
        self.modal = modal;
        modal.show();
      }, deferred.reject);

      return deferred.promise;
    }
  };

  return SelectorModal;
});
