/* 结束流程按钮 */


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

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

/**
  <sino-flow-base-finish-button
    name="" id 名称
    tag="" tag提示语
    subflag="" 流程类型>
  </sino-flow-base-finish-button>
 */
module.directive('sinoFlowBaseFinishButton', function(DefaultWorkflowService, $toast) {
  
  return {
    restrict: 'E',
    require: '^sinoFlowButtonBar',
    link: function(scope, element, attrs, ctrl) {
      ctrl.button(function() {
        return {
          id: attrs.buttonId,
          name: attrs.name,
          show: attrs.show ? scope.$eval(attrs.show) : true,
          title: attrs.text,
          warrant: true,
          onClick: function() {
            var requestParam = {
              flowType: ctrl.getAttr(attrs, 'flowType'),
              recordId: ctrl.getAttr(attrs, 'recordId'),
              subflag: attrs.subflagValue,
              flag: attrs.flag || '0',
              tempNotions: ctrl.getTempNotions(),
              onStateChange: function(state) {
                switch(state) {
                  case 'needWriteNotion':
                    $toast.showLongCenter('请先填写意见');
                    ctrl.openNotion();
                    break;
                  case 'generateWorkflowRequest':
                    break;
                }
              },
              title: ctrl.getAttr(attrs, 'title')
            }
            
            var promise = DefaultWorkflowService.finish(requestParam).then(function(data) {
              ctrl.updateSubflag(scope, attrs, attrs.subflagValue);
              scope.$emit('sino.flow.action', attrs.buttonId || attrs.name);
              return data;
            });
            return successCallFnInAlert(promise, attrs.tag, ctrl.successFn);
          }
        };
      });
    } 
  };
      
      
  function successCallFnInAlert(promise, tag, successFn) {
    return promise.then(function(data) {
      if(data.success) {
        return successFn().then(function() {
          $toast.showShortCenter(tag + '成功。');
        });
      } else {
        $toast.showShortCenter(tag + '失败。');
      }
    }, function(data) {
      if(data.message !== '1') {
         $toast.showShortCenter(tag + '失败，请检查网络连接。');
      }
    });
  }
});
