package cn.ey.biz.module.external.api.fd.feign.config;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;

import feign.Client;
import feign.Feign;
import feign.Logger;
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
/**
 * Feign 自定义配置
 * @author 86182
 *
 */
public class FdFeignConfiguration {

    @Bean
    public FdFeignClientInterceptor feignFdInterceptor() {
        return new FdFeignClientInterceptor();
    }

    @Bean
    public Logger.Level level() {
        return Logger.Level.FULL;
    }

    @Bean
    Encoder feignFormEncoder(ObjectFactory<HttpMessageConverters> converters) {
        return new SpringFormEncoder(new SpringEncoder(converters));
    }
  
    @Bean
    public Feign.Builder feignBuilder(Client feignClient) {
        return Feign.builder().client(feignClient);
    }

//    @Bean
//    public Client client(){
//        return new Client.Default(TrustingSSLSocketFactory.get(), new NoopHostnameVerifier());
//    }
    
    @Bean
    public Client feignClient() throws NoSuchAlgorithmException, KeyManagementException {
		SSLContext ctx = SSLContext.getInstance("SSL");// "SSL"TLSv1.2
		X509TrustManager tm = new X509TrustManager() {

			@Override
			public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
				// TODO Auto-generated method stub
				
			}

			@Override
			public X509Certificate[] getAcceptedIssuers() {
				return new X509Certificate[0];
			}
			
		};
		ctx.init(null, new TrustManager[]{tm}, null);
		return new Client.Default(ctx.getSocketFactory(),new NoopHostnameVerifier());
    }
}
