package com.sky.ioc.config;

import com.sky.ioc.mapper.job.TokenMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
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 javax.annotation.Resource;
import javax.net.ssl.HttpsURLConnection;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.Map;

@Configuration
public class RestTemplateConfig {

    @Resource
    TokenMapper tokenMapper;

    @Value("${sky.dataIp}")
    private String dataIp;

    private static RestTemplateBuilder builder = null;

    static {
        builder = new RestTemplateBuilder(restTemplate -> restTemplate.setRequestFactory(new SimpleClientHttpRequestFactory() {
            @Override
            protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
                if (connection instanceof HttpsURLConnection) {
                    ((HttpsURLConnection) connection).setHostnameVerifier((s, sslSession) -> true);
                }
                super.prepareConnection(connection, httpMethod);
            }
        }))
                // 超时时间
                .setConnectTimeout(Duration.of(5*60, ChronoUnit.SECONDS))
                .setReadTimeout(Duration.of(5*60, ChronoUnit.SECONDS));
    }

    @Bean
    public RestTemplate restTemplate(){
        return build();
    }

    public RestTemplate build() {
        Map<String,String> tokenMap = tokenMapper.getNewToken();
        String token ="Bearer eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX2tleSI6IjUwZTU1NTRkLWJjYzYtNGRhMS1iZDUxLWFhNTc3YzU4YTFiNCIsInVzZXJuYW1lIjoiYWRtaW4ifQ.X10VPYJfeeRTka7OtqNPOGMpL4QkW3fR_TfCKXCmO-yXbIIrr_40fcwiVnpXfYVENo_BvXWEACRd-Y6nXsbkog";
        if(tokenMap!=null){
            token = "Bearer "+tokenMap.get("token");
        }
        // 默认请求头
        builder = builder.defaultHeader("authorization", token);
        return builder.build();
    }

    public String addBaseUrl(String url) {
        if (url.startsWith("http")) {
            return url;
        }
        url = StringUtils.removeStart(url, "/");
        String baseUrl = StringUtils.appendIfMissing("http://"+dataIp, "/");
        return baseUrl + url;
    }
}
