package com.ho.common.tools.util;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONObject;

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

/**
 * @author kerwin
 */
@Slf4j
public class TranslateUtils {

    public static final String API_KEY = "hNDgbvTzhQymYvVvcAhCWEkh";
    public static final String SECRET_KEY = "tkgqkVDEJi8xBSrToNPdJdV2CYFNZM31";

    public static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().readTimeout(300, TimeUnit.SECONDS).build();


    // 静态翻译方法：输入待翻译文本，返回目标语言文本
    public static String translate(String text,String lang)  {
        MediaType mediaType = MediaType.parse("application/json");
        // 动态构建请求体（支持任意文本）
        String jsonBody = String.format("{\"from\":\"zh\",\"to\":\""+lang+"\",\"q\":\"%s\"}", text);
        RequestBody body = RequestBody.create(mediaType, jsonBody);

        Request request = null;
        try {
            request = new Request.Builder()
                    .url("https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=" + getAccessToken())
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Accept", "application/json")
                    .build();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        try (Response response = HTTP_CLIENT.newCall(request).execute()) {
            String responseBody = response.body().string();
            // 解析JSON获取dst值
            return parseDstFromResponse(responseBody);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 解析JSON响应并提取dst
    private static String parseDstFromResponse(String jsonResponse) {
        JSONObject root = new JSONObject(jsonResponse);
        JSONObject result = root.getJSONObject("result");
        JSONArray transResult = result.getJSONArray("trans_result");
        // 获取第一条翻译结果的dst字段
        String disStr = transResult.getJSONObject(0).getString("dst");
        if(disStr.contains("Zhongzi Technology")){
            disStr =  disStr.replace("Zhongzi Technology","Sinotech");
        }
        return disStr;
    }

    // 示例调用
    public static void main(String[] args) throws IOException {
        String translated = translate("电站汇总数据","fra");
        System.out.println("翻译结果: " + translated); // 输出: active power
    }


    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }

}
