package com.artfess.bpm.plugin.task.startnewflow.plugin;

import com.artfess.base.util.AppUtil;
import com.artfess.base.util.StringUtil;
import com.artfess.bpm.api.cmd.TaskFinishCmd;
import com.artfess.bpm.api.constant.BpmConstants;
import com.artfess.bpm.api.constant.EventType;
import com.artfess.bpm.api.constant.NodeType;
import com.artfess.bpm.api.context.ContextThreadUtil;
import com.artfess.bpm.api.event.StartNewFlowEvent;
import com.artfess.bpm.api.model.process.nodedef.BpmNodeDef;
import com.artfess.bpm.api.plugin.core.def.BpmTaskPluginDef;
import com.artfess.bpm.api.plugin.core.session.BpmTaskPluginSession;
import com.artfess.bpm.api.service.BpmDefinitionAccessor;
import com.artfess.bpm.persistence.model.DefaultBpmProcessInstance;
import com.artfess.bpm.plugin.core.runtime.AbstractBpmTaskPlugin;

import javax.annotation.Resource;

/**
 * 触发新流程运行插件
 * @author co
 *
 */
public class StartNewFlowPlugin extends AbstractBpmTaskPlugin{

	@Resource
	BpmDefinitionAccessor bpmDefinitionAccessor;

	@Override
	public Void execute(BpmTaskPluginSession pluginSession,BpmTaskPluginDef pluginDef) throws Exception {
		if(pluginSession.getEventType()!=EventType.TASK_COMPLETE_EVENT){
			return null;
		}
		TaskFinishCmd taskFinishCmd=(TaskFinishCmd)ContextThreadUtil.getActionCmd();
		String skipType = (String) taskFinishCmd.getTransitVars(BpmConstants.BPM_SKIP_TYPE);
		if (StringUtil.isNotEmpty(skipType)) {
			return null;
		}
		DefaultBpmProcessInstance instance  =(DefaultBpmProcessInstance) taskFinishCmd.getTransitVars(BpmConstants.PROCESS_INST);
		//此处需要调用runtime模块的启动方法，故此处发布事件，在runtime模块执行具体逻辑。
		BpmNodeDef bpmNodeDef = bpmDefinitionAccessor.getBpmNodeDef(instance.getProcDefId(), pluginSession.getBpmDelegateTask().getTaskDefinitionKey());
		if (!NodeType.SIGNTASK.equals(bpmNodeDef.getType())) {
			StartNewFlowEvent event = new StartNewFlowEvent(bpmNodeDef);
			AppUtil.publishEvent(event);
		}

		return null;
	}



}
