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

var module = angular.module('commons.directives.sinoSelectOption');


/**
* title {String} 显示标题
* data {Array<Item>}  
*  Item: {
*    id: 显示主键 
*     name: 显示名称
*  }
* multiple {Boolean} 多选状态 默认单选
* spliter: {String} name 属性分割符 默认为','
* textSpliter: {String} text 属性分割符，默认为','
* name: {String} 主键name
* text: {String} 显示text 
*/
module.directive('sinoSelectOption', function(SelectOptionModal) {
  return {
    restrict: 'AE',
    templateUrl: 'views/commons/directives/sinoSelectOption.tpl.html',
    replace: true,
    scope: {
      title: '@title',
      data: '=data',
      multiple: '=multiple',
      spliter: '@spliter',
      textSpliter: '@textSpliter',
      name: '=name',
      text: '=text',
      selectAuth: '=selectAuth'
    },
    link: function(scope, $element) {
      scope.spliter = scope.spliter ? scope.spliter : ',';
      scope.textSpliter = scope.textSpliter ? scope.textSpliter : ',';
      var config = {
        scope: scope,
        title: scope.title,
        data: scope.data,
        multiple: scope.multiple,
        defaultData: scope.defaultData
      };
      if (scope.selectAuth) {
        $element.on('click', function() {
          var selectOptionModal = new SelectOptionModal(config);
          selectOptionModal.show();
        });
      }

      scope.$watch('name', function(value) {
        if (value) {
          config.defaultData = value.split(',');
        } else {
          config.defaultData = [];
        }
      });


      scope.$on('selectOption', function(event, data) {
        var name = [];
        var text = [];
        if (data) {
          _.each(data, function(value) {
            name.push(value.id);
            text.push(value.name);
          });
        } 
        scope.name = name.join(scope.spliter);
        scope.text = text.join(scope.textSpliter);
      });

      scope.$on('$destroy', function() {
        if (scope.modal) {
          scope.modal.remove();
        }
      });

      scope.$watch('selectedItem', function() {
        setFooterGroup();
      }, true);
      
      scope.selectItem =  function() {
        setFooterGroup();
      }

      function setFooterGroup() {
        scope.footerGroupConfig = {
          getItem: function() {
            var item = {};
            _.each(scope.config.data, function(value, key) {
              if (value.$$selected) {
                item[key] = value.name;
              }
            });
            return item;
          },

          updateItem: function(item) {
            _.each(scope.config.data, function(value, key) {
              if (!item[key]) {
                value.$$selected = false;
              }
            });
          }
        };
      }
    }
  };
});
