package com.qqchen.deploy.backend.workflow.listener.flowable.execution;

import com.qqchen.deploy.backend.workflow.enums.WorkflowNodeInstanceStatusEnums;
import com.qqchen.deploy.backend.workflow.dto.event.WorkflowNodeInstanceStatusChangeEvent;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Component("gatewayExecutionListener")
public class GatewayExecutionListener implements ExecutionListener {

    @Resource
    private ApplicationEventPublisher eventPublisher;

    @Override
    public void notify(DelegateExecution execution) {
        // 获取当前节点信息
        FlowElement flowElement = execution.getCurrentFlowElement();
        String eventName = execution.getEventName();
        String processInstanceId = execution.getProcessInstanceId();
        String executionId = execution.getId();
        String nodeId = execution.getCurrentActivityId();
        String nodeName = flowElement.getName();
        String nodeType = flowElement.getClass().getSimpleName();
        log.debug("Node execution event: {}, processInstanceId: {}, nodeId: {}, nodeType: {}, nodeName:{}", eventName, processInstanceId, nodeId, nodeType, nodeName);
        eventPublisher.publishEvent(WorkflowNodeInstanceStatusChangeEvent.builder()
            .processInstanceId(processInstanceId)
            .executionId(executionId)
            .nodeId(nodeId)
            .nodeName(nodeName)
            .nodeType(nodeType)
            .status(WorkflowNodeInstanceStatusEnums.COMPLETED)
            .startTime(LocalDateTime.now())
            .endTime(LocalDateTime.now())
            .build());
    }
}