package org.jeecg.config.weixin;

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.jeecg.config.vo.weixin.WechatMiniProgramProperties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Configuration
public class WechatConfig {

    @Value("${wechat.miniprogram.appid}")
    private String appId;

    @Value("${wechat.miniprogram.appsecret}")
    private String appSecret;

    @Value("${wechat.miniprogram.token.cache.enabled:true}")
    private boolean tokenCacheEnabled;

    @Value("${wechat.miniprogram.token.cache.timeout:7000}")
    private int tokenCacheTimeout;

    @Bean
    public WechatMiniProgramProperties wechatMiniProgramProperties() {
        return new WechatMiniProgramProperties(appId, appSecret, tokenCacheEnabled, tokenCacheTimeout);
    }

    @Bean
    public CloseableHttpClient httpClient() {
        PoolingHttpClientConnectionManager connectionManager =
                new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(200);
        connectionManager.setDefaultMaxPerRoute(50);

        return HttpClientBuilder.create()
                .setConnectionManager(connectionManager)
                .evictIdleConnections(30, TimeUnit.SECONDS)
                .setConnectionTimeToLive(60, TimeUnit.SECONDS)
                .build();
    }
}
