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

import cn.axzo.workflow.common.model.request.bpmn.task.BpmnTaskAuditDTO;
import cn.axzo.workflow.core.engine.cmd.CustomApproveTaskCmd;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.job.service.JobHandler;
import org.flowable.job.service.impl.persistence.entity.JobEntity;
import org.flowable.task.api.Task;
import org.flowable.variable.api.delegate.VariableScope;

import java.util.Objects;

import static cn.axzo.workflow.common.enums.BpmnFlowNodeType.NODE_STARTER;

/**
 * 异步的通过任务的处理器
 *
 * @author wangli
 * @since 2024/4/15 22:41
 */
@Slf4j
public class AsyncApproveTaskJobHandler extends AbstractExecuteWithLockJobHandler implements JobHandler {
    public static final String TYPE = "async-approve-task";

    @Override
    public String getType() {
        return TYPE;
    }

    @Override
    public void executeInternal(JobEntity job, String configuration, VariableScope variableScope, CommandContext commandContext) {
        log.info("AsyncApproveTaskJobHandler executing...");
        log(job);
        ProcessEngineConfigurationImpl processEngineConfiguration =
                CommandContextUtil.getProcessEngineConfiguration(commandContext);
        BpmnTaskAuditDTO dto = JSONUtil.toBean(job.getCustomValues(), BpmnTaskAuditDTO.class);
        Task task = processEngineConfiguration.getTaskService().createTaskQuery().taskId(dto.getTaskId()).singleResult();
        if (Objects.isNull(task)) {
            return;
        }
        CustomApproveTaskCmd command;
        if (Objects.equals(task.getTaskDefinitionKey(), NODE_STARTER.getType())) {
            // 这里的 operationDesc 设置为“” 是为了在日志中不显示（已通过）
            command = new CustomApproveTaskCmd(dto, "");
        } else {
            command = new CustomApproveTaskCmd(dto);
        }
        processEngineConfiguration.getCommandExecutor().execute(command);
    }

}
