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

var module = angular.module('commons.services.selectOptionModal');

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

  /**
  * @param {object} config 配置文件
  *
  * 配置项
  * scope: {Stirng}  作用域
  * title: {String} 选择框显示名称
  * data: {Array<Item>} 显示的数据 
  *  Item对象 {id: 显示项的主键
  *       name: 显示项的名称
  *    }
  * multiple: {Boolean} 是否支持多选
  * defaultData: {Array<String>} 默认的展示数据
  * 
  * return Event selectOption
  */
  function SelectOptionModal(config) {
    this.scope = this.createScope(config);
  }

  SelectOptionModal.prototype = {
    createScope: function(config) {
      var scope = config.scope;
        scope.config = config;
      scope.close = function() {
        if (scope.modal) {
          scope.modal.hide().then(function() {
            clearSelectedItems();
          });
        }
      };

      scope.submit = function() {
        if (scope.modal) {
          scope.modal.hide().then(function() {
            scope.$emit('selectOption', getSelectedItems());
            clearSelectedItems();
          });
        }
      };

      function clearSelectedItems() {
        var i = 0, len = config.data.length, item;
        for (; i < len; i++) {
          item = config.data[i];
          delete item.$$selected;
        }
      }

      function getSelectedItems() {
        var i = 0, len = config.data.length, item, result = {};
        for (; i < len; i++) {
          item = config.data[i];
          if (item.$$selected) {
            result[item.id] = item;
          }
        }
        return result;
      }

      function setDefaultItems() {
        var defaultData = scope.config.defaultData;
        if (!defaultData || defaultData.length <= 0) {
          return;
        }
        var i = 0, len = config.data.length, item;
        for (; i < len; i++) {
          item = config.data[i];
          if (defaultData.indexOf(item.id) !== -1) {
            item.$$selected = true;
          }
        }
      }

      setDefaultItems();

      return scope;
    },

    /**
    * 弹出option选择框
    */
    show: function() {
      var deferred = $q.defer(),
        self = this;
      this.deferred = deferred;
      if (this.scope.modal) {
        this.scope.modal.show();
      } else {
        $ionicModal.fromTemplateUrl('views/commons/modal/selectoption.modal.tpl.html',{
          scope: this.scope,
          animation: 'slide-in-up'
        }).then(function(modal) {
          self.scope.modal = modal;
          deferred.resolve(modal);
          modal.show();
        }, this.deferred.reject);          
      }

      return this.deferred.promise;
    }


  };

  return SelectOptionModal;
});
