/** 按钮组件 */


var angular = require('angular'),
  _ = require('jsUtil');
require('../modules');

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

module.directive('sinoFlowButtonBar', function() {

  return {
    restrict: 'E',
    templateUrl: 'views/flow/flowButtonModule.tpl.html',
    replace: true,
    transclude: true,
    scope: {
      successFn: '&',
      authService: '=',
      sqlFn: '&'
    },
    controller: 'SinoFlowButtonBarController',
    require: 'sinoFlowButtonBar',
    compile: function() {
      return {
        pre: function preLink(scope, iElement, iAttrs, controller) {
          controller.init();
        },
        post: function postLink(scope, iElement, iAttrs, controller) {
        }
      }
    }
  };
})
.controller('SinoFlowButtonBarController', function($scope, $element, $attrs,
  FlowButtonService, $q, $toast, $window, $parse, DefaultWorkflowParam, CoreAppConfig) {
  var self = this,
    flowButtonService,
    getButtonFns = [],
    tempNotions = [];

  self.name = $attrs.name;
  var appId = CoreAppConfig.getAppId();
  
  $scope.customize = appId === 'gjjoa';

  self.init = init;
  self.button = button;
  self.setTempNotions = setTempNotions;
  self.getTempNotions = getTempNotions;
  self.getAttr = getAttr;
  self.successCallFnInAlert = successCallFnInAlert;
  self.getActiveButtonLocals = getActiveButtonLocals;
  self.updateSubflag = updateSubflag;

  function init() {
    applySuccessFn();
    setWorkflowParam();
    flowButtonService = new FlowButtonService();
    flowButtonService.refreshButtons();
  };

  function applySuccessFn() {
    self.successFn = function(obj) {
      return $q.when($scope.successFn(getActiveButtonLocals()));
    }
  }

  $scope.selectMore = function() {
    if ($scope.moreFlag) {
      $scope.moreFlag = false;
    } else {
      $scope.moreFlag = true;
    }
  };

  function refresh() {
    flowButtonService.clear();
    _.each(getButtonFns, function(getButtonFn) {
      flowButtonService.addButton(getButtonFn());
    });
  }


  $scope.$watch(function() {
    return flowButtonService.showButtons;
  }, function(buttons) {
    $scope.buttons = flowButtonService.showButtons;
    $scope.moreButton = flowButtonService.moreButton;
  });

  $scope.$watch('authService', function(service) {
    if (service) {
      refresh();
      if(service && service.evection && service.evection.evectionId) {
        DefaultWorkflowParam.setParam("recordId", service.evection.evectionId);
      }
       if(service && service.nxjQj && service.nxjQj.id) {
        DefaultWorkflowParam.setParam("recordId", service.nxjQj.id);
      }
    }
  });

  $scope.$on('$destroy', function() {
    $window.document.body.removeEventListener('click', clickMore);
  });

  $window.document.body.addEventListener('click', clickMore, false);

  function clickMore() {
    $scope.$evalAsync(function() {
      $scope.moreFlag = false;
    });
  }

  /**
    获取按钮
   */
  function button(buttonFn) {
    getButtonFns.push(getButtonFnProxy(buttonFn));
  };


  var notEmitAction = ['send', 'finish', 'transfer', 'notApprove', 'approve']; // 不需要发布事件的操作
  function getButtonFnProxy(buttonFn) {
    var _ButtonFn = function() {
      var buttonConfig = buttonFn(),
        _buttonConfig = _.clone(buttonConfig);
        _buttonConfig.onClick = function() {
          self.activeButton = buttonConfig.name;
          $q.when(buttonConfig.onClick()).then(function() {
            var action = buttonConfig.id || buttonConfig.name;
            if (notEmitAction.indexOf(action) === -1) {
              $scope.$emit('sino.flow.action', action);
            }
          });
        }
      return _buttonConfig;
    }
    return _ButtonFn;
  }

  /**
   *  设置临时意见
   */
  function setTempNotions(_tempNotions) {
    tempNotions = _tempNotions
  }

  /**
   * 获取临时意见
   */
  function getTempNotions() {
    return tempNotions;
  }

  /**
   * 获取参数
   */
  function getAttr(attrs, name, defaultValue) {
    if (name === 'sqlFn') {
      return $attrs.sqlFn? ($scope.sqlFn() || defaultValue) : defaultValue;
    }
    return attrs[name] || $attrs[name] || defaultValue;
  }

  function successCallFnInAlert(promise, tag) {
    return promise.then(function(data) {
      if(data.success) {
        return self.successFn().then(function() {
          $toast.showShortCenter(tag + '成功。');
        });
      } else {
        $toast.showShortCenter(tag + '失败。');
      }
    }, function(data) {
      $toast.showShortCenter(tag + '失败，请检查网络连接。');
    });
  }

  function getActiveButtonLocals() {
      var locals = {}
      if (self.name && self.activeButton) {
        locals[self.name] = {
          activeButton: self.activeButton
        };
      }
      return locals;
  }

  function updateSubflag(scope, attrs, value) {
    var attr = getAttr(attrs, 'subflag');
    if (attr && value) {
      var setter = $parse(attr).assign;
      setter(scope, value);
    }
  }

  function setWorkflowParam() {
    var workflowParam = {
      flowType: getAttr($attrs, 'flowType'),
      recordId: getAttr($attrs, 'recordId'),
      title: getAttr($attrs, 'title'),
      tempNotions: getTempNotions(),
      settime: getAttr($attrs, 'setTime'),
      tableName: getAttr($attrs, 'tableName'),
      tableId: getAttr($attrs, 'tableId')
    };

    DefaultWorkflowParam.set(workflowParam);
  }
});
