package com.supervision.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.supervision.dto.paddlespeech.req.TtsReqDTO;
import com.supervision.dto.paddlespeech.res.PaddleSpeechResDTO;
import com.supervision.dto.paddlespeech.res.TtsResultDTO;
import com.supervision.exception.BusinessException;
import org.springframework.core.env.Environment;

public class TtsUtil {

    private static final String TTS_URL = SpringBeanUtil.getBean(Environment.class).getProperty("paddle-speech.tts");

    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static TtsResultDTO ttsTransform(String str) {
        // 构建
        String post = HttpUtil.post(TTS_URL, JSONUtil.toJsonStr(new TtsReqDTO(str)));
        try {
            PaddleSpeechResDTO<TtsResultDTO> response = objectMapper.readValue(post, new TypeReference<PaddleSpeechResDTO<TtsResultDTO>>() {
            });
            if (!response.getSuccess() || ObjectUtil.isEmpty(response.getResult())) {
                throw new BusinessException("文字转换语音失败");
            }
            return response.getResult();
        } catch (Exception e) {
            throw new BusinessException("语音转换文字失败", e);
        }

    }
}
