package com.qqchen.deploy.backend.workflow.event.handler;

import com.qqchen.deploy.backend.workflow.entity.WorkflowNodeInstance;
import com.qqchen.deploy.backend.workflow.enums.WorkflowNodeInstanceStatusEnums;
import com.qqchen.deploy.backend.workflow.dto.event.TerminationProcessInstanceListenerEvent;
import com.qqchen.deploy.backend.workflow.repository.IWorkflowNodeInstanceRepository;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.RuntimeService;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Slf4j
@Component
public class TerminationProcessInstanceHandler {

    @Resource
    @Lazy
    private RuntimeService runtimeService;

    @Resource
    private IWorkflowNodeInstanceRepository workflowNodeInstanceRepository;

    @Async
    @EventListener
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void handler(TerminationProcessInstanceListenerEvent event) {
        try {
            // 先删除死信任务
//            managementService.deleteDeadLetterJob(event.getJobId());
            WorkflowNodeInstance workflowNodeInstance = workflowNodeInstanceRepository.findTop1ByProcessInstanceIdOrderByStartTimeDesc(event.getProcessInstanceId());
            if (workflowNodeInstance != null) {
                workflowNodeInstance.setStatus(WorkflowNodeInstanceStatusEnums.FAILED);
                workflowNodeInstance.setEndTime(LocalDateTime.now());
                workflowNodeInstanceRepository.save(workflowNodeInstance);
            }
            runtimeService.deleteProcessInstance(event.getProcessInstanceId(), event.getReason());
            log.info("Process instance {} deleted due to: {}", event.getProcessInstanceId(), event.getReason());
        } catch (Exception e) {
            log.error("Failed to delete process instance: " + event.getProcessInstanceId(), e);
        }
    }
}