package com.kingdee.eas.custom.synctask.util;

import okhttp3.*;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.security.MessageDigest;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import com.alibaba.fastjson.JSONObject;

public class HttpClientUtil {
    private static final Logger logger = Logger.getLogger(HttpClientUtil.class);
    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .build();

    /**
     * 发送 POST 请求（JSON 格式）
     * @param urlPath   接口地址（可含路径参数，如 `/api/v2/transaction/get`）
     * @param params    JSON 请求体
     * @param queryParams URL 查询参数（如 `timestamp` 和 `token`）
     * @return 响应体字符串（失败返回 null）
     */
    public static String sendPostRequest(String urlPath, JSONObject params, Map<String, String> queryParams) {
        try {
            // 1. 构建完整 URL（含查询参数）
            HttpUrl.Builder urlBuilder = HttpUrl.parse(urlPath).newBuilder();
            if (queryParams != null) {
                queryParams.forEach(urlBuilder::addQueryParameter);
            }
            String fullUrl = urlBuilder.build().toString();

            // 2. 创建请求体
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, params.toJSONString());

            // 3. 构建请求
            Request request = new Request.Builder()
                    .url(fullUrl)
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .build();

            // 4. 发送请求并处理响应
            try (Response response = client.newCall(request).execute()) {
                if (response.isSuccessful() && response.body() != null) {
                    return response.body().string();
                } else {
                    logger.error("请求失败，状态码: " + response.code());
                }
            }
        } catch (IOException e) {
            logger.error("请求异常: " + e.getMessage(), e);
        }
        return null;
    }


}