package robot.mj.thread;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程池配置类
 */
public class ThreadPoolConfig {

    // 优化后的线程池配置：针对机器人场景优化
    private static final ExecutorService BUSINESS_THREAD_POOL =
            new ThreadPoolExecutor(
                    10,              // 核心线程数 - 减少核心线程数
                    50,              // 最大线程数 - 降低最大线程数
                    30,              // 空闲线程存活时间 - 缩短存活时间
                    TimeUnit.SECONDS,
                    new LinkedBlockingQueue<>(10000), // 增大队列容量，减少拒绝任务
                    new ThreadFactory() {
                        private final AtomicInteger threadNumber = new AtomicInteger(1);
                        @Override
                        public Thread newThread(Runnable r) {
                            Thread t = new Thread(r, "RobotBusinessThread-" + threadNumber.getAndIncrement());
                            t.setDaemon(true);
                            t.setPriority(Thread.NORM_PRIORITY - 2); // 进一步降低线程优先级
                            return t;
                        }
                    },
                    new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略：由调用线程执行
            );
    
    // 添加定时任务线程池，专门处理延迟操作
    private static final ScheduledExecutorService SCHEDULED_EXECUTOR_SERVICE =
            Executors.newScheduledThreadPool(4, new ThreadFactory() {
                private final AtomicInteger threadNumber = new AtomicInteger(1);
                @Override
                public Thread newThread(Runnable r) {
                    Thread t = new Thread(r, "RobotScheduledThread-" + threadNumber.getAndIncrement());
                    t.setDaemon(true);
                    t.setPriority(Thread.NORM_PRIORITY - 2);
                    return t;
                }
            });

    public static ExecutorService getBusinessThreadPool() {
        return BUSINESS_THREAD_POOL;
    }
    
    public static ScheduledExecutorService getScheduledExecutorService() {
        return SCHEDULED_EXECUTOR_SERVICE;
    }
    
    /**
     * 执行延迟任务，替代Thread.sleep
     */
    public static void scheduleDelay(Runnable task, long delay, TimeUnit unit) {
        System.out.println("提交延迟任务: 延迟" + delay + " " + unit + ", 当前时间: " + System.currentTimeMillis());
        SCHEDULED_EXECUTOR_SERVICE.schedule(() -> {
            try {
                System.out.println("执行延迟任务开始: 当前时间: " + System.currentTimeMillis());
                task.run();
                System.out.println("执行延迟任务完成: 当前时间: " + System.currentTimeMillis());
            } catch (Exception e) {
                System.err.println("延迟任务执行异常: " + e.getMessage());
            }
        }, delay, unit);
    }
    
    /**
     * 执行周期性任务
     */
    public static void scheduleAtFixedRate(Runnable task, long initialDelay, long period, TimeUnit unit) {
        SCHEDULED_EXECUTOR_SERVICE.scheduleAtFixedRate(task, initialDelay, period, unit);
    }
    
    /**
     * 优雅关闭线程池，释放资源
     */
    public static void shutdown() {
        System.out.println("开始关闭线程池...");
        
        // 关闭定时任务线程池
        SCHEDULED_EXECUTOR_SERVICE.shutdown();
        try {
            if (!SCHEDULED_EXECUTOR_SERVICE.awaitTermination(5, TimeUnit.SECONDS)) {
                SCHEDULED_EXECUTOR_SERVICE.shutdownNow();
            }
        } catch (InterruptedException e) {
            SCHEDULED_EXECUTOR_SERVICE.shutdownNow();
            Thread.currentThread().interrupt();
        }
        
        // 关闭业务线程池
        BUSINESS_THREAD_POOL.shutdown();
        try {
            if (!BUSINESS_THREAD_POOL.awaitTermination(10, TimeUnit.SECONDS)) {
                BUSINESS_THREAD_POOL.shutdownNow();
            }
        } catch (InterruptedException e) {
            BUSINESS_THREAD_POOL.shutdownNow();
            Thread.currentThread().interrupt();
        }
        
        System.out.println("线程池关闭完成");
    }
}
