import { useState } from "react";
import TextInputBar from "./TextInputBar";
import VoiceInputBar from "./VoiceInputBar";
import { textChat } from "@/service/bot";
import { useTextChat } from "@/store/textChat";
import { TAgentDetail } from "@/types/agent";
import { delay } from "@/utils";
import { EAI_MODEL } from "@/consts/enum";
import { useUnload } from "@tarojs/taro";
interface Props {
  character: TAgentDetail;
  aiModel: EAI_MODEL;
}

let stopReceiveChunk: (()=> void)|undefined
export default ({ character, aiModel }: Props) => {
  const [isVoice, setIsVoice] = useState(false);
  const [disabled, setDisabled] = useState(false);
  const {
    pushRobotMessage,
    updateRobotMessage,
    getCurrentRobotMessage,
    updateRobotReasoningMessage,
    pushMessage,
    updateMessage,
    deleteMessage,
  } = useTextChat();
  // const currentRobotMessageId = useTextChat((state)=> state.currentRobotMessageId);
  let myMessageId = '';

  const handleTextInputBarSwitch = () => {
    console.log("voice input on");
    setIsVoice(true);
  };
  const handleVoiceInputBarSwitch = () => {
    console.log("voice input off");
    setIsVoice(false);
  };
  
  
  
  const chatWithGpt = async (message: string) => {
    
  let currentRobotMessageId = ''
    await delay(300);
    setDisabled(true);
    // 发起文本聊天
    stopReceiveChunk = textChat({
      agentId: character.agentId,
      params: { message, model: aiModel },
      onStart: () => {
        currentRobotMessageId = pushRobotMessage({
          content: "",
          reasoningContent: "",
          robot: {
            avatar: character.avatarUrl ?? "",
            name: character.name ?? "",
            agentId: character.agentId ?? "",
          },
        });
      },
      onReceived: (m) => {
        // console.log(m.reasoningContent,3333)
        if (m.reasoningContent) {
          updateRobotReasoningMessage(m.reasoningContent, currentRobotMessageId);
        } else {
          updateRobotMessage(m.content);
        }
      },
      onFinished: () => {
        console.log("回复完毕 ok");
        const currentRobotMessage = getCurrentRobotMessage()
        // 如果没有任何回答，则显示
        if(!currentRobotMessage?.content?.length){
          updateRobotMessage('服务器繁忙...')
        }
        setDisabled(false);
      },
      onError: () => {
        deleteMessage(currentRobotMessageId);
        setDisabled(false);
      },
    });
  };
  const handleVoiceSend = (message: string) => {
    updateMessage(message, myMessageId);
    chatWithGpt(message);
  };
  const handleOnSend = (message: string) => {
    pushMessage(message);
    chatWithGpt(message);
  };

  // 推一个自己的空气泡框
  const handleBeforeSend = () => {
    myMessageId = pushMessage("");
  };

  // 发生主意识别错误时，删除当前自己发出的气泡框
  const handleVoiceError = () => {
    deleteMessage(myMessageId);
  };

  useUnload(()=> {
    if(stopReceiveChunk){
      stopReceiveChunk()
    }
  })

  if (isVoice) {
    // 语音输入
    return (
      <VoiceInputBar
        disabled={disabled}
        onSend={handleVoiceSend}
        beforeSend={handleBeforeSend}
        onIconClick={handleVoiceInputBarSwitch}
        onError={handleVoiceError}
      />
    );
  }

  // 文本输入
  return (
    <TextInputBar
      disabled={disabled}
      onSend={handleOnSend}
      onIconClick={handleTextInputBarSwitch}
    ></TextInputBar>
  );
};
