package cn.axzo.workflow.core.engine.cmd;

import cn.axzo.workflow.common.model.request.bpmn.task.AttachmentDTO;
import cn.axzo.workflow.common.model.request.bpmn.task.BpmnTaskAuditDTO;
import cn.axzo.workflow.common.model.request.bpmn.task.BpmnTaskDelegateAssigner;
import cn.axzo.workflow.core.engine.operation.DeleteProcessInstanceOperation;
import cn.axzo.workflow.core.service.ExtAxHiTaskInstService;
import org.flowable.common.engine.impl.interceptor.Command;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.task.api.history.HistoricTaskInstanceQuery;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.axzo.workflow.common.constant.BpmnConstants.COMMENT_TYPE_OPERATION_DESC;
import static cn.axzo.workflow.common.constant.BpmnConstants.INTERNAL_DELETE_PROCESS_FLAG;
import static cn.axzo.workflow.common.constant.BpmnConstants.INTERNAL_END_TENANT_ID;
import static cn.axzo.workflow.common.constant.BpmnConstants.INTERNAL_END_USER_ID;
import static cn.axzo.workflow.common.constant.BpmnConstants.INTERNAL_END_USER_NAME;
import static cn.axzo.workflow.common.constant.BpmnConstants.INTERNAL_PROCESS_DELETE_REASON;
import static cn.axzo.workflow.common.constant.BpmnConstants.INTERNAL_PROCESS_TYPE_REJECT;
import static cn.axzo.workflow.common.constant.BpmnConstants.TASK_COMPLETE_OPERATION_TYPE;
import static cn.axzo.workflow.common.enums.BpmnProcessInstanceResultEnum.REJECTED;
import static cn.axzo.workflow.core.engine.cmd.helper.CustomTaskHelper.addComment;
import static cn.axzo.workflow.core.engine.cmd.helper.CustomTaskHelper.batchAddAttachment;
import static cn.axzo.workflow.core.engine.cmd.helper.CustomTaskHelper.createVirtualTask;
import static cn.axzo.workflow.core.engine.cmd.helper.CustomTaskHelper.validTask;

/**
 * 自定义驳回任务的命令实现
 *
 * @author wangli
 * @since 2024/1/4 13:36
 */
public class CustomRejectionTaskCmd implements Command<Void>, Serializable {

    private final String taskId;
    private final String advice;
    private final List<AttachmentDTO> attachmentList;
    private final BpmnTaskDelegateAssigner approver;
    private final ExtAxHiTaskInstService extAxHiTaskInstService;

    public CustomRejectionTaskCmd(BpmnTaskAuditDTO dto, ExtAxHiTaskInstService extAxHiTaskInstService) {
        this.taskId = dto.getTaskId();
        this.advice = dto.getAdvice();
        this.attachmentList = dto.getAttachmentList();
        this.approver = dto.getApprover();
        this.extAxHiTaskInstService = extAxHiTaskInstService;
    }

    @Override
    public Void execute(CommandContext commandContext) {
        ProcessEngineConfigurationImpl processEngineConfiguration =
                CommandContextUtil.getProcessEngineConfiguration(commandContext);
        HistoricTaskInstanceQuery taskQuery =
                processEngineConfiguration.getHistoryService().createHistoricTaskInstanceQuery();
        HistoricTaskInstance historicTaskInstance = taskQuery.taskId(taskId).singleResult();

        TaskService taskService = processEngineConfiguration.getTaskService();
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();

        validTask(historicTaskInstance, (TaskEntity) task, approver);

        ((TaskEntity) task).setTransientVariable(TASK_COMPLETE_OPERATION_TYPE + task.getId(), REJECTED.getStatus());

        Task virtualTask = createVirtualTask(commandContext, extAxHiTaskInstService, task.getProcessInstanceId(), task.getName(),
                task.getTaskDefinitionKey(), advice, approver, REJECTED.getStatus());
        addComment(commandContext, virtualTask, COMMENT_TYPE_OPERATION_DESC, "已驳回");

        batchAddAttachment(commandContext, task.getProcessInstanceId(), task.getId(), attachmentList, approver);

        RuntimeService runtimeService = processEngineConfiguration.getRuntimeService();
        finishProcessInstance(commandContext, runtimeService, task, advice);
        return null;
    }

    private void finishProcessInstance(CommandContext commandContext, RuntimeService runtimeService, Task task,
                                       String reason) {
        Map<String, Object> variables = new HashMap<>();
        variables.put(INTERNAL_END_TENANT_ID, approver.getTenantId());
        variables.put(INTERNAL_END_USER_NAME, approver.getAssignerName());
        variables.put(INTERNAL_END_USER_ID, approver.buildAssigneeId());
        variables.put(INTERNAL_DELETE_PROCESS_FLAG, INTERNAL_PROCESS_TYPE_REJECT);
        variables.put(INTERNAL_PROCESS_DELETE_REASON, reason);
        runtimeService.setVariables(task.getProcessInstanceId(), variables);
        CommandContextUtil.getAgenda(commandContext)
                .planOperation(new DeleteProcessInstanceOperation(commandContext, task.getProcessInstanceId(),
                        extAxHiTaskInstService));
    }
}
