package lingtao.net.util;

import okhttp3.*;

import java.io.IOException;
import java.util.Map;

public class HttpUtils {

    private static final OkHttpClient HTTP_CLIENT = new OkHttpClient();
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private static final MediaType FORM = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");

    /**
     * 通用HTTP GET请求方法
     *
     * @param url     请求地址
     * @param headers 请求头映射
     * @return 响应结果字符串
     */
    public static String sendGetRequest(String url, Map<String, String> headers) {
        Request.Builder builder = new Request.Builder()
                .header("Content-Type", "application/json")
                .url(url);
        // 添加请求头
        if (headers != null && !headers.isEmpty()) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                builder.header(entry.getKey(), entry.getValue());
            }
        }

        Request request = builder.build();

        try (Response response = HTTP_CLIENT.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("请求异常: " + response.code());
            }
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 通用HTTP GET请求方法（无请求头）
     *
     * @param url 请求地址
     * @return 响应结果字符串
     */
    public static String sendGetRequest(String url) {
        return sendGetRequest(url, null);
    }

    /**
     * 通用HTTP POST请求方法（JSON参数）
     *
     * @param url       请求地址
     * @param jsonParam JSON参数
     * @param headers   请求头映射
     * @return 响应结果字符串
     */
    public static String sendPostRequest(String url, String jsonParam, Map<String, String> headers) {
        RequestBody body = RequestBody.create(JSON, jsonParam);
        Request.Builder builder = new Request.Builder()
                .header("Content-Type", "application/json")
                .url(url)
                .post(body);

        // 添加请求头
        if (headers != null && !headers.isEmpty()) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                builder.header(entry.getKey(), entry.getValue());
            }
        }

        Request request = builder.build();

        try (Response response = HTTP_CLIENT.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("请求异常: " + response.code());
            }
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 通用HTTP POST请求方法（JSON参数，无请求头）
     *
     * @param url       请求地址
     * @param jsonParam JSON参数
     * @return 响应结果字符串
     */
    public static String sendPostRequest(String url, String jsonParam) {
        return sendPostRequest(url, jsonParam, null);
    }

    /**
     * 通用HTTP POST请求方法（表单参数）
     *
     * @param url        请求地址
     * @param formParams 表单参数映射
     * @param headers    请求头映射
     * @return 响应结果字符串
     */
    public static String sendPostFormRequest(String url, Map<String, String> formParams, Map<String, String> headers) {
        StringBuilder formBody = new StringBuilder();
        if (formParams != null && !formParams.isEmpty()) {
            for (Map.Entry<String, String> entry : formParams.entrySet()) {
                if (formBody.length() > 0) {
                    formBody.append("&");
                }
                formBody.append(entry.getKey()).append("=").append(entry.getValue());
            }
        }

        RequestBody body = RequestBody.create(FORM, formBody.toString());
        Request.Builder builder = new Request.Builder()
                .header("Content-Type", "application/json")
                .url(url)
                .post(body);

        // 添加请求头
        if (headers != null && !headers.isEmpty()) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                builder.header(entry.getKey(), entry.getValue());
            }
        }

        Request request = builder.build();

        try (Response response = HTTP_CLIENT.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("请求异常: " + response.code());
            }
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 通用HTTP POST请求方法（表单参数，无请求头）
     *
     * @param url        请求地址
     * @param formParams 表单参数映射
     * @return 响应结果字符串
     */
    public static String sendPostFormRequest(String url, Map<String, String> formParams) {
        return sendPostFormRequest(url, formParams, null);
    }
}
