var angular = require('angular'),
  _ = require('jsUtil');
require('../modules');
require('../../flow/services/WorkflowTransfer');
require('./DefaultWorkflowRequest');
require('../../linker/services/LinkerService');
require('../../flow/services/NotionService');

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

module.factory('DefaultWorkflowService', function(WorkflowTransfer, DefaultWorkflowRequest, LinkerService,
  NotionService) {
  return {
    finish: finish,
    send: send
  };

  function finish(requestParam) {
    setNotionParam(requestParam);
    var workflowRequest = DefaultWorkflowRequest.generateFinishWorkflowRequest(requestParam);
    requestParam.onStateChange('generateWorkflowRequest');
    return WorkflowTransfer.finish(workflowRequest);
  }

  function send(requestParam) {
    setNotionParam(requestParam);
    var workflowRequest = DefaultWorkflowRequest.generateWorkflowRequest(requestParam, requestParam.transferflag,
      requestParam.contents);

    workflowRequest = updateSign(workflowRequest);

    requestParam.onStateChange('generateWorkflowRequest');
    return WorkflowTransfer.send(workflowRequest);
  }

  /**
   * 如果没有填写意见（没有写意见并且意见内容不是TRUE）,则将签字去掉
   * 
   * @param {any} request 
   * @returns 
   */
  function updateSign(request) {
    if(_.isEmpty(request.idea.replace(/\^#\^/g, ''))) {
      request.sign = 'FALSE';
    }
    return request;
  }

  function setNotionParam(requestParam) {
    requestParam.contents = requestParam.tempNotions.map(function(tempNotion) {
      if (tempNotion.requireFn()) {
        if (_.isEmpty(tempNotion.content) && (!tempNotion.tempSign)) {
          requestParam.onStateChange('needWriteNotion');
          throw new Error('1');//需要填写意见
        }
      }
      return tempNotion.content;
    });
  }
});
