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

import cn.axzo.workflow.common.model.request.bpmn.task.BpmnTaskAuditWithFormDTO;
import cn.axzo.workflow.core.engine.job.AsyncApproveTaskWithFormJobHandler;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.TaskService;
import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.job.service.JobService;
import org.flowable.job.service.impl.persistence.entity.JobEntity;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;

import static cn.axzo.workflow.core.engine.cmd.helper.CustomTaskHelper.validTask;

/**
 * 自定义(同步)审批通过任务的命令器实现
 *
 * @author wangli
 * @since 2024/1/4 15:50
 */
public class CustomApproveTaskWithFormAsyncCmd extends AbstractCommand<String> implements Serializable {

    private static final Logger log = LoggerFactory.getLogger(CustomApproveTaskWithFormAsyncCmd.class);
    private final BpmnTaskAuditWithFormDTO dto;
    @Override
    public String paramToJsonString() {
        return JSON.toJSONString(dto);
    }

    public CustomApproveTaskWithFormAsyncCmd(BpmnTaskAuditWithFormDTO dto) {
        this.dto = dto;
    }

    @Override
    public String execute(CommandContext commandContext) {
        ProcessEngineConfigurationImpl processEngineConfiguration =
                CommandContextUtil.getProcessEngineConfiguration(commandContext);
        HistoricTaskInstanceQuery taskQuery =
                processEngineConfiguration.getHistoryService().createHistoricTaskInstanceQuery();
        TaskService taskService = processEngineConfiguration.getTaskService();

        HistoricTaskInstance historicTaskInstance = taskQuery.taskId(dto.getTaskId()).singleResult();

        TaskEntity task = (TaskEntity) taskService.createTaskQuery().taskId(dto.getTaskId()).singleResult();
        validTask(historicTaskInstance, task, dto.getApprover(), dto.getNodeTypes());


        return startAsync(processEngineConfiguration, task);
    }

    private String startAsync(ProcessEngineConfigurationImpl processEngineConfiguration, Task task) {
        JobService jobService = processEngineConfiguration.getJobServiceConfiguration().getJobService();

        JobEntity job = jobService.createJob();
        // 这里的 executionId 可为 null
        job.setExecutionId(task.getExecutionId());
        job.setProcessInstanceId(task.getProcessInstanceId());
        job.setProcessDefinitionId(task.getProcessDefinitionId());
        job.setElementId(task.getTaskDefinitionKey());
        job.setElementName(task.getName());
        job.setJobHandlerType(AsyncApproveTaskWithFormJobHandler.TYPE);
        job.setTenantId(task.getTenantId());

        // 携带自定义的数据
        job.setCustomValues(JSONUtil.toJsonStr(dto));

        // 创建异步任务并调度
        jobService.createAsyncJob(job, false);
        jobService.scheduleAsyncJob(job);
        return job.getId();
    }

}
