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

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

module.directive('sinoViewNotionButton', function(CommonService, $ionicModal) {
  return {
    restrict: 'E',
    template: '<button>{{buttonTitle}}</button>',
    replace: true,
    scope: true,
    link: function(scope, element, attrs) {
      scope.buttonTitle = attrs.title || '查看意见';

      var $childScope = scope.$new();
      var modal;

      function showModal() {
        if (modal) {
          modal.remove();
        }
        var templateUrl = 'views/flow/viewNotionButton.tpl.html';
        return $ionicModal.fromTemplateUrl(templateUrl, {
          scope: $childScope
        }).then(function(_modal) {
          modal = _modal;
          modal.show();
        });
      }

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

      $childScope.orderBy = function(orderBy) {
        $childScope.sortType = orderBy;
      };

      /**
       * 关闭下拉列表
       */
      $childScope.closeDropDown = function() {
        if ($childScope.dropdown) {
          $childScope.dropdown = !$childScope.dropdown;
        }
      };

      $childScope.changeDropDown = function() {
        $childScope.dropdown = !$childScope.dropdown;
      };

      element.on('click', function() {
        scope.$evalAsync(function() {
          $childScope.flowType = attrs.flowType;
          $childScope.recordId = attrs.recordId;
          showModal();
        });
      });

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

    }
  }
});
