package com.palacesun.engine.common;

import com.alibaba.fastjson.JSONObject;
import com.palacesun.engine.gateway.EncryptionGatewayManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ClientUtil {
    private static final Log log = LogFactory.getLog(ClientUtil.class);
    // HTTP请求日志debug开关，true表示开启详细日志，false表示关闭
    private static final boolean HTTP_LOG_DEBUG = true;
    public static ExecutorService executorService = Executors.newFixedThreadPool(10);

    public static String doClient(String url, String json) {
        String result = "调用" + url + "接口结束！";
        InnerThread innerThread = new InnerThread();
        innerThread.url = url;
        innerThread.json = json;
        innerThread.start();
        return result;
    }

    public static CloseableHttpClient buildHttpClient() {
        return EncryptionGatewayManager.getParameterValue("gatewayurl").contains("https") ? SkipHttpsUtil.wrapClient() : HttpClients.createDefault();
    }

    public static String doPost(String url, String json) {
        CloseableHttpClient httpClient = buildHttpClient();
        HttpPost httpPost = new HttpPost(url);
        String result = null;
        long startTime = System.currentTimeMillis();

        // 记录请求日志
        if (HTTP_LOG_DEBUG) {
            log.info("==================== HTTP请求开始 ====================");
            log.info("请求URL: " + url);
            log.info("请求方法: POST");
            log.info("请求头: content-type=application/json;charset=UTF-8");
            log.info("请求参数: " + (json != null ? json : "{}"));
            log.info("请求时间: " + new java.util.Date());
        }

        try {
            httpPost.setHeader("content-type", "application/json;charset=UTF-8");
            StringEntity se = new StringEntity(json, "utf-8");
            httpPost.setEntity(se);
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, "UTF-8");
            }

            long endTime = System.currentTimeMillis();
            // 记录响应日志
            if (HTTP_LOG_DEBUG) {
                log.info("==================== HTTP响应结束 ====================");
                log.info("响应状态码: " + response.getStatusLine().getStatusCode());
                log.info("响应状态: " + response.getStatusLine().getReasonPhrase());
                log.info("响应参数: " + (result != null ? result : "null"));
                log.info("响应时间: " + new java.util.Date());
                log.info("请求耗时: " + (endTime - startTime) + " ms");
                log.info("========================================================");
            }

        } catch (ClientProtocolException var20) {
            long endTime = System.currentTimeMillis();
            if (HTTP_LOG_DEBUG) {
                log.error("==================== HTTP请求异常 ====================");
                log.error("异常类型: ClientProtocolException");
                log.error("异常信息: " + var20.getMessage());
                log.error("请求耗时: " + (endTime - startTime) + " ms");
                log.error("========================================================");
            }
        } catch (UnsupportedEncodingException var21) {
            long endTime = System.currentTimeMillis();
            if (HTTP_LOG_DEBUG) {
                log.error("==================== HTTP请求异常 ====================");
                log.error("异常类型: UnsupportedEncodingException");
                log.error("异常信息: " + var21.getMessage());
                log.error("请求耗时: " + (endTime - startTime) + " ms");
                log.error("========================================================");
            }
        } catch (Exception e) {
            long endTime = System.currentTimeMillis();
            if (HTTP_LOG_DEBUG) {
                log.error("==================== HTTP请求异常 ====================");
                log.error("异常类型: " + e.getClass().getSimpleName());
                log.error("异常信息: " + e.getMessage());
                log.error("请求耗时: " + (endTime - startTime) + " ms");
                log.error("========================================================");
            }
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        return result;
    }

    public static String doPost(String url, String json, GatewaySocketCallback callback) {
        CloseableHttpClient httpClient = buildHttpClient();
        HttpPost httpPost = new HttpPost(url);
        String result = null;
        String resultStatus = "";
        long startTime = System.currentTimeMillis();

        // 记录请求日志
        if (HTTP_LOG_DEBUG) {
            log.info("==================== HTTP请求开始(回调版本) ====================");
            log.info("请求URL: " + url);
            log.info("请求方法: POST");
            log.info("请求头: content-type=application/json;charset=UTF-8");
            log.info("请求参数: " + (json != null ? json : "{}"));
            log.info("请求时间: " + new java.util.Date());
            log.info("回调对象: " + (callback != null ? callback.getClass().getSimpleName() : "null"));
        }

        try {
            httpPost.setHeader("content-type", "application/json;charset=UTF-8");
            StringEntity se = new StringEntity(json, "utf-8");
            httpPost.setEntity(se);
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity, "UTF-8");
            }

            long endTime = System.currentTimeMillis();
            // 记录响应日志
            if (HTTP_LOG_DEBUG) {
                log.info("==================== HTTP响应结束(回调版本) ====================");
                log.info("响应状态码: " + response.getStatusLine().getStatusCode());
                log.info("响应状态: " + response.getStatusLine().getReasonPhrase());
                log.info("响应参数: " + (result != null ? result : "null"));
                log.info("响应时间: " + new java.util.Date());
                log.info("请求耗时: " + (endTime - startTime) + " ms");
            }

            JSONObject jsonObject = JSONObject.parseObject(result);
            String data = (String) jsonObject.get("data");
            if (!jsonObject.get("code").equals("OOW_01")) {
                if ("refresh".equals(data)) {
                    resultStatus = "refresh";
                } else {
                    resultStatus = "norefresh";
                }

                callback.isSucc(data);
                if (HTTP_LOG_DEBUG) {
                    log.info("回调处理: 成功处理，数据=" + data + "，结果状态=" + resultStatus);
                }
            } else {
                callback.clean();
                if (HTTP_LOG_DEBUG) {
                    log.info("回调处理: 执行清理操作");
                }
            }
            if (HTTP_LOG_DEBUG) {
                log.info("====================================================================");
            }

        } catch (ClientProtocolException var24) {
            long endTime = System.currentTimeMillis();
            if (HTTP_LOG_DEBUG) {
                log.error("==================== HTTP请求异常(回调版本) ====================");
                log.error("异常类型: ClientProtocolException");
                log.error("异常信息: " + var24.getMessage());
                log.error("请求耗时: " + (endTime - startTime) + " ms");
                log.error("回调处理: 执行失败回调");
                log.error("====================================================================");
            }
            callback.isFail();
            result = "noRefresh";
        } catch (UnsupportedEncodingException var25) {
            long endTime = System.currentTimeMillis();
            if (HTTP_LOG_DEBUG) {
                log.error("==================== HTTP请求异常(回调版本) ====================");
                log.error("异常类型: UnsupportedEncodingException");
                log.error("异常信息: " + var25.getMessage());
                log.error("请求耗时: " + (endTime - startTime) + " ms");
                log.error("回调处理: 执行失败回调");
                log.error("====================================================================");
            }
            callback.isFail();
            result = "noRefresh";
        } catch (Exception e) {
            long endTime = System.currentTimeMillis();
            if (HTTP_LOG_DEBUG) {
                log.error("==================== HTTP请求异常(回调版本) ====================");
                log.error("异常类型: " + e.getClass().getSimpleName());
                log.error("异常信息: " + e.getMessage());
                log.error("请求耗时: " + (endTime - startTime) + " ms");
                log.error("回调处理: 执行失败回调");
                log.error("====================================================================");
            }
            e.printStackTrace();
            callback.isFail();
            result = "noRefresh";
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        return resultStatus;
    }

    public static CloseableHttpClient getWrapClient() {
        return EncryptionGatewayManager.getParameterValue("gatewayurl").contains("https") ? SkipHttpsUtil.wrapClient() : HttpClients.createDefault();
    }

    public static void main(String[] args) {
        log.info("ClientUtil main method started");
        String url = "http://172.16.100.87:9005/initconfigfile/loadconfig";
        String result = doClient(url, "{}");
        System.out.println("result:" + result);
    }

    public static class InnerThread extends Thread {
        String url;
        String json;

        public void run() {
            ClientUtil.doPost(this.url, this.json);
        }
    }
}
