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

import com.alibaba.fastjson2.JSONObject;
import com.cmvr.test.enums.RunModeEnum;
import com.cmvr.test.flow.context.TaskContext;
import com.cmvr.test.flow.context.TaskInstHolder;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteMessage;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteResult;
import com.cmvr.test.service.ex.ExAeEvaluationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component("END")
@RequiredArgsConstructor
public class FlowEndNodeHandler implements FlowNodeTypeHandler {

    private final TaskInstHolder taskInstHolder;
    private final ExAeEvaluationService exAeEvaluationService;

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

    @Override
    public TaskNodeExecuteResult handle(TaskNodeExecuteMessage message) {
        String instId = message.getInstId();
        String itemId = message.getItemId();
        String taskId = message.getTaskId();
        TaskContext context = taskInstHolder.getContext(instId);
        RunModeEnum runMode = context.getRunMode();
//        if (runMode.equals(RunModeEnum.NORMAL) || runMode.equals(RunModeEnum.TRIAL)) {
//            // 仅语音交互和触控交互进行评估
//            return TaskNodeExecuteResult.success();
//        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("instId", instId);
        jsonObject.put("taskId", taskId);
        jsonObject.put("itemId", itemId);
        jsonObject.put("aeType", RunModeEnum.VI_PROJECT.name());

        executor.submit(() -> {
            Thread.currentThread().setName("evaluation-thread-" + Thread.currentThread().getId());
            try {
                log.info("异步评估任务开始执行：threadName={}, instId={}, itemId={}", Thread.currentThread().getName(), instId, itemId);
//                exAeEvaluationService.executeEvaluation(jsonObject);
                log.info("异步评估任务执行结束：threadName={}, instId={}, itemId={}", Thread.currentThread().getName(), instId, itemId);
            } catch (Exception e) {
                log.error("评估任务执行异常：threadName={}, instId={}, itemId={}, 错误={}", Thread.currentThread().getName(), instId, itemId, e.getMessage(), e);
                Thread.currentThread().interrupt(); // 保持中断状态
            }
        });
        return TaskNodeExecuteResult.success(message.getInputParams());
    }
}
