/** 保存按钮 */


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

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

/**
  <sino-flow-save-button
    save-fn="save()" 保存方法
    show="" 显示权限 false
  before-valid-fn="valid()" 验证方法
  name="" 名称
  >
  </sino-flow-save-button>
 */
module.directive('sinoFlowSaveButton', function($q, $toast) {
  
  return {
    restrict: 'E',
    require: '^sinoFlowButtonBar',
    link: function(scope, element, attrs, ctrl) {
      ctrl.save = save;
      
      ctrl.button(function() {
        return {
          id: 'save',
          name: attrs.name,
          show: attrs.show ? scope.$eval(attrs.show) : true,
          onClick: function() {
            return save().then(function(data) {
              $toast.showShortCenter('保存成功');
            }, function(data) {
              if (data !== 'validError') {
                $toast.showShortCenter('保存失败');
              }
            });
          }
        }
      });
      
      function save() {
        var deferred = $q.defer();
        if (attrs.beforeValidFn && !scope.$eval(attrs.beforeValidFn)) {
          deferred.reject('validError');
        } else {
          $q.when(scope.$eval(attrs.saveFn, ctrl.getActiveButtonLocals())).then(deferred.resolve, deferred.reject);
        }
        return deferred.promise;
      };
    }
  }
});
