import { requestTextToSpeech } from "@/service/chat";
import { useAudioStreamPlayer } from "@/utils/audioStreamPlayer";

// 在消息框内点击播放音频消息 
export const useTextToSpeech = () => {
  // 聊天消息流式音频播报
  const { setFistChunk, pushBase64ToQuene, playChunk, stopPlayChunk, setIsLastChunk, onPlayerStatusChanged } =
    useAudioStreamPlayer();

  
  let stopCurrentChunk:any, currentReqTask:any
  const startSpeech = (currentTextToSpeech: {
    agentId: string,
    loginId: string,
    msgUk: string,
    text: string
  }) => {
    if(!currentTextToSpeech){
      return
    }
    let isFirstChunk = true;
    const { reqTask, stopChunk } = requestTextToSpeech({
      params: currentTextToSpeech,
      onStart: () => {
        isFirstChunk = true;
      },
      // 音频输出单独处理
      onAudioParsed: (m) => {
        const audioStr = m?.audio ?? "";
        if (isFirstChunk) {
          isFirstChunk = false;
          setFistChunk(audioStr, reqTask);
        } else {
          pushBase64ToQuene(audioStr);
        }
        playChunk();
      },
      onReceived: (m) => {},
      onFinished: async (m) => {
        
      },
      onComplete: async () => {
        isFirstChunk = true;
        // chunk 接收已结束
        setIsLastChunk()
      },
      onError: () => {},
    });
    stopCurrentChunk = stopChunk
    currentReqTask = reqTask
  }
  

  const stopSpeech = ()=> {
    stopCurrentChunk?.();
    stopPlayChunk?.();
  }

  

  return {
    startSpeech,
    stopSpeech,
    onPlayerStatusChanged,
  };
};
