<template>
  <div>
    <button @click="downloadFile">说话</button>
    <div>{{ text }}</div>
  </div>
</template>

<script setup>
import { onMounted, watch, ref } from "vue";
import axios from "axios";
import PQueue from "p-queue";

const text = ref("");

// 创建一个队列实例，设置并发数为 1
const queue = new PQueue({ concurrency: 1 });
const queue1 = new PQueue({ concurrency: 1 });

// 需要tts的文本
const messageQueue = [];

// lastStrIndex 用于记录上一个字符串的结束位置
let lastStrIndex = 0;

// 将字符串根据标点符号断句分割，并添加到messageQueue中
const splitMessage = async (str) => {
  const punctuation = ["。", "！", "？", "；", "：", "，"];

  for (let i = lastStrIndex; i < str.length; i++) {
    if (punctuation.includes(str[i])) {
      const message = str.slice(lastStrIndex, i + 1);
      console.log(message, "==========");
      await playTTS(message);
      lastStrIndex = i + 1; // 更新上一个字符串的结束位置
    }
  }
};

const playTTS = async (ttsMessage) => {
  //const ttsMessage =
  //  "这个错误通常表示浏览器无法识别音频数据的格式或编码，导致无法加载音频源。为了解决这个问题，你可以尝试使用静态的 WAV 格式音频文件以确保能够正常播放，并且避免直接处理原始的音频数据。以下是一个示例代码来加载外部的 WAV 格式音频文件："; // 替换为你想要播报的文本

  try {
    const wgToken = `C1qziFGlIv3tnCQxcFaStrLuZOO2ZZXjN7FB_G0WlrOLjclfObbSaXAKzl4RWwQBf_0Zhsm0CoVvdVsYMD18iM_LJrxtn7LHJJQuF9UoUuF3fvqOwrG4EF6Z4GahtxtQ2oeaPQBBNKlgVW1xUW7tkhEdXWqzDHPA_I_91Lczk0PI4guhx1c88Hst4-HI8pdMbiUdEJzj3d3a2W06Fa0XA9Q0taAwaRd1k9jUrDVyj9GfS84_SIgJF4SPjWVfsraV79ieb_StgRcUwZjbscGPMlifnJD6F00wwNbxG7AuCHbl3EtMfSed1vuVx3AsizIckwzIVSVRpOGw72cdAMui-I6es9Ozj2ITzSa5KgyXEpX4qCHF1VcCM1wlHLQ_5hLnJIi4r8NsnJPsxMYrTw`;
    const res = await axios.post(
      `https://fls-ai-stg-sit.pingan.com.cn/openapi/ai/voice/tts/v2?channelId=ASP-TEST&sceneId=ASP-TEST&token=${wgToken}`,
      { sessionId: "N7FB_G0WlrOLjc", text: ttsMessage },
      {
        responseType: "arraybuffer",
        headers: {
          "X-Ai-TTS-Appid": "2b1317fb5b284b308dc90a6fdeae6c4e",
        },
      }
    );
    console.log(res.data);

    queue1.add(async () => {
      // 播放获取到的音频
      await playAudio(res.data);
    });
  } catch (error) {
    console.error("Error calling TTS API:", error);
  }
};

// const playAudio = async (audioData) => {
//   const blob = new Blob([audioData], { type: "audio/wav" });
//   const url = URL.createObjectURL(blob);
//   const audio = new Audio(url);
//   audio.onended = () => URL.revokeObjectURL(url);
//   audio.onerror = (error) => console.error("Audio playback error:", error);
//   audio
//     .play()
//     .then(() => console.log("Audio playing"))
//     .catch((error) => console.error("Error playing audio:", error));
// };

const playAudio = (audioData, options = {}) => {
  return new Promise((resolve, reject) => {
    const blob = new Blob([audioData], { type: "audio/wav" });
    const url = URL.createObjectURL(blob);
    const audio = new Audio(url);

    if (options.volume) {
      audio.volume = options.volume; // 设置音量
    }

    audio.onended = () => {
      URL.revokeObjectURL(url);
      resolve();
    };

    audio.onerror = (error) => {
      URL.revokeObjectURL(url);
      reject(error);
    };

    audio
      .play()
      .then(() => console.log("Audio playing"))
      .catch(reject);
  });
};

const downloadFile = async () => {
  const downloadUrl =
    "https://fls-ai.pingan.com.cn/openapi/ai/llm/forward/api/ai/nlp/dialogue?token=mVcexzY_mjtGAL5_exPlmAyfOJxuuEthWY1mk9tUFC_HwceY58uRZ2WDhz7-ttexCdUtFN8C7V636_jIq6fzaSfqIj8OQyhUPKPMa2eZjLlblT77ySqBt_lYM6iEAhrj7-raGmySMmkLS4Rqh651Ak2tqmUbjS64cqv5ofMsuadOCg1J-CtLFt7NeSoU4N3Kpm5MJ_4sOFBhQGfBym88dcwxosFl9LbvhpyleXFf6fOZkkOj0l2X8Nr2pfNjYs3_VOmCQxrxXh1XZ_a1v9qj5_rA9k9wGNNQfmr2JwJTUT4V9NwtNq94gNFt8C0J6MWKVE2eyr25Rke8tkKu3CGNNmspmEFpr6LavPlaWnWOIh9CRJ1cIDB70pg_JD2l0nPTkPbtaTQaIGTz"; // 替换为实际的下载URL

  try {
    const response = await axios.post(
      downloadUrl,
      {
        conversationId: "1976cfe3a5174f9ba768677f789cad7e",
        content: "请输出纯文本的回答，不要markdown：如何学习英语？",
        messageId: Date.now(),
        applicationId: "",
      },
      {
        headers: {
          "Team-Id": "123456",
          Authorization: "dffb9e92eec04c30bb441a5316a4e55c",
          "Content-Type": "application/json",
        },
        onDownloadProgress: ({ event }) => {
          //console.log(event);
          const xhr = event.target;
          const { responseText } = xhr;
          //   // Always process the final line
          //   const lastIndex = responseText.lastIndexOf(
          //     "\n",
          //     responseText.length - 2
          //   );
          //   let chunk = responseText;

          //   if (lastIndex !== -1) chunk = responseText.substring(lastIndex);
          //console.log(responseText, "chunk====");
          text.value = responseText;
          queue.add(async () => {
            await splitMessage(responseText);
          });
        },
      }
    );
    console.log(response);
    console.log(messageQueue, "messageQueue=======0000");
  } catch (error) {
    console.error("下载文件时出错:", error);
  }
};
onMounted(() => {});
</script>
