package org.jeecg.modules.adweb.common.util;

import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.translate.AmazonTranslate;
import com.amazonaws.services.translate.AmazonTranslateClient;
import com.amazonaws.services.translate.model.TranslateTextRequest;
import com.amazonaws.services.translate.model.TranslateTextResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @Description:
 * @Author: wrk
 * @date 2022/8/3 11:03
 */
@Component
@Slf4j
public class AwsTranslateUtils {

    private static final String REGION = "us-west-2";

    @Value("${aws.translate.accessKey}")
    private String accessKey;

    @Value("${aws.translate.secretKey}")
    private String secretKey;


    /**
     * 翻译中文
     * @param text
     * @return
     */
    public String translate(String text){
        try {
            BasicAWSCredentials awsCreds = new BasicAWSCredentials(accessKey, secretKey);
            AmazonTranslate translate = AmazonTranslateClient.builder()
                    .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
                    .withRegion(REGION)
                    .build();

            TranslateTextRequest request = new TranslateTextRequest()
                    .withText(text)
                    .withSourceLanguageCode("auto")
                    .withTargetLanguageCode("zh");
            TranslateTextResult result  = translate.translateText(request);
            return result.getTranslatedText();
        } catch (Exception e){
            log.error("调用亚马逊翻译接口失败", e);
        }
        return "";
    }
}
