package com.qingyun.common.utils;

import cn.hutool.core.lang.ObjectId;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;

public class TaskManager {

    // 存储任务ID与Future的映射
    private static Map<String, Future<?>> taskMap = new ConcurrentHashMap<>();

    /**
     * 提交任务并返回任务ID
     */
    public static String submitTask(Callable<?> task, ThreadPoolTaskExecutor executor,String taskId) {
        Future<?> future = executor.submit(task);
        taskMap.put(taskId!=null ? taskId : "task-" + ObjectId.next(), future);
        return taskId;
    }

    /**
     * 根据任务ID取消任务
     */
    public static boolean cancelTask(String taskId) {
        if (StringUtils.isBlank(taskId)) {
            return false;
        }
        Future<?> future = taskMap.get(taskId);
        if (future != null) {
            boolean cancelled = future.cancel(true); // true 表示尝试中断线程
            if (cancelled) {
                taskMap.remove(taskId);
            }
            return cancelled;
        }
        return false;
    }
}
