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

import cn.axzo.workflow.common.model.request.bpmn.task.BpmnTaskAuditDTO;
import cn.axzo.workflow.common.model.request.bpmn.task.BpmnTaskDelegateAssigner;
import cn.axzo.workflow.core.engine.cmd.CustomRejectionTaskAsyncCmd;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.impl.cfg.TransactionListener;
import org.flowable.common.engine.impl.interceptor.CommandConfig;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.common.engine.impl.interceptor.CommandExecutor;
import org.flowable.job.service.JobServiceConfiguration;
import org.flowable.job.service.impl.asyncexecutor.ResetExpiredJobsCmd;
import org.flowable.spring.SpringProcessEngineConfiguration;
import org.flowable.task.service.delegate.DelegateTask;

import java.util.Collections;

import static org.flowable.common.engine.impl.interceptor.EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG;

/**
 * 自动拒绝的事务监听
 *
 * <pre>
 * 使用示例:
 *  Context.getTransactionContext().addTransactionListener(TransactionState.COMMITTED, new AutoRejectTransactionListener(delegateTask, extAxHiTaskInstService));
 * </pre>
 *
 * @author wangli
 * @since 2024-08-07 10:26
 */
@Slf4j
@AllArgsConstructor
public class AutoRejectTransactionListener implements TransactionListener {
    private final DelegateTask delegateTask;
    private final String operationDesc;

    @Override
    public void execute(CommandContext commandContext) {
        log.info("exec auto reject transaction listener start, processInstanceId: {}, taskId: {}",
                delegateTask.getProcessInstanceId(), delegateTask.getId());

        SpringProcessEngineConfiguration springProcessEngineConfiguration = (SpringProcessEngineConfiguration) commandContext
                .getEngineConfigurations().get(KEY_PROCESS_ENGINE_CONFIG);
        CommandConfig commandConfig = new CommandConfig().transactionRequired();

        CommandExecutor commandExecutor = springProcessEngineConfiguration.getCommandExecutor();
        BpmnTaskAuditDTO reject = new BpmnTaskAuditDTO();
        reject.setTaskId(delegateTask.getId());
        reject.setApprover(new BpmnTaskDelegateAssigner("", "system", delegateTask.getTenantId()));
        reject.setOperationDesc(operationDesc);
        String jobId = commandExecutor.execute(commandConfig, new CustomRejectionTaskAsyncCmd(reject));

        // 重置任务，因为上面的 cmd 和这个 cmd 的 lock 对象不一致
        JobServiceConfiguration jobServiceConfiguration = springProcessEngineConfiguration.getJobServiceConfiguration();
        commandExecutor.execute(commandConfig,
                new ResetExpiredJobsCmd(Collections.singletonList(jobId), jobServiceConfiguration.getJobEntityManager(), jobServiceConfiguration));

        log.info("exec auto reject transaction listener end");
    }
}
