import { useState } from "react";
import TextInputBar from "./TextInputBar";
import VoiceInputBar from "./VoiceInputBar";
import { textChat } from "@/service/bot";
import { TMessage,TRobotMessage, useTextChat } from "@/store/textChat";
import { TAgentDetail } from "@/types/agent";
import { delay, getLoginId } from "@/utils";
import { EAI_MODEL } from "@/consts/enum";
import { useUnload } from "@tarojs/taro";
import { EChatRole, EContentType } from "@/types/bot";

import { saveMessageToServer } from './message'


interface Props {
  agent: TAgentDetail | null;
  aiModel: EAI_MODEL;
  histories: (TMessage|TRobotMessage)[];
  setShowWelcome: (b: boolean) => void;
}

let stopReceiveChunk: (() => void) | undefined;
export default ({ agent, setShowWelcome, histories }: Props) => {
  const [isVoice, setIsVoice] = useState(false);
  const [disabled, setDisabled] = useState(false);
  const {
    pushRobotMessage,
    updateRobotMessage,
    getCurrentRobotMessage,
    updateRobotReasoningMessage,
    pushMessage,
    updateMessage,
    deleteMessage,
  } = useTextChat();
  
  let myMsgUk = '';
  let mySessionId = '';

  const handleTextInputBarSwitch = () => {
    console.log("voice input on");
    setIsVoice(true);
  };
  const handleVoiceInputBarSwitch = () => {
    console.log("voice input off");
    setIsVoice(false);
  };

  const chatWithGpt = async (message: string, sessionId: string, msgUk: string) => {
    setShowWelcome(false)
    let currentRobotMsgUk = "";
    await delay(300);
    setDisabled(true);
    if (!agent?.agentId) {
      return;
    }
    const loginId = getLoginId();
    if (!loginId) {
      return;
    }

    // const greeting = "欢迎光临我的智能体，你想问什么？";
    // {
    //   content: greeting,
    //   contentType: EContentType.TextPlain,
    //   role: EChatRole.System,
    // },
    
    const newMsg = {
      content: message,
      contentType: EContentType.TextPlain,
      role: EChatRole.User,
    }
    
    saveMessageToServer({
      loginId,
      messages: [{
        ...newMsg,
        isStreaming: false,
        msgUk,
      }],
      agentId: agent.agentId,
      sessionId,
    })

    // 发起文本聊天
    stopReceiveChunk = textChat({
      params: {
        agentId: agent.agentId,
        isEnableOutputAudioStream: false,
        isEnableSearch: false,
        isEnableThinking: false,
        loginId,
        messages: [newMsg],
        sessionId,
      },
      onStart: () => {
        currentRobotMsgUk = pushRobotMessage({
          role: EChatRole.Assistant,
          saveStatus: 2,
          content: "",
          reasoningContent: "",
          robot: {
            avatar: agent?.avatarUrl ?? "",
            name: agent?.name ?? "",
            agentId: agent?.agentId ?? "",
          },
        });
      },
      onReceived: (m) => {
        console.log("received:", m);
        if (m.reasoningContent) {
          updateRobotReasoningMessage(
            m.reasoningContent,
            currentRobotMsgUk
          );
        } else {
          updateRobotMessage(m.content);
        }
      },
      onFinished: () => {
        console.log("回复完毕 ok");
        const currentRobotMessage = getCurrentRobotMessage();
        console.log(currentRobotMessage,333)
        if(!agent.agentId){
          return
        }
        setDisabled(false);
        // 如果没有任何回答，则显示
        if (!currentRobotMessage?.content?.length) {
          updateRobotMessage("服务器繁忙...");
          return 
        }

        saveMessageToServer({
          loginId,
          messages: [{
            content: currentRobotMessage.content,
            contentType: EContentType.TextPlain,
            isStreaming: false,
            role: currentRobotMessage.role,
            msgUk: currentRobotMessage.msgUk,
          }],
          agentId: agent.agentId,
          sessionId,
        })
        
      },
      onError: () => {
        deleteMessage(currentRobotMsgUk);
        setDisabled(false);
      },
    });
  };
  const handleVoiceSend = (message: string) => {
    updateMessage(message, myMsgUk);
    chatWithGpt(message, mySessionId, myMsgUk);
  };
  const handleOnSend = async (message: string) => {
    if(!agent?.agentId){
      return
    }
    const {sessionId, msgUk} = pushMessage(message);
    chatWithGpt(message, sessionId, msgUk);
  };

  // 推一个自己的空气泡框
  const handleBeforeSend = () => {
    if(!agent?.agentId){
      return
    }
    const {sessionId, msgUk} = pushMessage("");
    myMsgUk = msgUk
    mySessionId = sessionId
  };

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

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

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

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