package com.ruoyi.aicall.tts.doubao;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.aicall.utils.WavFileWriter;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class DoubaoTTSWebApi {
    private static final Logger log = LoggerFactory.getLogger(DoubaoTTSWebApi.class);
    private static String ttsAccountJson = null;
    private static DoubaoTtsAccount ttsAccount = null;

    private static OkHttpClient client;
    static{
        int ttsThreadNum = 20;
        client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .connectionPool(new ConnectionPool(ttsThreadNum, 12L, TimeUnit.HOURS))
                .build();
    }

    private static boolean processPOSTRequest(String accessToken, String voiceCode, String text, String audioSaveFile) {

        String API_URL = ttsAccount.getServer_url_webapi();
        String appid = ttsAccount.getApp_id();
        String voiceType = voiceCode;

        TtsRequest ttsRequest = TtsRequest.builder()
                .app(TtsRequest.App.builder()
                        .appid(appid)
                        .cluster("volcano_tts")
                        .build())
                .user(TtsRequest.User.builder()
                        .uid("uid")
                        .build())
                .audio(TtsRequest.Audio.builder()
                        .encoding("wav")
                        .voiceType(voiceType)
                        .build())
                .request(TtsRequest.Request.builder()
                        .reqID(UUID.randomUUID().toString())
                        .operation("query")
                        .text(text)
                        .build())
                .build();


        String reqBody = JSON.toJSONString(ttsRequest);
        log.info("request: {}", reqBody);

        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(MediaType.get("application/json; charset=utf-8"), reqBody);
        Request request = new Request.Builder()
                .url(API_URL)
                .header("Authorization", "Bearer;" + accessToken)
                .post(body)
                .build();

        try {
            Response response = client.newCall(request).execute();
            JSONObject result = JSONObject.parseObject(response.body().string());
            if (StringUtils.isNotBlank(result.getString("data"))) {
                WavFileWriter.writeWavFromBase64(result.getString("data"), audioSaveFile);
                response.close();
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("Doubao tts合成失败：{}", e.toString());
            return false;
        }
    }

    public static boolean shortTextTTSWebAPI(String voiceCode, String text, String ttsPath, String doubaoTtsAccountJson) {
         if (StringUtils.isBlank(text.trim())) {
            log.info("tts text cant not be null, ttsPath:" + ttsPath);
            return true;
        }
        ttsAccountJson = doubaoTtsAccountJson;
        ttsAccount = JSON.parseObject(ttsAccountJson, DoubaoTtsAccount.class);
        return processPOSTRequest(ttsAccount.getAccess_token(), voiceCode, text, ttsPath);
    }

    public static void main(String[] args) {
        shortTextTTSWebAPI("zh_female_vv_uranus_bigtts", "您好，请问您是张三先生吗", "D://file/test2.wav", "{\"access_token\":\"esgS1pvKY_jdvpDezc0EFjJbYGPVTY7j\",\"cluster\":\"volcano_tts\",\"emotion\":\"happy\",\"sample_rate\":\"16000\",\"write_pcm_enable\":\"0\",\"ws_conn_timeout_ms\":\"9000\",\"speech_rate\":\"1\",\"voice_name\":\"S_T7d3irgK1\",\"language\":\"0\",\"server_url\":\"wss://openspeech.bytedance.com/api/v1/tts/ws_binary\",\"server_url_webapi\":\"https://openspeech.bytedance.com/api/v1/tts\",\"app_id\":\"8380189306\"}");
    }
}