package com.hdkj.lt.si.config;

import com.ruoyi.common.core.config.ThreadPoolProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

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

/**
 * 状估模块 Bean 配置: RestTemplate (带超时) + 有界线程池.
 * @author Annie
 */
@Configuration
@EnableConfigurationProperties(ThreadPoolProperties.class)
public class SeConfig {

    /**
     * 状估查询专用线程池 (有界). 跨所有请求共享, 大小 = poolSize,
     * 即并发调用远程接口的全局上限. 守护线程, 应用关闭时 shutdown.
     */
    @Bean(name = "seQueryExecutor", destroyMethod = "shutdown")
    public ExecutorService seQueryExecutor(ThreadPoolProperties config) {
        ThreadFactory factory = new ThreadFactory() {
            private final AtomicInteger counter = new AtomicInteger(0);

            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, "se-query-" + counter.incrementAndGet());
            }
        };
        return new ThreadPoolExecutor(
                config.getCoreSize(),
                config.getMaxSize(),
                config.getKeepAlive(),
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(config.getQueueSize()),factory,
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
    }
}
