package com.mosty.common.core.util;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.util.CollectionUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;

/**
 * DATE: 18/9/3
 *
 * @author: wan
 */
@Slf4j
public class HttpClientUtil {

    private static final String UTF_8 = "UTF-8";

    private static final int TIME_OUT = 60000;

    /**
     * post 参数json字符串，返回String
     *
     * @param uri 请求uri
     * @return 返回结果
     */
    public static HttpResponse postRequest(String uri, Map<String, String> headerMap) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        log.info("httpclient调用地址为：{},加密后身份证号 ：{}", uri);
//        String output;
        HttpResponse response;
        CloseableHttpClient httpClient;

        if (uri.startsWith("https")) {
            SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(
                    SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(), NoopHostnameVerifier.INSTANCE);
            httpClient = HttpClients.custom().setSSLSocketFactory(scsf).build();
        } else {
            httpClient = HttpClients.createDefault();
        }
        try {
            HttpPost postRequest = new HttpPost(uri);
            //设置超时时间。
            RequestConfig requestConfig = setRequestConfig();
            postRequest.setConfig(requestConfig);
            if (!CollectionUtils.isEmpty(headerMap)) {
                headerMap.forEach(postRequest::setHeader);
            }

            response = httpClient.execute(postRequest);

//             = EntityUtils.toString(response.getEntity(), UTF_8);
        } catch (IOException e) {
            throw new RuntimeException("POST调用异常", e);
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return response;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        String uri ="http://10.68.2.210:7001/login/app?key=asdasd+";
        String url = URLEncoder.encode(uri, "UTF-8");
        System.out.println(url);

    }

    /**
     * 绕过证书
     * @return
     */
    public static CloseableHttpClient wrapHttpsClient() {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] arg0,
                                               String arg1) throws CertificateException {
                }

                public void checkServerTrusted(X509Certificate[] arg0,
                                               String arg1) throws CertificateException {
                }
            };
            ctx.init(null, new TrustManager[] { tm }, null);
            SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(
                    ctx, NoopHostnameVerifier.INSTANCE);
            CloseableHttpClient httpclient = HttpClients.custom()
                    .setSSLSocketFactory(ssf).build();
            return httpclient;
        } catch (Exception e) {
            log.error("顺丰HttpClient异常", e);
            return HttpClients.createDefault();
        }
    }

    private static RequestConfig setRequestConfig(){
        return RequestConfig.custom().setSocketTimeout(TIME_OUT).setConnectTimeout(TIME_OUT).build();
    }
}
