package com.jeesharp.business.modules.pay.tlinx.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

/**
 * HTTP工具类
 * 
 * @author wangmeng
 * @since 2026-03-16
 */
public class HttpUtil {
    
    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
    
    private static final int CONNECT_TIMEOUT = 30000;
    private static final int READ_TIMEOUT = 30000;
    
    /**
     * POST请求
     *
     * @param url 请求URL
     * @param params 请求参数
     * @param charset 字符集
     * @return 响应字符串
     */
    public static String post(String url, Map<String, String> params, String charset) {
        HttpURLConnection conn = null;
        OutputStream out = null;
        BufferedReader reader = null;
        
        try {
            URL httpUrl = new URL(url);
            conn = (HttpURLConnection) httpUrl.openConnection();
            
            // 设置请求属性
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(CONNECT_TIMEOUT);
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
            
            // 构建请求参数
            StringBuilder paramBuilder = new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (paramBuilder.length() > 0) {
                    paramBuilder.append("&");
                }
                paramBuilder.append(entry.getKey())
                           .append("=")
                           .append(URLEncoder.encode(entry.getValue(), charset));
            }
            
            String postData = paramBuilder.toString();
            logger.debug("POST请求参数: {}", postData);
            
            // 发送请求
            out = conn.getOutputStream();
            out.write(postData.getBytes(charset));
            out.flush();
            
            // 读取响应
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                String result = response.toString();
                logger.debug("POST响应: {}", result);
                return result;
            } else {
                logger.error("HTTP请求失败，响应码: {}", responseCode);
                return "";
            }
            
        } catch (Exception e) {
            logger.error("HTTP POST请求异常", e);
            return "";
        } finally {
            // 关闭资源
            try {
                if (out != null) {
                    out.close();
                }
                if (reader != null) {
                    reader.close();
                }
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (Exception e) {
                logger.warn("关闭HTTP连接时发生异常", e);
            }
        }
    }
    
    /**
     * GET请求
     *
     * @param url 请求URL
     * @param params 请求参数
     * @param charset 字符集
     * @return 响应字符串
     */
    public static String get(String url, Map<String, String> params, String charset) {
        try {
            // 构建完整URL
            StringBuilder urlBuilder = new StringBuilder(url);
            if (params != null && !params.isEmpty()) {
                urlBuilder.append("?");
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    urlBuilder.append(entry.getKey())
                             .append("=")
                             .append(URLEncoder.encode(entry.getValue(), charset))
                             .append("&");
                }
                // 移除最后一个&
                urlBuilder.deleteCharAt(urlBuilder.length() - 1);
            }
            
            String fullUrl = urlBuilder.toString();
            logger.debug("GET请求URL: {}", fullUrl);
            
            URL httpUrl = new URL(fullUrl);
            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
            
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(CONNECT_TIMEOUT);
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
            
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                conn.disconnect();
                
                String result = response.toString();
                logger.debug("GET响应: {}", result);
                return result;
            } else {
                logger.error("HTTP GET请求失败，响应码: {}", responseCode);
                conn.disconnect();
                return "";
            }
            
        } catch (Exception e) {
            logger.error("HTTP GET请求异常", e);
            return "";
        }
    }
}