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

import cn.axzo.workflow.common.exception.WorkflowEngineException;
import cn.axzo.workflow.common.model.request.bpmn.process.SuperBpmnProcessInstanceCancelDTO;
import cn.axzo.workflow.common.model.request.bpmn.task.AttachmentDTO;
import cn.axzo.workflow.common.model.request.bpmn.task.BpmnTaskDelegateAssigner;
import cn.axzo.workflow.core.engine.model.AddComment;
import cn.axzo.workflow.core.engine.operation.DeleteProcessInstanceOperation;
import cn.axzo.workflow.core.service.ExtAxHiTaskInstService;
import com.alibaba.fastjson.JSON;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.history.HistoricProcessInstanceQuery;
import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.task.api.Task;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

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

import static cn.axzo.workflow.common.code.BpmnInstanceRespCode.PROCESS_INSTANCE_CANCEL_FAIL_NOT_EXISTS;
import static cn.axzo.workflow.common.code.BpmnInstanceRespCode.PROCESS_INSTANCE_CANCEL_FAIL_NOT_SELF;
import static cn.axzo.workflow.common.code.BpmnInstanceRespCode.PROCESS_INSTANCE_CANT_CANCEL;
import static cn.axzo.workflow.common.code.BpmnInstanceRespCode.PROCESS_INSTANCE_NOT_EXISTS;
import static cn.axzo.workflow.common.constant.BpmnConstants.CANCEL_PROCESS_NODE_DEF_KEY_NAME;
import static cn.axzo.workflow.common.constant.BpmnConstants.CLOSE_PROCESS_ASSIGNER;
import static cn.axzo.workflow.common.constant.BpmnConstants.INTERNAL_DELETE_PROCESS_FLAG;
import static cn.axzo.workflow.common.constant.BpmnConstants.INTERNAL_PROCESS_DELETE_REASON;
import static cn.axzo.workflow.common.constant.BpmnConstants.INTERNAL_PROCESS_TYPE_CANCEL;
import static cn.axzo.workflow.common.enums.BpmnFlowNodeType.NODE_CANCEL;
import static cn.axzo.workflow.common.enums.BpmnProcessInstanceResultEnum.ABORTED;
import static cn.axzo.workflow.common.enums.BpmnProcessInstanceResultEnum.CANCELLED;
import static cn.axzo.workflow.core.engine.cmd.helper.CustomTaskHelper.batchAddAttachment;
import static cn.axzo.workflow.core.engine.cmd.helper.CustomTaskHelper.completeVirtualTask;
import static cn.axzo.workflow.core.engine.cmd.helper.CustomTaskHelper.createVirtualTask;

/**
 * 自定义的撤回流程实例的命令实现
 *
 * @author wangli
 * @since 2024/1/2 18:19
 */
public class CustomCancelProcessInstanceCmd extends AbstractCommand<Void> implements Serializable {
    private static final long serialVersionUID = 6556399267210245511L;
    private final String processInstanceId;
    private final String tenantId;
    private final String reason;
    private final BpmnTaskDelegateAssigner initiator;
    private final String nodeName;
    private final List<AttachmentDTO> attachmentList;
    private final ExtAxHiTaskInstService extAxHiTaskInstService;
    private final Boolean superAdmin;

    public CustomCancelProcessInstanceCmd(SuperBpmnProcessInstanceCancelDTO dto,
                                          ExtAxHiTaskInstService extAxHiTaskInstService) {
        this.processInstanceId = dto.getProcessInstanceId();
        this.tenantId = dto.getTenantId();
        this.reason = dto.getReason();
        this.initiator = dto.getInitiator();
        this.nodeName = StringUtils.hasText(dto.getNodeName()) ? dto.getNodeName() : "发起人撤回";
        this.attachmentList = dto.getAttachmentList();
        this.superAdmin = Objects.nonNull(dto.getSuperAdmin()) && dto.getSuperAdmin();
        this.extAxHiTaskInstService = extAxHiTaskInstService;
    }

    @Override
    public String paramToJsonString() {
        Map<String, Object> params = new HashMap<>();
        params.put("processInstanceId", processInstanceId);
        params.put("tenantId", tenantId);
        params.put("reason", reason);
        params.put("initiator", initiator);
        return JSON.toJSONString(params);
    }

    @Override
    public Void execute(CommandContext commandContext) {
        ProcessEngineConfigurationImpl processEngineConfiguration =
                CommandContextUtil.getProcessEngineConfiguration(commandContext);

        HistoryService historyService = processEngineConfiguration.getHistoryService();
        HistoricProcessInstanceQuery query = historyService.createHistoricProcessInstanceQuery()
                .processInstanceId(processInstanceId);
        if (Objects.equals(Boolean.TRUE, superAdmin)) {
            query.processInstanceTenantId(tenantId);
        }

        HistoricProcessInstance instance = query.singleResult();
        if (Objects.isNull(instance)) {
            throw new WorkflowEngineException(PROCESS_INSTANCE_NOT_EXISTS);
        }

        if (Objects.nonNull(instance.getEndTime())) {
            throw new WorkflowEngineException(PROCESS_INSTANCE_CANCEL_FAIL_NOT_EXISTS);
        }

        if (!Objects.equals(Boolean.TRUE, superAdmin) && !initiator.comparePersonIdToOther(instance.getStartUserId())) {
            throw new WorkflowEngineException(PROCESS_INSTANCE_CANCEL_FAIL_NOT_SELF);
        }

        if (Objects.equals(instance.getBusinessStatus(), ABORTED.getStatus())) {
            throw new WorkflowEngineException(PROCESS_INSTANCE_CANT_CANCEL);
        }

        List<Task> tasks = processEngineConfiguration.getTaskService()
                .createTaskQuery()
                .processInstanceId(processInstanceId)
                .active()
                .list();
        String taskDefKey = "";
        if (!CollectionUtils.isEmpty(tasks)) {
            taskDefKey = tasks.get(0).getTaskDefinitionKey();
        }
        Map<String, Object> variables = new HashMap<>();
//        variables.put(INTERNAL_END_TENANT_ID, tenantId);
//        variables.put(INTERNAL_END_USER_ID, initiator.buildAssigneeId());
//        variables.put(INTERNAL_END_USER_NAME, initiator.getAssignerName());
        variables.put(INTERNAL_DELETE_PROCESS_FLAG, INTERNAL_PROCESS_TYPE_CANCEL);
        variables.put(INTERNAL_PROCESS_DELETE_REASON, reason);
        variables.put(CANCEL_PROCESS_NODE_DEF_KEY_NAME, taskDefKey);
        RuntimeService runtimeService = processEngineConfiguration.getRuntimeService();
        runtimeService.setVariables(instance.getId(), variables);

        CommandContextUtil.getAgenda(commandContext).planOperation(new DeleteProcessInstanceOperation(commandContext,
                processInstanceId, extAxHiTaskInstService, CANCELLED));

        // 添加自定义的节点,用于展示最后的操作
        TaskEntity task = createVirtualTask(commandContext, extAxHiTaskInstService, processInstanceId,
                nodeName, NODE_CANCEL.getType(), reason, initiator, CANCELLED.getStatus(), new AddComment(CANCELLED.getDesc()));

        batchAddAttachment(commandContext, processInstanceId, task, attachmentList, initiator);

        completeVirtualTask(commandContext, task);

        if (Objects.nonNull(initiator)) {
            runtimeService.setVariable(task.getProcessInstanceId(), CLOSE_PROCESS_ASSIGNER, initiator);
        }
        return null;
    }

}
