package com.blueland.bpm.engine.core.executor;

import java.util.HashMap;
import java.util.Map;

import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Service;

import com.blueland.bpm.common.util.StringUtils;
import com.blueland.bpm.engine.core.cmd.CancelProcessInstanceCmd;
import com.blueland.bpm.engine.core.model.ProcessInputModel;
import com.blueland.bpm.engine.core.model.ProcessInstanceModel;
import com.blueland.bpm.engine.util.PageFieldsUtil;
import com.blueland.bpm.engine.util.WorkFlowContants;
import com.blueland.bpm.engine.util.WorkFlowException;
/**
 * 作废流程执行类
 * @version:  1.0
 * @author lw 
 */
@Service(WorkFlowContants.ACTION_TYPE_CANCEL_PROCESS)
public class CancelProcessExecutor  extends AbstractProcessExecutor  implements ProcessExecutor{
	
	@Override
	public ProcessInstanceModel execute(ProcessInputModel processInputModel)
			throws WorkFlowException {
		ProcessInstance processInstance = getProcessInstance(processInputModel.getWf_procInstId());
		ProcessDefinition processDefinition=getProcessDefinition(processInstance.getProcessDefinitionId());
		
		// 根据wfCurActInstId获取当前任务实例，可以没有待办也能够作废
		Task task = null;
		if(!StringUtils.isEmpty(processInputModel.getWf_curActInstId())){
			task = taskService.createTaskQuery()
				.processInstanceId(processInputModel.getWf_procInstId())
				.taskId(processInputModel.getWf_curActInstId()).singleResult();
		}else{
			task=new TaskEntity();
		}
		Map<String, Object> workflowMap = new HashMap<String, Object>();
		// 设置页面fields
		if (StringUtils.isEmpty(processInputModel.getWf_fields())) {
			processInputModel.setWf_fields(PageFieldsUtil
					.fieldsToXml(processInputModel.getFields()));
		}
		if(processInputModel.getWf_sender()!=null){
			identityService.setAuthenticatedUserId(processInputModel.getWf_sender());
		}
		// 设置参数到引擎变量中
		workflowMap.put(WorkFlowContants.WF_PROCESS_INPUT_VARIABLE_KEY,
				processInputModel);
		workflowMap.putAll(processInputModel.getWf_variables());
		if (StringUtils.isNotBlank(processInputModel.getWf_curComment())) {
			taskService.addComment(task.getId(),
					task.getProcessInstanceId(),
					processInputModel.getWf_curComment(),
					processInputModel.getWf_commentDisplayArea());
		}
		Command<Void> cancelProcessInstanceCmd = new CancelProcessInstanceCmd(
				processInputModel.getWf_procInstId(),
				processInputModel.getWf_curActInstId(), processInputModel.getWf_curComment());
		this.managementService.executeCommand(cancelProcessInstanceCmd);
		ProcessInstanceModel processInstanceModel = processInstanceModellBuilder
				.builderProcessInfo(processInputModel,processDefinition, processInstance, task);
		return processInstanceModel;
	}

}
