package com.cretin.webservices.helper.translate;

import com.cretin.webcore.config.AppConstants;
import com.cretin.webdb.self.BaiduTranslateInfoModel;
import org.springframework.web.client.RestTemplate;

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

public class TransApi {
    private static final String TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate";

    private static String appid = "20220801001289939";
    private static String securityKey = "fMxDRYS6nmHcL81WfFzG";

    //记得去修改服务器ip https://api.fanyi.baidu.com/access/0/3

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

    public TransApi() {
    }

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

    private Map<String, String> buildParams(String query, String from, String to) {
        Map<String, String> params = new HashMap<String, String>();
        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;
    }

}
