package org.springblade.common.utils;

import cn.hutool.core.util.RandomUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.core.tool.utils.DateUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class TaskControl {

    private static final Map<String, MonitorTask> tasks = new HashMap<>();
    private static final Map<String, MonitorTask> asyncTasks = new HashMap<>();
    private static final Logger log = LoggerFactory.getLogger(TaskControl.class);
    private static final Object singleTaskLock = new Object();
    private static final Object asyncSingleTaskLock = new Object();

	// 创建一个固定大小的线程池
	public static final ExecutorService executor = Executors.newFixedThreadPool(10);

	public static void runTask(String taskId, Runnable runnable) {
		executor.submit(runnable);
	}

    public static void newSingleInstanceTask(String taskId, Runnable runnable) {
        synchronized (singleTaskLock) {
            MonitorTask monitorTask = tasks.get(taskId);
            if (monitorTask != null) {
                log.info("task is still running, id:{}, req.time:{}", taskId, DateUtil.format(monitorTask.getRequestTime(), "yyyy-MM-dd HH:mm"));
            } else {
                tasks.put(taskId, new MonitorTask(taskId));
            }
        }
        try {
            runnable.run();
        } finally {
            synchronized (singleTaskLock) {
                tasks.remove(taskId);
            }
        }
    }

    public static AsyncTaskRunner newSingleInstanceTask(String taskId) {
        synchronized (asyncSingleTaskLock) {
            MonitorTask task = asyncTasks.get(taskId);
            if (task != null) {
                return new NopTaskRunner();
            }
            asyncTasks.put(taskId, new MonitorTask(taskId));
            return new MultiAsyncTaskRunner(taskId, new Runnable() {
                @Override
                public void run() {
                    synchronized (asyncSingleTaskLock) {
                        asyncTasks.remove(taskId);
                    }
                }
            });
        }
    }


//	public static void main(String[] args) {
//		// 创建一个固定大小为4的线程池
//		ExecutorService executor = Executors.newFixedThreadPool(10);
//
//		// 提交任务到线程池
//		for (int i = 0; i < 100; i++) {
//			int finalI = i; // 用于在lambda表达式中捕获变量
//			executor.submit(() -> {
//				try {
//					Thread.sleep(RandomUtil.randomInt(500,3000));
//				} catch (InterruptedException e) {
//					throw new RuntimeException(e);
//				}
//				System.out.println("Task " + finalI + " executed by " + Thread.currentThread().getName());
//			});
//		}
//
//		// 关闭线程池，不再接受新任务，等待现有任务完成
//		executor.shutdown();
//		try {
//			// 等待线程池关闭，最多等待1分钟
//			if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
//				// 超时后，尝试立即关闭所有正在执行的任务
//				executor.shutdownNow();
//			}
//		} catch (InterruptedException e) {
//			// 线程被中断时的处理
//			executor.shutdownNow();
//		}
//	}

}
