package com.emoon.openplatform.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @author destiny
 * @description: HTTP工具类，提供POST请求功能
 * @date 2025/9/23 18:07
 */
@Slf4j
public class HttpUtil {
    private static final RestTemplate restTemplate = new RestTemplate();
    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 模拟PHP中的curlPost函数 - 发送POST请求
     *
     * @param url  请求URL
     * @param data 请求数据
     * @return 响应内容
     */
    public static String curlPost(String url, Map<String, String> data) {
        return curlPost(url, data, null, false);
    }

    /**
     * 模拟PHP中的curlPost函数 - 发送POST请求
     *
     * @param url     请求URL
     * @param data    请求数据
     * @param headers 请求头
     * @return 响应内容
     */
    public static String curlPost(String url, Map<String, String> data, Map<String, String> headers) {
        return curlPost(url, data, headers, false);
    }

    /**
     * 模拟PHP中的curlPost函数 - 发送POST请求
     *
     * @param url     请求URL
     * @param data    请求数据
     * @param headers 请求头
     * @param isJson  是否以JSON格式发送
     * @return 响应内容
     */
    public static String curlPost(String url, Map<String, String> data, Map<String, String> headers, boolean isJson) {
        try {
            HttpEntity<?> requestEntity = buildRequestEntity(data, headers, isJson);
            ResponseEntity<String> response = restTemplate.exchange(
                url,
                HttpMethod.POST,
                requestEntity,
                String.class
            );
            return response.getBody();
        } catch (Exception e) {
            return handleException(e);
        }
    }

    /**
     * 重载方法：用于发送JSON对象而不是Map
     */
    public static String curlPost(String url, Object dataObject, Map<String, String> headers, boolean isJson) {
        try {
            HttpEntity<?> requestEntity = buildRequestEntity(dataObject, headers, isJson);
            ResponseEntity<String> response = restTemplate.exchange(
                url,
                HttpMethod.POST,
                requestEntity,
                String.class
            );
            return response.getBody();
        } catch (Exception e) {
            return handleException(e);
        }
    }

    /**
     * 构建请求实体
     */
    private static HttpEntity<?> buildRequestEntity(Object data, Map<String, String> headers, boolean isJson) {
        HttpHeaders httpHeaders = new HttpHeaders();

        // 设置请求头
        if (headers != null && !headers.isEmpty()) {
            headers.forEach(httpHeaders::set);
        }

        if (isJson) {
            // JSON格式发送
            httpHeaders.setContentType(MediaType.APPLICATION_JSON);
            String jsonData = toJson(data);
            return new HttpEntity<>(jsonData, httpHeaders);
        } else {
            // 表单格式发送
            httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            MultiValueMap<String, String> formData = toFormData(data);
            return new HttpEntity<>(formData, httpHeaders);
        }
    }

    /**
     * 将对象转换为JSON字符串
     */
    private static String toJson(Object data) {
        try {
            return objectMapper.writeValueAsString(data);
        } catch (Exception e) {
            throw new RuntimeException("Failed to convert object to JSON", e);
        }
    }

    /**
     * 将对象转换为表单数据
     */
    @SuppressWarnings("unchecked")
    private static MultiValueMap<String, String> toFormData(Object data) {
        MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();

        if (data == null) {
            return formData;
        }

        if (data instanceof Map) {
            ((Map<String, String>) data).forEach((key, value) ->
                formData.add(String.valueOf(key), value != null ? value.toString() : ""));
        } else { // 对于普通对象，可以考虑使用objectMapper转换为Map再处理
            try {
                Map<String, Object> map = objectMapper.convertValue(data, Map.class);
                map.forEach((key, value) ->
                    formData.add(key, value != null ? value.toString() : ""));
            } catch (Exception e) {
                // 如果转换失败，添加对象的toString表示
                formData.add("data", data.toString());
            }
        }

        return formData;
    }

    /**
     * 统一异常处理
     */
    private static String handleException(Exception e) {
        e.printStackTrace();
        return "{\"error\":\"" + e.getMessage() + "\"}";
    }
}
