/** 发送按钮 */


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

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

/**
  <sino-flow-base-send-button
   transferflag="" 是否转办, 是1, 不是0
   button-id="" id名称
   name="" 发送名称
   set-time="" 紧急停止时间
   before-valid-fn="" 发送之前的验证
   valid-error-text="" 验证的错误提示
   ></sino-flow-base-send-button>
 */
module.directive('sinoFlowBaseSendButton', function(DefaultWorkflowService, $toast, $q, $timeout,
    DefaultWorkflowParam, OpenQzNotionService) {
  return {
    restrict: 'E',
    require: '^sinoFlowButtonBar',
    link: function(scope, element, attrs, ctrl) {

      ctrl.button(function() {
        return {
          id: attrs.buttonId,
          name: attrs.name,
          title: attrs.text,
          show: attrs.show ? scope.$eval(attrs.show) : true,
          onClick: send,
          warrant: true,
        };
      });

      function send() {
        if (attrs.beforeValidSend && !scope.$eval(attrs.beforeValidSend)) {
          $toast.showLongCenter(attrs.validErrorText || '验证失败！');
          return;
        }

        return sendWorkFlow();
      }

      function sendWorkFlow() {
        var save = ctrl.save || function() {};
        var deferred = $q.defer();
        setRequestParam();

        $q.when(save()).then(function(data) {
          // 页面渲染完毕发送
          return $timeout(function() {
            return DefaultWorkflowService.send(DefaultWorkflowParam.get())
              .then(function(data) {
              if (data !== 'cancel') {
                ctrl.updateSubflag(scope, attrs, '1');
                scope.$emit('sino.flow.action', attrs.buttonId || attrs.name);
                deferred.resolve(ctrl.successFn());
              } else {
                deferred.reject();
              }
            });
          });
        }, deferred.reject);

        return deferred.promise;
      }

      function setRequestParam() {
        DefaultWorkflowParam.get().needSign = ctrl.getAttr(attrs, 'needSign') === 'false' ? false : true;
        DefaultWorkflowParam.get().transferflag = attrs.transferflag;
        DefaultWorkflowParam.get().tempNotions = ctrl.getTempNotions();
        DefaultWorkflowParam.get().settime = ctrl.getAttr(attrs, 'setTime');
        DefaultWorkflowParam.get().title = ctrl.getAttr(attrs, 'title');
        DefaultWorkflowParam.get().sql = ctrl.getAttr(attrs, 'sqlFn');
        DefaultWorkflowParam.get().okButton = '下一步';
        DefaultWorkflowParam.get().successFn = send;
        DefaultWorkflowParam.get().onStateChange = function(state) {
          switch(state) {
            case 'needWriteNotion':
              OpenQzNotionService.openRequireNotion(DefaultWorkflowParam.get());
              break;
            case 'generateWorkflowRequest':
              break;
          }
        }
      }
    }
  };
});
