package com.ruoyi.system.domain.qcc.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.system.domain.qcc.EsearchJsonRecord;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

public class FinalCostHttpHelper {
    private static final String NORMAL_REGIX = "(200)|(201)|(202)|(205)|(207)|(208)|(209)|(213)|(215)" +
            "|(218)|(219)|(105)|(110)";
    private static final Pattern pattern = Pattern.compile(NORMAL_REGIX);
    private static final String REQ_ENCODEING_UTF8 = "utf-8";
    private static PoolingHttpClientConnectionManager httpClientConnectionManager;
    public static String httpGet(String url, Header[] headers) throws Exception {
        HttpUriRequest uriRequest = new HttpGet(url);
        if (null != headers)
            uriRequest.setHeaders(headers);
        CloseableHttpClient httpClient = null;
        try {
            httpClient = declareHttpClientSSL(url);
            CloseableHttpResponse httpresponse = httpClient.execute(uriRequest);
            HttpEntity httpEntity = httpresponse.getEntity();
            String result = EntityUtils.toString(httpEntity, REQ_ENCODEING_UTF8);
            return result;
        } catch (ClientProtocolException e) {
            System.out.println(String.format("http请求失败，uri{%s},exception{%s}", new Object[] { url, e }));
        } catch (IOException e) {
            System.out.println(String.format("IO Exception，uri{%s},exception{%s}", new Object[] { url, e }));
        } finally {
            if (null != httpClient)
                httpClient.close();
        }
        return null;
    }


    private static CloseableHttpClient declareHttpClientSSL(String url) {
        if (url.startsWith("https://")) {
            return sslClient();
        } else {
            return HttpClientBuilder.create().setConnectionManager(httpClientConnectionManager).build();
        }
    }

    /**
     * 设置SSL请求处理
     *
     */
    private static CloseableHttpClient sslClient() {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] xcs, String str) {
                }

                public void checkServerTrusted(X509Certificate[] xcs, String str) {
                }
            };
            ctx.init(null, new TrustManager[] { tm }, null);
            SSLConnectionSocketFactory sslConnectionSocketFactory = SSLConnectionSocketFactory.getSocketFactory();
            return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (KeyManagementException e) {
            throw new RuntimeException(e);
        }
    }

    public FinalCostHttpHelper() {
        httpClientConnectionManager = new PoolingHttpClientConnectionManager();
        httpClientConnectionManager.setMaxTotal(100);
        httpClientConnectionManager.setDefaultMaxPerRoute(20);
    }


    public static EsearchJsonRecord getJsonObject(String jsonString) {
        if (StringUtils.isBlank(jsonString)) {
            return null;
        }
        JSONObject json = JSON.parseObject(jsonString);
        if(json.getString("Status").equals("200")) {
            String result = json.getString("Result");
            if (StringUtils.isBlank(result)) {
                return null;
            }
            EsearchJsonRecord record = JSON.parseObject(result, EsearchJsonRecord.class);
            return record;
        }
        return null;
    }


    // 返回值
    public static List<EsearchJsonRecord> PrettyPrintJson2(String jsonString) {
        if (StringUtils.isBlank(jsonString)) {
            return null;
        }
        JSONObject json = JSON.parseObject(jsonString);
        if(json.getString("Status").equals("200")){
            String result = json.getString("Result");
            List<EsearchJsonRecord> list = JSON.parseArray(result, EsearchJsonRecord.class);
            if(CollectionUtils.isNotEmpty(list)){
                return list;
            }
        }
        return new ArrayList<>();
    }

    public static Boolean isSuccess (String status) {
        if (StringUtils.isBlank(status)) {
            return false;
        }
        return "200".equals(status);
    }

    public static String FormartJson(String jsonString, String key) {
        JSONObject jObject = JSON.parseObject(jsonString);
        return (String) jObject.get(key);
    }


    public static boolean isNormalRequest(final String status) {
        return pattern.matcher(status).matches();
    }

    public static boolean isSuccessResult(final String status) {
        if (StringUtils.isBlank(status)) {
            return false;
        }
        return "200".equals(status) || "201".equals(status);
    }



}
