import { appendMessages } from "@/service/chat"
import { type TAppendMessages, TRobotMessage, EContentType, EChatRole } from "@/types/bot";
import { isSuccess } from "@/utils";
import { useRef, useEffect, useState } from "react";


export const sendMyMessageToServer = async (data: {
  message: string, 
  loginId: string, 
  agentId: string,
  msgUk: string,
  sessionId: string,
})=> {
  let result = false
  const newMsg = {
    content: data.message,
    contentType: EContentType.TextPlain,
    role: EChatRole.User,
  };
  try{
    // 将发送的消息上报
    const myMsgResponse = await saveMessageToServer({
      loginId: data.loginId,
      messages: [
        {
          ...newMsg,
          saveStatus: 2,
          isStreaming: false,
          msgUk: data.msgUk,
        },
      ],
      agentId: data.agentId,
      sessionId: data.sessionId,
    });
    if(isSuccess(myMsgResponse.status)){
      result = true;
    }
  }catch(e){
    result = false;
  }
  return result
}

export const saveMessageToServer = (data: TAppendMessages) => {
  const postData = {
    ...data,
    messages: data.messages.map((message)=> {
      
      if(message.contentType === EContentType.AiseekQA){
        message.content = JSON.stringify(message.content)
        return message
      }
      return message
    })
  }
  return appendMessages(postData)
}


// 保存智能体消息内容至服务器
export const saveAgentChatContentToServer = async (currentRobotMessage: TRobotMessage, loginId:string, agentId:string, sessionId: string) => {
  const currentContentType = currentRobotMessage?.body?.contentType
  let content = ''
  // audio chunk 不需要上报，在初始时已经上报
  if(currentContentType === EContentType.AiseekAudioChunk && currentRobotMessage?.body?.content.sentenceBegin){
    // 只保存文本至服务器
    content = (currentRobotMessage?.content as string) ?? ''
  }else if(currentContentType === EContentType.AiseekQA ){
    // 也原样保存至服务器
    content = currentRobotMessage?.body?.content ?? currentRobotMessage.content as string
  }else{
    content = (currentRobotMessage?.content as string) ?? ''
  }

  const robot = currentRobotMessage.robot ?? {}
  await saveMessageToServer({
    loginId,
    messages: [{
      saveStatus: 2,
      content: content,
      contentType: currentContentType ?? EContentType.TextPlain,
      isStreaming: true,
      robot: {...robot},
      role: currentRobotMessage.role,
      msgUk: currentRobotMessage.msgUk,
    }],
    agentId: agentId,
    sessionId,
  })
}

// 定时上报智能体回复的消息体

export const usePostMessage = (getCurrentRobotMessage: () => TRobotMessage | undefined) => {
  const timerRef = useRef<NodeJS.Timeout | null>(null);
  const isRunningRef = useRef(false);
  const dataRef = useRef<any>({});
  const [isRunning, setIsRunning] = useState(false);
  // 保存间隔时间的ref，方便在回调中访问最新值
  const intervalRef = useRef<number>(5000);

  // 组件卸载时清理定时器
  useEffect(() => {
    return () => {
      stopTimedMessage();
    };
  }, []);

  // 实际执行发送逻辑的函数
  const sendMessage = async () => {
    // 如果已经停止运行，直接返回
    if (!isRunningRef.current) {
      return;
    }

    try {
      const msg = getCurrentRobotMessage();
      if (!msg) {
        // 即使没有消息，也需要继续下一次定时
        scheduleNextSend();
        return;
      }
      // qa 消息不会走此处的逻辑，因为是一次性就返回了
      const message = {
        ...msg,
        body: undefined,
        isStreaming: msg.isStreaming ?? false,
        contentType: msg.contentType ?? EContentType.TextPlain,
        saveStatus: msg.saveStatus ?? 1
      };
      // 空消息不上报
      if(message.content === ''){
        return;
      }
    // 这里使用闭包保存的data值，注意如果data会变化需要特殊处理
      // 可以将data也存入ref中，确保每次获取最新值
      await saveMessageToServer({
        ...dataRef.current,
        messages: [message]
      });
      console.log('消息发送成功');
    } catch (error) {
      console.error('消息发送失败:', error);
    } finally {
      // 无论成功失败，都安排下一次发送
      scheduleNextSend();
    }
  };

  // 安排下一次发送
  const scheduleNextSend = () => {
    if (isRunningRef.current) {
      timerRef.current = setTimeout(sendMessage, intervalRef.current);
    }
  };

  // 开始定时发送消息
  const startTimedMessage = (data: TAppendMessages, interval: number = 5000) => {
    if (isRunningRef.current) {
      console.warn('定时任务已在运行中');
      return;
    }
    dataRef.current = data;
    // 更新配置
    intervalRef.current = interval;
    isRunningRef.current = true;
    setIsRunning(true);
    console.log('开始定时发送消息，间隔:', interval, 'ms');

    // 立即执行第一次发送
    sendMessage();
  };

  // 停止定时发送消息
  const stopTimedMessage = () => {
    if (timerRef.current) {
      clearTimeout(timerRef.current);
      timerRef.current = null;
    }
    isRunningRef.current = false;
    setIsRunning(false);
    console.log('定时发送消息已停止');
  };

  // 检查定时任务是否正在运行
  const isTimedMessageRunning = () => {
    return isRunning;
  };

  return {
    saveMessageToServer,
    startTimedMessage,
    stopTimedMessage,
    isTimedMessageRunning,
  };
};