package com.zsElectric.boot.common.async;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

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

/**
 * 异步任务配置类
 * 功能：配置线程池参数、异常处理、优雅关闭等
 */
@Slf4j
@Configuration
@EnableAsync
@EnableConfigurationProperties(ThreadPoolProperties.class)
public class AsyncConfig implements AsyncConfigurer {

    @Resource
    private ThreadPoolProperties threadPoolProperties;

    /**
     * 核心业务线程池 - 用于处理重要异步任务
     */
    @Bean(name = "businessTaskExecutor")
    public ThreadPoolTaskExecutor businessTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        
        // 核心线程池配置
        executor.setCorePoolSize(threadPoolProperties.getCorePoolSize());
        executor.setMaxPoolSize(threadPoolProperties.getMaxPoolSize());
        executor.setQueueCapacity(threadPoolProperties.getQueueCapacity());
        executor.setKeepAliveSeconds(threadPoolProperties.getKeepAliveSeconds());
        
        // 线程配置
        executor.setThreadNamePrefix(threadPoolProperties.getThreadNamePrefix());
        executor.setAllowCoreThreadTimeOut(threadPoolProperties.isAllowCoreThreadTimeOut());
        
        // 拒绝策略配置
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        
        // 优雅关闭配置
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(threadPoolProperties.getAwaitTerminationSeconds());
        
        // 线程工厂自定义（设置线程优先级、守护线程等）
        executor.setThreadFactory(new CustomThreadFactory());
        
        executor.initialize();
        return executor;
    }

    /**
     * IO密集型任务线程池 - 适用于网络请求、文件操作等
     */
    @Bean(name = "ioIntensiveTaskExecutor")
    public ThreadPoolTaskExecutor ioIntensiveTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        
        // IO密集型任务可以设置更大的线程数
        int cpuCores = Runtime.getRuntime().availableProcessors();
        executor.setCorePoolSize(cpuCores * 2);
        executor.setMaxPoolSize(cpuCores * 4);
        executor.setQueueCapacity(500);
        executor.setKeepAliveSeconds(120);
        executor.setThreadNamePrefix("io-task-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        executor.initialize();
        
        return executor;
    }

    /**
     * 默认异步执行器（覆盖Spring默认配置）
     */
    @Override
    public Executor getAsyncExecutor() {
        return businessTaskExecutor();
    }

    /**
     * 异步任务异常处理
     * 用于处理无返回值的@Async方法的异常
     *  第一层：业务异常处理
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (throwable, method, params) -> {
            // 记录异步任务执行异常
            log.info("异步任务执行异常 - 方法: {}, 异常: {}", method.getName(), throwable.getMessage());
            // 这里可以接入日志框架、告警系统等
            throwable.printStackTrace();
        };
    }
}