package com.ai.da.common.utils;

import com.ai.da.common.config.exception.BusinessException;
import com.ai.da.model.dto.GenerateToPythonDTO;
import com.ai.da.python.PythonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.*;

@Slf4j
@Component
public class AsyncCallerUtil {

    // 存放状态 表示当前任务是否需要继续等待，默认持续等待
    public static Map<String, Boolean> waitingStatus = new HashMap<>();

    private static PythonService pythonService;

    @Autowired
    public void setPythonService(PythonService pythonService) {
        AsyncCallerUtil.pythonService = pythonService;
    }

    public CompletableFuture<List<String>> callGenerateAsync(GenerateToPythonDTO generateToPython) {
//        return CompletableFuture.supplyAsync(() -> pythonService.generateSketchOrPrint(generateToPython));
        return null;
    }

    public List<String> generate(GenerateToPythonDTO generateToPython) {
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);
        String taskId = generateToPython.getTasks_id();
        ScheduledFuture<?> timeoutTask = null;
        if (!waitingStatus.containsKey(taskId)) waitingStatus.put(taskId, true);

        try {
            CompletableFuture<List<String>> generateResult = callGenerateAsync(generateToPython);
            // 5秒后第一次确认，之后每隔10秒确认一次用户选择结果
            timeoutTask = scheduledExecutorService.scheduleAtFixedRate(() -> {
                // 调用另一个接口获取用户的选择
                if (!waitingStatus.get(taskId)) {
                    // 如果用户选择取消，则取消对generate的调用
                    generateResult.cancel(true);
                    waitingStatus.remove(taskId);
                } else log.info("===============持续等待===============");
            }, 5, 10, TimeUnit.SECONDS);

            log.info("阻塞等待结果...");
            // 阻塞，等待结果
            List<String> result = generateResult.get();
            // 取消定时任务
            timeoutTask.cancel(true);
            waitingStatus.remove(taskId);
            return result;
        } catch (CancellationException e) {
            // generateResult.cancel(true);通过抛出异常取消该任务
            log.info("==========成功取消generate任务==========");
            return null;
        } catch (InterruptedException | ExecutionException | BusinessException e) {
            // 处理异常
            log.error("发生错误 ： " + e, e);
            // 取消定时任务
            assert timeoutTask != null;
            timeoutTask.cancel(true);
            throw new BusinessException(e.getMessage());
        } finally {
            // 关闭线程池
//            executorService.shutdown();
//            scheduledExecutorService.shutdown();
        }
    }

}
