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

import cn.axzo.workflow.common.exception.WorkflowEngineException;
import cn.axzo.workflow.common.model.request.bpmn.task.BpmnActivityTriggerDTO;
import cn.axzo.workflow.core.engine.job.AsyncActivityTriggerJobHandler;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
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.service.impl.persistence.entity.TaskEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.util.Objects;

import static cn.axzo.workflow.common.code.BpmnTaskRespCode.ACTIVITY_TRIGGER_NOT_EXISTS;
import static cn.axzo.workflow.core.engine.cmd.CustomActivityTriggerCmd.validateActivityConfig;

/**
 * 自定义(异步)流转业务姐弟那的命令器实现
 *
 * @author wangli
 * @since 2024-09-09 13:58
 */
public class CustomActivityTriggerAsyncCmd extends AbstractCommand<String> implements Serializable {

    private static final long serialVersionUID = 4037000685442842145L;
    private static final Logger log = LoggerFactory.getLogger(CustomActivityTriggerAsyncCmd.class);
    private final BpmnActivityTriggerDTO dto;

    public CustomActivityTriggerAsyncCmd(BpmnActivityTriggerDTO dto) {
        this.dto = dto;
    }

    @Override
    public String paramToJsonString() {
        return JSON.toJSONString(dto);
    }

    @Override
    public String execute(CommandContext commandContext) {
        ProcessEngineConfigurationImpl processEngineConfiguration =
                CommandContextUtil.getProcessEngineConfiguration(commandContext);
        TaskEntity task = (TaskEntity) processEngineConfiguration.getTaskService().createTaskQuery()
                .executionId(dto.getTriggerId())
                .taskDefinitionKey(StringUtils.isBlank(dto.getActivityId()) ? null : dto.getActivityId())
                .singleResult();
        if (Objects.isNull(task)) {
            throw new WorkflowEngineException(ACTIVITY_TRIGGER_NOT_EXISTS, dto.getTriggerId());
        }

        if (!validateActivityConfig(task)) {
            log.info("业务节点唤醒时，发现节点已经修改配置，无法继续唤醒，processInstanceId:{}, taskDefinitionKey={}", task.getProcessInstanceId(), task.getTaskDefinitionKey());
            return "";
        }

        return startAsync(commandContext);
    }

    private String startAsync(CommandContext commandContext) {
        ProcessEngineConfigurationImpl processEngineConfiguration =
                CommandContextUtil.getProcessEngineConfiguration(commandContext);
        TaskService taskService = processEngineConfiguration.getTaskService();
        TaskEntity task = (TaskEntity) taskService.createTaskQuery()
                .executionId(dto.getTriggerId())
                .taskDefinitionKey(StringUtils.isBlank(dto.getActivityId()) ? null : dto.getActivityId())
                .singleResult();
        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(AsyncActivityTriggerJobHandler.TYPE);
        job.setTenantId(task.getTenantId());

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

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