package jnpf.personnels.utils;

import org.springframework.stereotype.Component;

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

@Component
public class RosterExportThreadPool {
    private static final int DEFAULT_CORE_POOL_SIZE = 0; // 默认核心线程数为0
    private static final int DEFAULT_MAXIMUM_POOL_SIZE = 20; // 默认最大线程数为10
    private static final long DEFAULT_KEEP_ALIVE_TIME = 120L; // 默认空闲线程存活时间（单位：秒）
    private static final String DEFAULT_THREAD_NAME_PREFIX = "roster-export-"; // 默认线程名称前缀

    private ThreadPoolExecutor executor;

    public ThreadPoolExecutor getExecutor() {
        return executor;
    }

    private String threadNamePrefix;

    /**
     * 创建线程池，使用默认配置。
     */
    public RosterExportThreadPool() {
        this(DEFAULT_CORE_POOL_SIZE, DEFAULT_MAXIMUM_POOL_SIZE, DEFAULT_KEEP_ALIVE_TIME, TimeUnit.SECONDS, DEFAULT_THREAD_NAME_PREFIX);
    }

    /**
     * 创建线程池，自定义核心线程数、最大线程数、空闲线程存活时间和线程名称前缀。
     *
     * @param corePoolSize     核心线程数
     * @param maximumPoolSize  最大线程数
     * @param keepAliveTime    空闲线程存活时间
     * @param timeUnit         时间单位
     * @param threadNamePrefix 线程名称前缀
     */
    public RosterExportThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit timeUnit, String threadNamePrefix) {
        this.threadNamePrefix = threadNamePrefix;
        ThreadFactory threadFactory = new NamedThreadFactory(threadNamePrefix);
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(25);
        this.executor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                timeUnit,
                workQueue,
                threadFactory,
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
    }

    /**
     * 提交任务到线程池执行。
     *
     * @param task 待执行的任务
     */
    public void execute(Runnable task) {
        executor.execute(task);
    }

    /**
     * 关闭线程池，不再接受新任务并等待已提交任务执行完毕。
     */
    public void shutdown() {
        executor.shutdown();
    }

    /**
     * 关闭线程池，不再接受新任务并立即停止所有正在执行的任务。
     */
    public void shutdownNow() {
        executor.shutdownNow();
    }

    // 自定义ThreadFactory，设置线程名称
    private static class NamedThreadFactory implements ThreadFactory {
        private final String namePrefix;
        private final AtomicInteger nextId = new AtomicInteger(1);

        public NamedThreadFactory(String namePrefix) {
            this.namePrefix = namePrefix;
        }

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r);
            t.setName(namePrefix + nextId.getAndIncrement());
            return t;
        }
    }
}
