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

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

module.directive('sinoCommonnotionSelectButton', function(CommonService, $ionicModal) {
  return {
    restrict: 'E',
    template: '<button>{{buttonTitle}}</button>',
    replace: true,
    scope: {
      onSelect: '&'
    },
    link: function(scope, element, attrs) {
      var $childScope = scope.$new();
      var modal,
        notion;
      scope.buttonTitle = attrs.title || '选择常用意见';

      var notionUrl = 'views/flow/commonNotionSelectButton.tpl.html';
      $ionicModal.fromTemplateUrl(notionUrl, {
        scope: $childScope
      }).then(function(_modal){
        modal = _modal;
      });

      $childScope.onOkBtnClick = function() {
        scope.onSelect({notion: notion});
        modal.hide();
      };

      $childScope.close = function() {
        modal.hide();
      };

      $childScope.onNotionSelect = function(_notion) {
        notion = _notion;
      };

      element.on('click', function() {
        scope.$evalAsync(function() {
          modal.show();
        });
      });

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

    }
  }
});
