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.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.CallBackToStartActivityCmd;
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_CALLBACK_START_ACTIVITY)
public class CallbackToStartActivityExecutor extends AbstractProcessExecutor implements ProcessExecutor{
	
	@Override
	public ProcessInstanceModel execute(ProcessInputModel processInputModel)
			throws WorkFlowException {
		ProcessDefinition processDefinition=getProcessDefinition(processInputModel.getWf_procDefId());
		additionalProcessInputModel( processInputModel, processDefinition);
		ProcessInstance processInstance = getProcessInstance(processInputModel.getWf_procInstId());
		// 根据wfCurActInstId获取当前任务实例
		Task task =this.findTaskById(processInputModel.getWf_curActInstId());
		if(processInputModel.getWf_sender()!=null){
			identityService.setAuthenticatedUserId(processInputModel.getWf_sender());
		}
		Map<String, Object> workflowMap = new HashMap<String, Object>();
		// 设置页面fields
		if (StringUtils.isEmpty(processInputModel.getWf_fields())) {
			processInputModel.setWf_fields(PageFieldsUtil
					.fieldsToXml(processInputModel.getFields()));
		}
		workflowMap.put(WorkFlowContants.WF_FIELDS_KEY,
				processInputModel.getWf_fields());
		// 设置参数到引擎变量中
		workflowMap.put(WorkFlowContants.WF_PROCESS_INPUT_VARIABLE_KEY,
				processInputModel);
		workflowMap.putAll(processInputModel.getWf_variables());
		Command<Void> callBackToStartActivityCmd=new CallBackToStartActivityCmd(processInputModel.getWf_curActInstId(),
				processInputModel.getWf_sender(), workflowMap);
		if (StringUtils.isNotBlank(processInputModel.getWf_curComment())) {
			taskService.addComment(task.getId(), task.getProcessInstanceId(),
					processInputModel.getWf_curComment(),processInputModel.getWf_commentDisplayArea());
		}
		this.managementService.executeCommand(callBackToStartActivityCmd);
		ProcessInstanceModel processInstanceModel = processInstanceModellBuilder
				.builderProcessInfo(processInputModel,processDefinition, processInstance, task);
		return processInstanceModel;
	}

}
