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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.blueland.bpm.common.util.StringUtils;
import com.blueland.bpm.engine.core.cmd.CallBackPrevTaskCmd;
import com.blueland.bpm.engine.core.model.ExceptionErrorCode;
import com.blueland.bpm.engine.core.model.ProcessInputModel;
import com.blueland.bpm.engine.core.model.ProcessInstanceModel;
import com.blueland.bpm.engine.core.service.impl.ProcessDefinitionResource;
import com.blueland.bpm.engine.util.PageFieldsUtil;
import com.blueland.bpm.engine.util.ProcessDefinitionUtils;
import com.blueland.bpm.engine.util.WorkFlowContants;
import com.blueland.bpm.engine.util.WorkFlowException;
import com.blueland.bpm.identity.model.User;
/**
 * 退回上一步活动处理类
 * @version:  1.0
 * @author lw 
 */
@Service(WorkFlowContants.ACTION_TYPE_CALLBACK_PREV_ACTIVITY)
public class CallbackToPrevActivityExecutor extends AbstractProcessExecutor implements ProcessExecutor{
	@Autowired
	ProcessDefinitionResource processDefinitionResource;
	@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());
		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_FIELDS_KEY,
				processInputModel.getWf_fields());
		// 设置参数到引擎变量中
		workflowMap.put(WorkFlowContants.WF_PROCESS_INPUT_VARIABLE_KEY,
				processInputModel);
		workflowMap.putAll(processInputModel.getWf_variables());
		autoSetPrevActInfo(workflowMap,processInputModel,task);
		Command<Void> callBackPrevTaskCmd = new CallBackPrevTaskCmd(
				processInputModel.getWf_curActInstId(),
				processInputModel.getWf_nextActDefId(), workflowMap);
		if (StringUtils.isNotBlank(processInputModel.getWf_curComment())) {
			taskService.addComment(task.getId(), task.getProcessInstanceId(),
					processInputModel.getWf_curComment(),processInputModel.getWf_commentDisplayArea());
		}
		this.managementService.executeCommand(callBackPrevTaskCmd);
		ProcessInstanceModel processInstanceModel = processInstanceModellBuilder
				.builderProcessInfo(processInputModel,processDefinition, processInstance, task);
		return processInstanceModel;
	}
	
	protected void autoSetPrevActInfo(Map workflowMap,
			ProcessInputModel processInputModel, Task task)
			throws WorkFlowException {
		processInputModel.setWf_nextActDefId(task.getPreTaskDefKey());
		processInputModel.setWf_nextActDefName(task.getName());
		if (ProcessDefinitionUtils.isMultiInstance(processInputModel,
				repositoryService)) {
			/*List<String> userIds = processDefinitionResource
					.findActivityReturnFormer(task.getProcessDefinitionId(),
							task.getProcessInstanceId(), task.getId(),
							task.getPreTaskId());
			if (userIds == null || userIds.isEmpty()) {
				throw new WorkFlowException(ExceptionErrorCode.B2007,
						"findActivityReturnFormer is empty");
			}
			workflowMap.put(WorkFlowContants.ELEMENT_ASSIGNEE_LIST, userIds);*/
			throw new WorkFlowException(ExceptionErrorCode.B2007,
					"prevActInfo is MultiInstance");

		} else {
			//by lw 20220119 User userReiver =userService.getUserByCode(task.getSendUserId(),task.getSenderOrgId());
			User userReiver =userService.getUserById(task.getSendUserId());
			if (userReiver==null) {//喏维赞允许部分流程（与组织无关流程）组织ID可为空，用用户最新组织走流程
				userReiver = userService.getUserById(task.getSendUserId());
			}
			processInputModel.setWf_receiver(userReiver.getUserId());
			ProcessDefinitionUtils.convertWf_receiver(processInputModel);
		}

	}

}
