package thyyxxk.webserver.utils;

import cn.xfyun.api.TtsClient;
import cn.xfyun.model.response.TtsResponse;
import cn.xfyun.service.tts.AbstractTtsWebSocketListener;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import okhttp3.WebSocket;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.entity.ResultVo;

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

/**
 * @author dj
 */
@Slf4j
public class VoiceUtil {
    private static final String appId = "21cb4067";
    private static final String apiKey = "c49c636d0a771bc694d75d3433cd84e3";
    private static final String apiSecret = "MjAzNTk3MDRiODc2NmU2ZjMxMTBhYzZl";

    private static void deleteOldFile(String serialNo) {
        String path = "D:\\apache-tomcat-9.0.30\\webapps\\voices\\" + serialNo + ".mp3";
        File file = new File(path);
        if (file.exists()) {
            if (file.delete()) {
                log.info("删除重复文件：{}", serialNo);
            }
        }
    }

    public static ResultVo<String> textToSpeech(String data, String id) {
        deleteOldFile(id);
        String voiceUrl = "http://172.16.32.160:8888/voices/" + id + ".mp3";
        String filePath = "D:\\apache-tomcat-9.0.30\\webapps\\voices\\" + id + ".mp3";
        final Boolean[] progress = { false, null };
        final String[] message = {""};
        try  {
            TtsClient ttsClient = new TtsClient.Builder()
                    .signature(appId, apiKey, apiSecret)
                    .vcn("aisjinger")
                    .volume(100)
                    .build();
            File file = new File(filePath);
            ttsClient.send(data, new AbstractTtsWebSocketListener(file) {
                @Override
                public void onSuccess(byte[] bytes) {
                    progress[0] = true;
                }
                @Override
                public void onFail(WebSocket webSocket, Throwable throwable, Response response) {
                    log.error("生成语音文件失败：{}", throwable.getMessage());
                    message[0] = throwable.getMessage();
                }

                @Override
                public void onBusinessFail(WebSocket webSocket, TtsResponse ttsResponse) {
                    log.error("生成语音文件失败：{}", ttsResponse.toString());
                    message[0] = ttsResponse.toString();
                }

                @Override
                public void onClosing(WebSocket webSocket, int code, String reason) {
                    super.onClosing(webSocket, code, reason);
                }

                @Override
                public void onClosed(WebSocket webSocket, int code, String reason) {
                    super.onClosed(webSocket, code, reason);
                    progress[1] = true;
                }
            });
        }catch (Exception e){
            log.error("生成语音文件失败", e);
            log.error("错误码查询链接：https://www.xfyun.cn/document/error-code");
            message[0] = e.getMessage();
            progress[1] = true;
        }

        while (null == progress[1]) {
            try {
                TimeUnit.MILLISECONDS.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        if (progress[0]) {
            return ResultVoUtil.success(voiceUrl);
        }
        return ResultVoUtil.fail(ExceptionEnum.INTERNAL_SERVER_ERROR, message[0]);
    }
}
