package com.cmvr.test.flow.runtime.engine;

import com.cmvr.test.enums.RunModeEnum;
import com.cmvr.test.model.dto.TeQueryTaskDetailDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 异步流程任务调度器（包装线程池执行器）
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class FlowTaskAsyncDispatcher {

    @Resource(name = "threadPoolTaskExecutor")
    private final ThreadPoolTaskExecutor executor;

    private final FlowTaskEngine taskEngine;

    /**
     * 异步提交流程任务
     *
     * @param instId     任务实例 ID
     * @param taskId     任务定义 ID
     * @param terminalId 终端 ID
     * @param runMode    运行模式（NORMAL / TRIAL）
     * @param items      所有检测项详情
     */
    public void submit(String instId, String taskId, String terminalId,
                       RunModeEnum runMode, List<TeQueryTaskDetailDTO> items) {
        executor.submit(() -> {
            Thread.currentThread().setName("task-thread-" + Thread.currentThread().getId());
            try {
                log.info("异步任务开始执行：threadName={}, instId={}, taskId={}", Thread.currentThread().getName(), instId, taskId);
                taskEngine.run(instId, taskId, terminalId, runMode, items);
                log.info("异步任务执行结束：threadName={}, instId={}, taskId={}", Thread.currentThread().getName(), instId, taskId);
            } catch (Exception e) {
                log.error("任务执行异常：threadName={}, instId={}, taskId={}, 错误={}", Thread.currentThread().getName(), instId, taskId, e.getMessage(), e);
                Thread.currentThread().interrupt(); // 保持中断状态
            }
        });
    }
}