package com.m2pool.manage.utils;

import com.tencentcloudapi.common.AbstractModel;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.tmt.v20180321.TmtClient;
import com.tencentcloudapi.tmt.v20180321.models.TextTranslateBatchRequest;
import com.tencentcloudapi.tmt.v20180321.models.TextTranslateBatchResponse;
import com.tencentcloudapi.tmt.v20180321.models.TextTranslateRequest;
import com.tencentcloudapi.tmt.v20180321.models.TextTranslateResponse;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class TranslateUtils {
    //private static final String TRANS_API_HOST = "https://fanyi-api.baidu.com/api/trans/vip/translate";
    //
    //
    //private static String appid = "20250731002420396";
    //private static String securityKey ="fSFN5UNOV4tfm5oBDuin";


    private static final String TENCENTCLOUD_SECRET_KEY = "jFZhcKo4AGJBB9xYx98tSpyueBVcbWSL";

    private static final String TENCENTCLOUD_SECRET_ID = "AKIDEH8mFVYO1WosjOq57ze6LNBl8JJ5ez72";


    /**
     * 翻译 HTML 内容，仅翻译标签内的文本，优化为批量翻译
     * @param html 原始 HTML 字符串
     * @param from 源语言
     * @param to 目标语言
     * @return 翻译后的 HTML 字符串
     */
    public static String translateHtml(String html, String from, String to) {
        Document doc = Jsoup.parse(html);
        // 收集所有文本节点
        List<TextNode> textNodes = new ArrayList<>();
        collectTextNodes(doc.body(), textNodes);

        List<String> originalTexts = new ArrayList<>();
        for (TextNode node : textNodes) {
            String text = node.text().trim();
            if (!text.isEmpty() && text.matches(".*[\\u4e00-\\u9fa5].*")) {
                originalTexts.add(text);
            }
        }

        String[] htmlTextList = originalTexts.toArray(new String[0]);
        List<String> textList = translateBatch(htmlTextList, from, to);

        int index = 0;
        for (TextNode node : textNodes) {
            String text = node.text().trim();
            if (!text.isEmpty() && text.matches(".*[\\u4e00-\\u9fa5].*") && index < textList.size()) {
                String translatedText = textList.get(index);
                node.text(node.text().replace(text, translatedText));
                index++;
            }
        }

            System.out.println("翻译后的HTML"+doc.html());

        return doc.html();
    }

    /**
     * 获取元素下所有文本节点
     * @param element
     * @param textNodes
     */
    private static void collectTextNodes(Element element, List<TextNode> textNodes) {
        for (Node child : element.childNodes()) {
            if (child instanceof TextNode) {
                TextNode textNode = (TextNode) child;
                // 获取原文本内容，并在首尾添加空格
                String newText = " " + textNode.text() + " ";
                textNode.text(newText);
                textNodes.add((TextNode) child);
            } else if (child instanceof Element) {
                collectTextNodes((Element) child, textNodes);
            }
        }
    }


    /**
     * 腾讯机器文本批量翻译
     * @param htmlTextList
     * @return
     */
    public static String[] tencentTextBatchTranslate(String[] htmlTextList, String from, String to){
        try{
            Credential cred = new Credential(TENCENTCLOUD_SECRET_ID, TENCENTCLOUD_SECRET_KEY);
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("tmt.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            TmtClient client = new TmtClient(cred, "ap-beijing", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            TextTranslateBatchRequest req = new TextTranslateBatchRequest();
            req.setSource(from);
            req.setTarget(to);
            req.setProjectId(0L);
            req.setSourceTextList(htmlTextList);
            TextTranslateBatchResponse resp = client.TextTranslateBatch(req);
            return resp.getTargetTextList();
        }catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
            return new String[0];
        }

    }

    public static List<String> translateBatch(String[] htmlText, String from, String to) {

        int totalLength = 0;
        int index = 0;
        int lastRecordIndex = 0;
        List<String> result = new ArrayList<>();

        for (String str : htmlText) {
            if (str != null) {
                totalLength += str.length();
                // 本次长度大于 6000
                if (totalLength >= 6000) {
                    // 截取上次记录坐标 lastRecordIndex 到当前遍历到数组的下标 index - 1
                    String[] subArray = Arrays.copyOfRange(htmlText, lastRecordIndex, index);
                    String[] subResult = tencentTextBatchTranslate(subArray, from, to);
                    result.addAll(Arrays.asList(subResult));
                    // 更新 lastRecordIndex 和 totalLength
                    lastRecordIndex = index;
                    totalLength = str.length();
                }
            }
            index++;
        }

        // 处理剩余部分
        if (lastRecordIndex < htmlText.length) {
            String[] remainingArray = Arrays.copyOfRange(htmlText, lastRecordIndex, htmlText.length);
            if (remainingArray.length > 0) {
                String[] remainingResult = tencentTextBatchTranslate(remainingArray, from, to);
                result.addAll(Arrays.asList(remainingResult));
            }
        }

        return result;
    }
    public static String translate(String sourcText, String from, String to){
        return tencentTextTranslate(sourcText,from,to);
    }

    /**
     *  腾讯机器单文本翻译
     * @param sourcText
     * @param from
     * @param to
     * @return
     */
    public static String tencentTextTranslate(String sourcText, String from, String to){
        try{
            Credential cred = new Credential(TENCENTCLOUD_SECRET_ID, TENCENTCLOUD_SECRET_KEY);
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("tmt.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            TmtClient client = new TmtClient(cred, "ap-beijing", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            TextTranslateRequest req = new TextTranslateRequest();
            req.setSource(from);
            req.setTarget(to);
            req.setProjectId(0L);
            req.setSourceText(sourcText);
            TextTranslateResponse resp = client.TextTranslate(req);

            System.out.println("结果"+ resp.getTargetText());
            return resp.getTargetText();
        }catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
            return "";
        }

    }


    public static void main(String[] args) {
        //translateHtml("<h2 style=\"line-height: 2.5;\"><img src=\"https://m2pool.com/img/nexa.png\" alt=\"\" data-href=\"https://m2pool.com/img/nexa.png\" style=\"width: 25.50px;height: 25.50px;\"/><span style=\"color: rgba(0, 0, 0, 0.6); background-color: rgb(255, 255, 255);\">&nbsp;</span><font size=\"5\">Nexa 挖矿教程&nbsp;</font></h2><span id=\"step2\"></span><p><br/></p><h3>选择挖矿地址</h3><table style=\"width: auto;\"><tbody><tr><th colspan=\"1\" rowspan=\"1\" width=\"182.54\" style=\"text-align: center;\"> &nbsp; 币种 &nbsp;</th><th colspan=\"1\" rowspan=\"1\" width=\"157\" style=\"text-align: center;\"><span style=\"color: rgb(207, 19, 34);\">最小起付额</span></th><th colspan=\"1\" rowspan=\"1\" width=\"446.12\" style=\"text-align: center;\">TCP 端口</th><th colspan=\"1\" rowspan=\"1\" width=\"477.26\" style=\"text-align: center;\">SSL 端口</th></tr><tr><td colspan=\"1\" rowspan=\"1\" width=\"auto\" style=\"text-align: center;\"> <img src=\"https://m2pool.com/img/nexa.png\" alt=\"\" data-href=\"https://m2pool.com/img/nexa.png\" style=\"width: 20.55px;height: 20.55px;\"/> Nexa</td><td colspan=\"1\" rowspan=\"1\" width=\"auto\" style=\"text-align: center;\"><span style=\"color: rgb(207, 19, 34);\">10000</span></td><td colspan=\"1\" rowspan=\"1\" width=\"auto\" style=\"text-align: center;\">stratum+tcp://nexa.m2pool.com:33333 <br/></td><td colspan=\"1\" rowspan=\"1\" width=\"auto\" style=\"text-align: center;\">stratum+ssl://nexa.m2pool.com:33335</td></tr></tbody></table><h3></h3><h2></h2><h3><br/></h3><h3>适配性</h3><pre><code></code></pre><table border=\"0\" width=\"100%\" cellpadding=\"0\" cellspacing=\"0\"><tbody><tr><th>币种</th><th>GPU挖矿软件</th><th>ASIC矿机型号</th></tr><tr><td><img src=\"https://m2pool.com/img/nexa.png\" alt=\"\" width=\"20.69\" height=\"20.69\"/>&nbsp;Nexa</td><td>bzminer、lolminer、Rigel、WildRig</td><td>龍珠A21</td></tr></tbody></table><p>注意：如果您的GPU挖矿软件或ASIC矿机与m2pool无法适配,请通过<a href=\"mailto:support@m2pool.com\">邮件:support@m2pool.com&nbsp;</a>与我们取得联系。</p><p><span id=\"step\"></span></p><h3 style=\"line-height: 3;\">步骤1 - 注册m2pool账号</h3><hr/><p style=\"text-indent: 2em; line-height: 2.5;\">1. m2pool 矿池挖矿方式为用户名挖矿，需注册m2pool账号</p><p style=\"text-indent: 2em; line-height: 2.5;\"><span style=\"text-indent: 2em;\">2.注册账号成功后，请前往个人中心-挖矿账户页面，添加币种挖矿账户，此处创建的挖矿账户即为您需要在矿机上配置的用户名。</span></p><p style=\"text-indent: 2em; text-align: start; line-height: 2.5;\"><br/></p><h3 style=\"line-height: 3;\">步骤2 - 获得并绑定钱包地址</h3><hr/><p style=\"text-indent: 2em; text-align: left; line-height: 2.5;\">1. 获取钱包，您可以通过以下方式获得币种的的钱包地址，用于接收挖矿收益。</p><p style=\"text-indent: 2em; text-align: start; line-height: 2.5;\"> &nbsp; (1) 官方全节点钱包：<a href=\"https://nexa.org/\" target=\"\">https://nexa.org/</a>, 该类型钱包需要实时同步币种区块链节点。</p><p style=\"text-indent: 2em; text-align: start; line-height: 2.5;\"> &nbsp; (2) 交易所钱包:前往支持该币种现货交易的交易所，<a href=\"https://www.mxc.com/\" target=\"\">MEXC</a>、 <a href=\"https://www.coinex.com/zh-hans/\" target=\"\">CoinEx</a> 等，找到充值即可获得钱包。</p><p style=\"text-indent: 2em; text-align: start; line-height: 2.5;\"> &nbsp; (3) 硬件钱包:取决于您的硬件钱包是否支持该币种区块链，该类型钱包安全性高，但不是所有硬件钱包都支持，请您仔细了解您的硬件钱包。 &nbsp;</p><p style=\"text-indent: 2em; text-align: left; line-height: 2.5;\">2. 获得钱包地址后，在个人中心-挖矿账户页面，点击右上方添加按钮，在钱包地址一栏填入您的钱包即可。</p><p style=\"text-indent: 2em; text-align: left; line-height: 2.5;\"><br/></p><p>步骤3 - 矿工接入参数示例</p><hr/><p style=\"text-indent: 2em; text-align: left; line-height: 2.5;\">1. Pool/Url: 见上方<a href=\"#table\" target=\"\"><span style=\"color: rgb(146, 84, 222);\"></span></a><a href=\"#step2\">挖矿地址</a>表格</p><p style=\"text-indent: 2em; text-align: left; line-height: 2.5;\">2. Wallet/User/Worker: 挖矿账户名.矿工号(英文句号.分隔挖矿账户名和矿工号),(用户名为您在 <a href=\"https://m2pool.com/zh/AccessMiningPool/nexaAccess#step2\" target=\"\"><span style=\"color: rgb(146, 84, 222);\"></span></a><a href=\"#step\">步骤1的第2步</a>生成的挖矿账号(非m2pool的登陆邮箱号)，矿工号为您自行定义(长度不超过36个字符)，如果您有多个矿工，请勿设置相同的矿工号，设置相同矿工号会将多个矿工的算力合并，虽然不会影响您的收益，但这会导致无法区分不同的矿工，不便于您对矿工的管理。) </p><p style=\"text-indent: 2em; text-align: left; line-height: 2.5;\">3.Password:任意输入,不同的挖矿软件或矿机可能会有不同的配置方式，但只需保证上述3个参数配置正确，即可接入m2pool矿池，如果您需要帮助，请通过 <a href=\"mailto:support@m2pool.com\" target=\"\"><span style=\"color: rgb(146, 84, 222);\">邮件</span></a><span style=\"color: rgb(146, 84, 222);\"> </span>联系我们。 </p><p style=\"text-indent: 2em; text-align: left; line-height: 2.5;\"><br/></p><h3 style=\"text-align: left; line-height: 2.5;\">步骤4 - 坐等挖矿收益</h3><hr/><p style=\"text-indent: 2em; text-align: left; line-height: 2.5;\">1.在您添加完挖矿钱包后，即可在您的矿机上配置相关参数，开启挖矿。</p><p style=\"text-indent: 2em; text-align: left; line-height: 2.5;\">2. 您在m2pool上的所有挖矿收益均为自动结算(不同币种有不同的收益结算方式，请仔细查看您选择币种的收益结算方式)。</p><p><br/></p>\n", "zh", "en");
        translateHtml("  <pre _msthidden=\"3\"><code>{\n" +
                "\n" +
                "<font color=\"#ff0000\">\"code\": {ERR_CODE},</font>\n" +
                "\n" +
                "\"msg\": \"错误描述\"\n" +
                "\n" +
                "}</code></pre>\n","zh","en");
        //translate("牛逼", "zh", "en");
    }




}
