package com.yd.csf.service.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class AsyncConfig {

    /**
     * 异步聚合查询线程池
     */
    @Bean("asyncQueryExecutor")
    public Executor asyncQueryExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数（根据CPU核心数动态设置）
        executor.setCorePoolSize(Runtime.getRuntime().availableProcessors());
        // 最大线程数
        executor.setMaxPoolSize(Runtime.getRuntime().availableProcessors() * 2);
        // 队列容量
        executor.setQueueCapacity(100);
        // 线程名前缀
        executor.setThreadNamePrefix("async-query-");
        // 拒绝策略：由调用线程处理（保证不会丢失任务）
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待任务完成再关闭
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        // 空闲线程存活时间
        executor.setKeepAliveSeconds(60);
        executor.initialize();
        return executor;
    }

//    /**
//     * 通用异步任务线程池
//     */
//    @Bean("commonAsyncExecutor")
//    public Executor commonAsyncExecutor() {
//        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//        executor.setCorePoolSize(5);
//        executor.setMaxPoolSize(10);
//        executor.setQueueCapacity(50);
//        executor.setThreadNamePrefix("common-async-");
//        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//        executor.setWaitForTasksToCompleteOnShutdown(true);
//        executor.setAwaitTerminationSeconds(30);
//        executor.setKeepAliveSeconds(30);
//        executor.initialize();
//        return executor;
//    }

    /**
     * 通用异步任务线程池
     * @return
     */
    @Bean(name = "commonAsyncExecutor")
    public ThreadPoolTaskExecutor commonAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数、最大线程数、队列容量等参数...
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(20);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("common-async-");

        // 设置 TaskDecorator，用于传递 RequestAttributes
        executor.setTaskDecorator(runnable -> {
            // 获取当前线程的 RequestAttributes
            RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
            return () -> {
                try {
                    // 将 RequestAttributes 设置到子线程中
                    RequestContextHolder.setRequestAttributes(attributes);
                    runnable.run();
                } finally {
                    // 任务完成后清空，避免内存泄漏
                    RequestContextHolder.resetRequestAttributes();
                }
            };
        });

        executor.initialize();
        return executor;
    }
}