package cn.iocoder.yudao.framework.http.util;

import cn.iocoder.yudao.framework.http.core.Request;
import cn.iocoder.yudao.framework.http.core.Response;
import cn.iocoder.yudao.framework.http.core.client.HttpClient;
import cn.iocoder.yudao.framework.http.core.client.HttpClientFactory;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * Http 工具类
 *
 * @author Jayden
 * @date 2024/11/28
 */
@Slf4j
public class HttpUtils {
    // 创建一个HttpClient实例，用于执行HTTP请求
    private static final HttpClient HTTP_CLIENT = HttpClientFactory.get(Request.Util.OkHttp);

    /**
     * 发送POST请求并返回响应结果
     *
     * @param url         请求的URL地址
     * @param params      请求参数，键值对形式
     * @param headers     请求头，键值对形式
     * @param paramFormat 请求参数的格式
     * @return Response对象，包含响应结果
     */
    public static Response post(String url, Map<String, Object> params, Map<String, String> headers, Request.ParamFormat paramFormat) {
        // 创建请求对象，指定URL、请求方法和参数
        Request request = Request.create(url, Request.Method.POST, params);
        request.setParamFormat(paramFormat);

        try {
            // 执行请求并获取响应
            Response response = HTTP_CLIENT.execute(request, Request.Option.create(0, 0, headers));
            // 记录响应码和响应内容
            log.info("response code ---------------------------->" + response.getCode());
            log.info("response content is --------------------》" + response.getBody());
            return response;
        } catch (Exception e) {
            // 记录错误信息并抛出运行时异常
            log.error("Error executing POST request: " + e.getMessage(), e);
            throw new RuntimeException("Error executing POST request: " + e.getMessage(), e);
        }
    }

    /**
     * 执行GET请求
     *
     * @param url     请求的URL
     * @param headers 请求头，键值对形式
     * @return 返回响应对象，包含响应码、响应内容等信息
     * @throws RuntimeException 如果执行请求时发生异常，则抛出运行时异常
     */
    public static Response get(String url, Map<String, String> headers, String param) {
        // 创建请求对象，指定URL和请求方法
        Request request = Request.create(url, Request.Method.GET, param);
        try {
            // 执行请求并获取响应
            Response response = HTTP_CLIENT.execute(request, Request.Option.create(0, 0, headers));
            // 记录响应码和响应内容
            log.info("response code ---------------------------->" + response.getCode());
            log.info("response content is --------------------》" + response.getBody());
            return response;
        } catch (Exception e) {
            // 记录错误信息并抛出运行时异常
            log.error("Error executing GET request: " + e.getMessage(), e);
            throw new RuntimeException("Error executing GET request: " + e.getMessage(), e);
        }
    }
}
