package com.hzs.third.translate.service.impl;

import cn.hutool.core.text.UnicodeUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.hzs.common.core.constant.Constants;
import com.hzs.common.core.exception.base.BaseException;
import com.hzs.third.translate.config.TranslateConfig;
import com.hzs.third.translate.dto.TranslateParam;
import com.hzs.third.translate.dto.TranslateResult;
import com.hzs.third.translate.service.ITranslateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description:
 * @Author: jiang chao
 * @Time: 2023/3/7 18:43
 * @Classname: TranslateServiceImpl
 * @PackageName: com.hzs.third.translate.service.impl
 */
@Slf4j
@Service
public class TranslateServiceImpl implements ITranslateService {

    @Autowired
    private TranslateConfig translateConfig;

    /**
     * 语言翻译
     *
     * @param param 翻译入参
     * @return
     */
    @Override
    public Map<String, String> translate(TranslateParam param) {
        try {
            // 请求参数加盐
            String salt = String.valueOf(System.currentTimeMillis());
            // MD5加密
            String sign = MD5.create().digestHex(translateConfig.getAppId() + param.getContent() + salt + translateConfig.getSecretKey()).toLowerCase();
            // 翻译内容进行URLEncode转码
            String content = URLEncoder.encode(param.getContent(), Constants.UTF8);

            // 返回的翻译对应map
            Map<String, String> resultMap = new ConcurrentHashMap<>();

            List<String> toList = param.getTo();
            if (CollectionUtils.isNotEmpty(toList)) {
                for (String str : toList) {
                    String url = translateConfig.getUrl() + "?q=" + content + "&from=" + param.getFrom() + "&to=" + str + "&appid=" + translateConfig.getAppId() + "&salt=" + salt + "&sign=" + sign;
                    log.info("异步翻译请求URL: {}", url);

                    String result = HttpUtil.get(url, CharsetUtil.CHARSET_UTF_8);
                    log.info("异步翻译返回内容：{}", result);

                    // 翻译返回内容为 unicode，需要进行解码
                    result = UnicodeUtil.toString(result);

                    TranslateResult translateResult = JSONUtil.toBean(result, TranslateResult.class);
                    if (null != translateResult && null != translateResult.getFrom()) {
                        // 返回成功并且有内容
                        resultMap.put(str, translateResult.getTrans_result().get(0).getDst());
                    }
//                    // 非企业认证，QPS=1
//                    Thread.sleep(1000);
                }
            }

            return resultMap;
        } catch (Exception e) {
            log.error("异步翻译异常！param: {}", param, e);
            throw new BaseException("异步翻译异常");
        }
    }

}
