package com.haha.common.utils;

import com.alibaba.fastjson2.JSON;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.util.HashMap;
import java.util.Map;

/**
 * HTTP请求参数解析工具类
 * 统一处理从HttpServletRequest中读取JSON、XML、form-urlencoded格式的参数
 */
@Slf4j
public class RequestParseUtil {

    private RequestParseUtil() {}

    /**
     * 从HttpServletRequest中读取请求体内容
     *
     * @param request HTTP请求对象
     * @return 请求体字符串
     */
    public static String readRequestBody(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (Exception e) {
            log.error("读取请求体失败", e);
        }
        return sb.toString();
    }

    /**
     * 解析请求参数，支持 JSON 和 form-urlencoded 两种格式
     *
     * @param request       HTTP请求对象
     * @param requestParams form表单参数（@RequestParam捕获的参数）
     * @return 参数Map
     */
    public static Map<String, Object> parseRequestParams(HttpServletRequest request, Map<String, String> requestParams) {
        Map<String, Object> params = new HashMap<>();

        String contentType = request.getContentType();
        log.debug("请求Content-Type: {}", contentType);

        try {
            if (contentType != null && contentType.toLowerCase().contains("application/json")) {
                // JSON 格式：从 request body 读取
                String body = readRequestBody(request);
                if (body != null && !body.isEmpty()) {
                    params = JSON.parseObject(body, Map.class);
                    log.debug("解析JSON参数: {}", params.size());
                }
            } else if (contentType != null && contentType.toLowerCase().contains("text/xml")) {
                // XML 格式（微信支付回调）：从 request body 读取原始XML
                String body = readRequestBody(request);
                if (body != null && !body.isEmpty()) {
                    params.put("xmlBody", body);
                    log.debug("解析XML参数");
                }
            } else {
                // form-urlencoded 格式：使用 @RequestParam 捕获的参数
                if (requestParams != null && !requestParams.isEmpty()) {
                    params.putAll(requestParams);
                    log.debug("解析表单参数: {}", params.size());
                }
            }
        } catch (Exception e) {
            log.error("解析请求参数失败", e);
        }

        return params;
    }

    /**
     * 从HttpServletRequest中读取微信支付回调请求头和请求体
     *
     * @param request HTTP请求对象
     * @return 包含body和微信签名头的参数Map
     */
    public static Map<String, Object> parseWechatPayCallbackParams(HttpServletRequest request) {
        String body = readRequestBody(request);

        Map<String, Object> params = new HashMap<>();
        params.put("body", body);
        params.put("Wechatpay-Timestamp", request.getHeader("Wechatpay-Timestamp"));
        params.put("Wechatpay-Nonce", request.getHeader("Wechatpay-Nonce"));
        params.put("Wechatpay-Signature", request.getHeader("Wechatpay-Signature"));
        params.put("Wechatpay-Serial", request.getHeader("Wechatpay-Serial"));
        params.put("Wechatpay-Signature-Type", request.getHeader("Wechatpay-Signature-Type"));

        log.info("微信支付回调请求头: Timestamp={}, Nonce={}, Serial={}",
                params.get("Wechatpay-Timestamp"),
                params.get("Wechatpay-Nonce"),
                params.get("Wechatpay-Serial"));

        return params;
    }
}
