package com.sonic.cow.client.impl;

import com.alibaba.fastjson.JSONObject;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.sonic.cow.client.TtsClient;
import com.sonic.cow.client.config.TtsCnConfig;
import com.sonic.cow.client.input.tts.TtsInput;
import com.sonic.cow.client.output.tts.TtsOutput;
import com.sonic.cow.domain.input.VoiceTtsInput;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class TtsClientImpl implements TtsClient {

    @Autowired
    private TtsCnConfig ttsCnConfig;

    @Override
    public String tts(String userId, VoiceTtsInput input) {
        //构造入参对象
        TtsInput ttsInput = new TtsInput(ttsCnConfig.getTtsAppId(), ttsCnConfig.getCluster(), input.getVoiceType());

        //设置用户ID
        ttsInput.getUser().setUid(userId);
        //设置音频编码格式
        ttsInput.getAudio().setEncoding("wav");

        //设置语速
        ttsInput.getAudio().setLoudness_ratio(input.getLoudnessRatio());
        ttsInput.getAudio().setSpeed_ratio(input.getSpeedRatio());

        //设置入参文本内容
        ttsInput.getRequest().setText(input.getText());
        log.info("===> asr input : {}", JSONObject.toJSONString(ttsInput));
        try {
            //RPC 生成语音
            HttpResponse<String> result = Unirest.post("https://openspeech.bytedance.com/api/v1/tts")
                    .header("Authorization", "Bearer; " + ttsCnConfig.getTtsAccessToken())
                    .body(JSONObject.toJSONString(ttsInput))
                    .asString();
            String body = result.getBody();
            log.info("===> asr body : {}",  body);
            TtsOutput response = JSONObject.parseObject(body, TtsOutput.class);
            //获取data数据并存储到文件中
            System.out.println("==========> start");
            System.out.println(response.getData());
            System.out.println("==========> end");
            return response.getData();
        } catch (UnirestException e) {
            log.error("===> asr error : ", e);
        }
        return null;
    }

}
