package cn.axzo.workflow.core.engine.tx.listener;

import cn.axzo.workflow.common.model.dto.TermNodePausingDTO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.impl.cfg.TransactionListener;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.common.engine.impl.interceptor.CommandExecutor;
import org.flowable.engine.ManagementService;
import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.job.api.Job;
import org.flowable.job.service.impl.cmd.DeleteTimerJobCmd;

import java.util.Objects;

/**
 * 删除业务节点长时间卡住的定时处理器
 *
 * @author wangli
 * @since 2025-03-12 15:02
 */
@Slf4j
@AllArgsConstructor
public class DeleteTimerJobTransactionListener implements TransactionListener {
    private final TermNodePausingDTO dto;

    @Override
    public void execute(CommandContext commandContext) {
        log.info("clear timer job. instanceId: {}, activityId: {}", dto.getProcessInstanceId(), dto.getActivityId());
        ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
        ManagementService managementService = processEngineConfiguration.getManagementService();
        Job timerJob = managementService.createTimerJobQuery()
                .elementId(dto.getActivityId())
                .processInstanceId(dto.getProcessInstanceId())
                .singleResult();
        if (Objects.nonNull(timerJob)) {
            CommandExecutor commandExecutor = processEngineConfiguration.getCommandExecutor();
            commandExecutor.execute(new DeleteTimerJobCmd(timerJob.getId(), processEngineConfiguration.getJobServiceConfiguration()));
        }
    }
}
