var angular = require('angular');
require('../modules');
require('../services/Timer');
require('../services/sinoClickService');
require('../../modules/warrant/services/WarrantService');
var module = angular.module('commons.directives.sinoclick');

module.directive('sinoClick', function(Timer, $ionicLoading, sinoClickService, $ionicPopup, $q,
  WarrantService, $timeout) {
  return {
    restrict: 'A',
    scope: {
      onClick: '&sinoClick'
    },
    link: function($scope, $element, $attr) {
      var doing = false,
        clickDoing = false,
        taskId = null;
      $element.on('click', function($event) {
        if (doing || clickDoing) {
            return;
          }
          clickDoing = true;
          confirmOutDeadline().then(function() {
            return confirm();
          }).then(function (res) {
            if (res) {
              onClick($event);
            } else {
              clickDoing = false;
            }
          }, function() {
            clickDoing = false;
          });
      });

      function confirmOutDeadline() {
        if ($attr.warrant && $attr.warrant === 'true') {
          return WarrantService.getIsOutDeadline().then(function (warrant) {
            if (warrant) {
              $ionicLoading.show({
                template: '试用期已过，无法使用此操作！'
              });
              $timeout(function () {
                $ionicLoading.hide();
              }, 2000);

              throw new Error('已过期，无法执行此操作');
            }
            return !warrant;
          });
        } else {
          return $q.when(true);
        }
      }

      function confirm() {
        var confirmPromise;
        if ($attr.confirm && $attr.confirm === 'true') {
          confirmPromise = $ionicPopup.confirm({
            title: $attr.confirmTitle ? $attr.confirmTitle : '操作',
            content: $attr.confirmContent ? $attr.confirmContent : '是否继续?',
            okText: $attr.confirmOkText ?  $attr.confirmOkText : '继续',
            cancelText: $attr.confirmCancelText ? $attr.confirmCancelText : '放弃'
          });
        } else {
          confirmPromise = $q.when(true);
        }
        return confirmPromise;
      }

      function onClick($event) {
        $scope.$evalAsync(function() {
          var promise = $scope.onClick({$event: $event}),
            isPromise = promise && promise.then,
            needExec = isPromise && !doing;
          clickDoing = false;
          if (isPromise) {
            doing = true;
          }

          if (needExec) {
            taskId = Timer.delay(function() {
              $ionicLoading.show({
                template: $attr.sinoClickTitle || '正在处理中，请等待...'
              });
            }, 250);
            sinoClickService.setCurrentTask(taskId);
            promise.finally(function() {
              $ionicLoading.hide();
              sinoClickService.clearCurrentTask();
              doing = false;
            });
          }
        });
      }
    }
  };
});
