package com.cf.imes.module.system.framework.trans.config;

import cn.hutool.core.text.UnicodeUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cf.imes.module.system.framework.trans.core.HttpGet;
import com.cf.imes.module.system.framework.trans.core.MD5;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author Gqr
 * @since 2025/11/11 9:34
 */
public class TransApi {

    private String appid;
    private String securityKey;
    private String apiHost;

    public TransApi(String appid, String securityKey, String apiHost) {
        this.appid = appid;
        this.securityKey = securityKey;
        this.apiHost = apiHost;
    }

    public String getTransResult(String query, String from, String to) {
        Map<String, String> params = buildParams(query, from, to);
        return HttpGet.get(apiHost, params);
    }

    private Map<String, String> buildParams(String query, String from, String to) {
        Map<String, String> params = new HashMap<>();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);

        params.put("appid", appid);

        // 随机数
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt", salt);

        // 签名
        String src = appid + query + salt + securityKey; // 加密前的原文
        params.put("sign", MD5.md5(src));

        return params;
    }

    public static void main(String[] args) {
        TransApi api = new TransApi("20251110002494620", "_CUXY5Hk4WLBnYRQBcWw","https://fanyi-api.baidu.com/api/trans/vip/translate");
        String query = "测试翻译机\n" +
                "语言是什么";
        String json = api.getTransResult(query, "auto", "cht");

        JSONObject obj = JSON.parseObject(json);
        JSONArray arr = obj.getJSONArray("trans_result");

        for (int i = 0; i < arr.size(); i++) {
            JSONObject item = arr.getJSONObject(i);
            String src = item.getString("src");
            String dst = item.getString("dst");
            System.out.println(src + " => " + UnicodeUtil.toString(dst));
        }
    }
}
