package com.zg.common.utils.http;

import okhttp3.*;

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

public class OkHttpUtils {

    // 通用客户端配置：10 秒连接，15 秒读/写
    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(15, TimeUnit.SECONDS)
            .writeTimeout(15, TimeUnit.SECONDS)
            .build();

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

    /**
     * GET 请求（不带 header）
     */
    public static String get(String url) {
        Request request = new Request.Builder().url(url).get().build();
        return execute(request);
    }

    /**
     * GET 请求（带自定义 header）
     */
    public static String getWithHeaders(String url, Map<String, String> headers) {
        Request.Builder builder = new Request.Builder().url(url);
        if (headers != null) {
            headers.forEach(builder::addHeader);
        }
        return execute(builder.get().build());
    }

    /**
     * POST 请求（表单提交）
     */
    public static String postForm(String url, Map<String, String> formParams) {
        FormBody.Builder formBuilder = new FormBody.Builder();
        if (formParams != null) {
            formParams.forEach(formBuilder::add);
        }
        Request request = new Request.Builder()
                .url(url)
                .post(formBuilder.build())
                .build();
        return execute(request);
    }

    /**
     * POST 请求（JSON 提交）
     */
    public static String postJson(String url, String jsonBody) {
        RequestBody body = RequestBody.create(jsonBody, JSON);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        return execute(request);
    }

    /**
     * POST 请求（JSON + header）
     */
    public static String postJsonWithHeaders(String url, String jsonBody, Map<String, String> headers) {
        RequestBody body = RequestBody.create(jsonBody, JSON);
        Request.Builder builder = new Request.Builder().url(url).post(body);
        if (headers != null) {
            headers.forEach(builder::addHeader);
        }
        return execute(builder.build());
    }

    /**
     * 执行请求
     */
    private static String execute(Request request) {
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new RuntimeException("请求失败，状态码：" + response.code());
            }
            return response.body() != null ? response.body().string() : "";
        } catch (IOException e) {
            throw new RuntimeException("请求异常：" + e.getMessage(), e);
        }
    }
}
