package com.zcxk.core.utils.http;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Andy
 * @description: HttpClient线程池
 * @date 2021/7/16
 * @version V1.0
 **/
public class HttpClientPoolUtil {

    public static Logger thirdLogger = LoggerFactory.getLogger("third");

    private static HttpClient httpClient = null;


    public static HttpClient getHttpClient() {
        if (httpClient == null) {
            httpClient = createHttpClient(100, 20, 10000, 3000, 3000);
        }
        return httpClient;
    }

    /**
     * 实例化HttpClient
     */
    public static HttpClient createHttpClient(int maxTotal, int maxPerRoute, int socketTimeout,
        int connectTimeout,
        int connectionRequestTimeout) {
        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout)
            .setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectionRequestTimeout)
            .build();
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(maxTotal);
        cm.setDefaultMaxPerRoute(maxPerRoute);
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm)
            .setDefaultRequestConfig(defaultRequestConfig).build();
        return httpClient;
    }


    /**
     * 发送post请求
     *
     * @param url 请求地址
     * @param params 请求参数
     * @param encoding 编码
     */
    public static String sendPost(String url, Map<String, String> params, Charset encoding) {
        String resp = "";
        HttpPost httpPost = new HttpPost(url);
        if (params != null && params.size() > 0) {
            List<NameValuePair> formParams = new ArrayList<NameValuePair>();
            Iterator<Entry<String, String>> itr = params.entrySet().iterator();
            while (itr.hasNext()) {
                Entry<String, String> entry = itr.next();
                formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(formParams, encoding);
            httpPost.setEntity(postEntity);
        }
        CloseableHttpResponse response = null;
        try {
            response = (CloseableHttpResponse) getHttpClient().execute(httpPost);
            resp = EntityUtils.toString(response.getEntity(), encoding);
        } catch (Exception e) {
            e.printStackTrace();
            thirdLogger.error("httpClient pool error === [" + url + "]> ", e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return resp;
    }

    /**
     * 发送post请求
     *
     * @param url 请求地址
     * @param params 请求参数
     * @param encoding 编码
     */
    public static String sendPost(String url, Map<String, String> params,
        Map<String, String> headerMap, Charset encoding) {
        String resp = "";
        HttpPost httpPost = new HttpPost(url);

        // 添加请求参数
        if (isNotEmpty(params)) {
            List<NameValuePair> formParams = new ArrayList<NameValuePair>();
            Iterator<Entry<String, String>> itr = params.entrySet().iterator();
            while (itr.hasNext()) {
                Entry<String, String> entry = itr.next();
                formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(formParams, encoding);
            httpPost.setEntity(postEntity);
        }

        // 添加头部参数
        if (isNotEmpty(headerMap)) {
            Iterator<Entry<String, String>> iter = headerMap.entrySet().iterator();
            while (iter.hasNext()) {
                Entry<String, String> element = (Entry<String, String>) iter
                    .next();
                httpPost.addHeader(element.getKey(), element.getValue());
            }
        }

        CloseableHttpResponse response = null;
        try {
            response = (CloseableHttpResponse) getHttpClient().execute(httpPost);
            resp = EntityUtils.toString(response.getEntity(), encoding);
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            thirdLogger.error("httpClient pool error === [" + url + "]> ", e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return resp;
    }

    /**
     * @Description 发送post json参数 author:LH Date : 2017年11月20日 上午10:33:44
     */
    public static String sendPost(String url, String json, Charset encoding) {

        String resp = "";

        CloseableHttpResponse response = null;

        HttpPost httpPost = new HttpPost(url);

        if (StringUtils.isNotEmpty(json)) {
            try {

                StringEntity se = new StringEntity(json);

                se.setContentType("text/json");

                se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

                httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");

                httpPost.addHeader("Connection", "close");

                httpPost.setEntity(se);

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        try {
            response = (CloseableHttpResponse) getHttpClient().execute(httpPost);

            resp = EntityUtils.toString(response.getEntity(), encoding);

        } catch (Exception e) {
            e.printStackTrace();
            thirdLogger.error("httpClient pool error === [" + url + "=" + json + "]> ", e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return resp;
    }

    /**
     * @Description 发送post json参数 author:LH Date : 2017年11月20日 上午10:33:44
     */
    public static String sendPost(String url, String json, Charset encoding, String contentType) {

        String resp = "";

        CloseableHttpResponse response = null;

        HttpPost httpPost = new HttpPost(url);

        if (StringUtils.isNotEmpty(json)) {
            StringEntity se = new StringEntity(json, "utf-8");
            se.setContentType("text/json");
            //默认 请求
            if (StringUtils.isBlank(contentType)) {
                httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json;charset=utf-8");
            } else {
                httpPost.addHeader(HTTP.CONTENT_TYPE, contentType);
            }
            httpPost.addHeader("Connection", "close");
            httpPost.setEntity(se);
        }
        try {
            response = (CloseableHttpResponse) getHttpClient().execute(httpPost);
            resp = EntityUtils.toString(response.getEntity(), encoding);
        } catch (Exception e) {
            e.printStackTrace();
            thirdLogger.error("httpClient pool error === [" + url + "=" + json + "]> ", e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return resp;
    }


    /**
     * @Description 发送post json参数 author:LH Date : 2017年11月20日 上午10:33:44
     */
    public static String sendGet(String url, Charset encoding) {

        String resp = "";

        CloseableHttpResponse response = null;

        HttpGet httpPost = new HttpGet(url);

        try {

            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");

            httpPost.addHeader("Connection", "close");


        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            response = (CloseableHttpResponse) getHttpClient().execute(httpPost);

            resp = EntityUtils.toString(response.getEntity(), encoding);

        } catch (Exception e) {
            e.printStackTrace();
            thirdLogger.error("httpClient pool error === [" + url + "]> ", e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return resp;
    }


    public static String sendGetReferer(String url, Charset encoding, String referer) {

        String resp = "";

        CloseableHttpResponse response = null;

        HttpGet httpPost = new HttpGet(url);

        try {

            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");

            httpPost.addHeader("Connection", "close");

            httpPost.setHeader("referer", referer);

        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            response = (CloseableHttpResponse) getHttpClient().execute(httpPost);

            resp = EntityUtils.toString(response.getEntity(), encoding);

        } catch (Exception e) {
            e.printStackTrace();
            thirdLogger.error("httpClient pool error === [" + url + "]> ", e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return resp;
    }


    private static boolean isNotEmpty(Map<String, String> headerMap) {
        if (headerMap == null || headerMap.size() == 0) {
            return false;
        }
        return true;
    }

    public static Long timeToSecond() {
        String dateStr = "1970-1-1 08:00:00";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long aftertime = 0;
        try {
            Date miDate = sdf.parse(dateStr);
            long d1time = System.currentTimeMillis() / 1000;
            long t1time = miDate.getTime() / 1000;
            aftertime = d1time - t1time;
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return aftertime;

    }

}
