package com.cnooc.expert.common.utils;

import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

public class RestUtils {

    private static final RestTemplate restTemplate = new RestTemplate();

    /**
     * 发送 Base64 编码的 JSON POST 请求
     *
     * @param apiUrl      API 地址
     * @param requestBody 请求体 Map
     * @return 响应字符串
     */
    public static <T> T sendPostRequest(String apiUrl, Map<String, String> headersMap,
                                        String requestBody, ParameterizedTypeReference<T> responseType) {
        try {
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            if(!CollectionUtils.isEmpty(headersMap)) {
                headersMap.forEach(headers::set);
            }
            // 构建请求实体
            HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);

            ResponseEntity<T> response = restTemplate.exchange(apiUrl, HttpMethod.POST, requestEntity, responseType);
            return response.getBody();
        } catch (Exception e) {
            throw new RuntimeException("发送 POST 请求失败", e);
        }
    }


    public static <T> T  sendPostRequest2Expert(String relativeUrl, String requestBody, ParameterizedTypeReference<T> responseType){


        String fullUrl = "http://10.xxx.xxx.xxx"+relativeUrl;
        Map<String, String> headers = new HashMap<>();
        headers.put("Access-Key", "Ysy9ht");

        return sendPostRequest(fullUrl, headers, requestBody, responseType);
    }




}
