"use client"

import { useCurrentUser } from "@/hooks/auth";
import { useChatConfig } from "../../context/chatConfig";
import CrushLevelAvatar from "../CrushLevelAvatar";
import { useDoRtcOperation, useGetRtcToken, useStartVoiceChat } from "@/hooks/useIm";
import { useCallback, useEffect, useRef, useState } from "react";
import { RTCClient } from "./rtc-types";
import RtcComponent from "./RtcComponent";
import { AutoPlayFailedEvent, LocalAudioPropertiesInfo, MediaType, onUserJoinedEvent, onUserLeaveEvent, PlayerEvent } from "@byteplus/rtc";
import { RtcOperation } from "@/services/im";
import ChatEndButton from "./ChatEndButton";
import ChatCallStatus from "./ChatCallStatus";
import { useAtom, useAtomValue, useSetAtom } from "jotai";
import { hasReceivedAiGreetingAtom, hasStartAICallAtom, isCallAtom, isCoinInsufficientAtom, selectedConversationIdAtom } from "@/atoms/im";
import { COIN_INSUFFICIENT_ERROR_CODE } from "@/hooks/useWallet";
import { useNimChat, useNimMsgContext } from "@/context/NimChat/useNimChat";
import { CustomMessageType } from "@/types/im";
import { useQueryClient } from "@tanstack/react-query";
import { walletKeys } from "@/lib/query-keys";
import { useAudioActivityDetection } from "@/hooks/useAudioActivityDetection";

// 字幕数据结构定义
interface SubtitleData {
  text: string;
  language: string;
  userId: string;
  sequence: number;
  definite: boolean;
  paragraph: boolean;
  roundId?: number;
}

interface SubtitleMessage {
  type: string;
  data: SubtitleData[];
}

export interface SubtitleState {
  userSubtitle: string;  // 用户字幕
  aiSubtitle?: string;    // AI 字幕（显示用）
  aiCompleteMessage: string; // AI完整消息拼接
  currentAiSentence: string; // 当前AI句子缓冲
  isUserSpeaking: boolean;
  isAiSpeaking: boolean;
  isAiThinking: boolean;
  hideInterrupt: boolean;
}

const durationText = ((duration: number) => {
  const hours = Math.floor(duration / 3600000);
  const minutes = Math.floor((duration % 3600000) / 60000);
  const seconds = Math.floor((duration % 60000) / 1000);
  
  if (hours > 0) {
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
  } else if (minutes > 0) {
    return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
  } else {
    return `00:${seconds.toString().padStart(2, '0')}`;
  }
});

const ChatCallContainer = () => {
  const [isConnected, setIsConnected] = useState(false);
  const [remoteStreams, setRemoteStreams] = useState<{
    [key: string]: {
      playerComp: React.ReactNode;
    };
  }>({});
  const [autoPlayFailUser, setAutoPlayFailUser] = useState<string[]>([]);
  const [isUserMicSpeaking, setisUserMicSpeaking] = useState<boolean>(false);
  const autoPlayFailUserdRef = useRef<string[]>([]);
  const rtc = useRef<RTCClient>(null);
  const rtcComponentRef = useRef<any>(null); // 添加这个ref来存储RtcComponent的引用
  const playStatus = useRef<{ [key: string]: { audio: boolean; video: boolean } }>({});
  const isJoiningRef = useRef<boolean>(false);
  const callStartTimeRef = useRef<number | null>(null); // 通话开始时间
  const rtcTimingRef = useRef<{
    rtcJoinStart?: number;
    rtcJoinEnd?: number;
    localStreamStart?: number;
    localStreamEnd?: number;
    startApiCall?: number;
    startApiSuccess?: number;
    aiGreetingReceived?: number;
  }>({}); // RTC各阶段时间记录
  const setHasReceivedAiGreeting = useSetAtom(hasReceivedAiGreetingAtom);
  const lastCallbackMessageRef = useRef<string>('');
  const { nim } = useNimChat();
  const { sendMessageActive } = useNimMsgContext();
  const selectedConversationId = useAtomValue(selectedConversationIdAtom);
  const queryClient = useQueryClient();
  
  // 字幕状态管理 - 使用 ref 来同步保存状态，避免异步setState问题
  const subtitleStateRef = useRef<SubtitleState>({
    userSubtitle: '',
    aiSubtitle: '',
    aiCompleteMessage: '',
    currentAiSentence: '',
    isUserSpeaking: false,
    isAiSpeaking: false,
    isAiThinking: false,
    hideInterrupt: false,
  });

  // 用于触发页面更新的状态
  const [subtitleState, setSubtitleState] = useState<SubtitleState>(subtitleStateRef.current);
  
  // 音频播放相关
  const connectingAudioRef = useRef<HTMLAudioElement | null>(null);
  
  // 用于跟踪最新的sequence，确保按序处理
  const lastSequenceRef = useRef<{ [userId: string]: number }>({});
  // AI说话结束的防抖定时器
  const aiSpeechEndTimerRef = useRef<NodeJS.Timeout | null>(null);
  // 用户麦克风说话状态延迟定时器
  const userMicSpeakingTimerRef = useRef<NodeJS.Timeout | null>(null);
  
  // 本地音频活动检测
  const audioActivityDetection = useAudioActivityDetection({
    threshold: 35, // 音频阈值，可以根据需要调整
    sampleRate: 50, // 50ms 采样率，更快的响应
  });
  const setHasStartAICall = useSetAtom(hasStartAICallAtom);
  // 用于存储当前的音频流，以便传递给音频检测
  const currentAudioStreamRef = useRef<MediaStream | null>(null);
  const { aiId } = useChatConfig();
  const { data: user } = useCurrentUser();
  const userId = user?.userId;
  const roomId = `${user?.userId}-${aiId}`;
  const [isCall, setIsCall] = useAtom(isCallAtom);
  const setIsCoinInsufficient = useSetAtom(isCoinInsufficientAtom);

  
  // 使用 ref 来存储当前通话的 taskId，确保每次开始新通话时生成新的 ID
  const taskIdRef = useRef<string | null>(null);
  
  // 用于管理请求取消的 AbortController
  const abortControllerRef = useRef<AbortController | null>(null);
  
  // 生成新的 taskId 的函数
  const generateNewTaskId = useCallback(() => {
    const newTaskId = `${roomId}-${new Date().getTime()}`;
    taskIdRef.current = newTaskId;
    return newTaskId;
  }, [roomId]);

  const { data } = useGetRtcToken({ roomId });
  const { mutateAsync: doRtcOperation } = useDoRtcOperation();
  const { mutate: startVoiceChat } = useStartVoiceChat();
  const hasReceivedAiGreeting = useAtomValue(hasReceivedAiGreetingAtom);

  // AI说话结束的防抖处理函数
  const handleAiSpeechEndDebounced = useCallback(() => {
    // 清除之前的定时器
    if (aiSpeechEndTimerRef.current) {
      clearTimeout(aiSpeechEndTimerRef.current);
    }
    
    // 设置新的防抖定时器
    aiSpeechEndTimerRef.current = setTimeout(() => {
      console.log('AI说话结束防抖触发，启用用户麦克风');
      
      // 更新状态
      const currentState = subtitleStateRef.current;
      const newState = {
        ...currentState,
        hideInterrupt: true,
      };
      
      // 启用用户麦克风
      rtc.current?.changeAudioState(true);
      
      // 更新状态
      updateSubtitleState(newState);
    }, 300); // 200毫秒防抖延迟
  }, []);

  // 清理防抖定时器的函数
  const clearAiSpeechEndTimer = useCallback(() => {
    if (aiSpeechEndTimerRef.current) {
      clearTimeout(aiSpeechEndTimerRef.current);
      aiSpeechEndTimerRef.current = null;
    }
  }, []);

  // 打断功能
  const handleInterrupt = useCallback(async () => {
    if (!taskIdRef.current) return;
    
    // 清除AI说话结束的防抖定时器
    clearAiSpeechEndTimer();
    
    // 用户打断时重新启用麦克风
    console.log('用户打断AI，重新启用麦克风');
    rtc.current?.changeAudioState(true);
    
    await doRtcOperation({
      data: {
        roomId,
        optType: RtcOperation.INTERRUPT,
        aiId,
        taskId: taskIdRef.current,
      }
    });
    setSubtitleState({
      userSubtitle: '',
      // aiSubtitle: '',
      aiCompleteMessage: '',
      currentAiSentence: '',
      isUserSpeaking: false,
      isAiSpeaking: false,
      isAiThinking: false,
      hideInterrupt: true,
    });
  }, [doRtcOperation, roomId, aiId]);
  
  const rtcToken = data?.token;
  
  const handleUserPublishStream = useCallback(
    (stream: { userId: string; mediaType: MediaType }) => {
      const userId = stream.userId;
      if (stream.mediaType & MediaType.VIDEO) {
        if (remoteStreams[userId]) {
          rtc.current?.setRemoteVideoPlayer(userId, `remoteStream_${userId}`);
        }
      }
    },
    [remoteStreams]
  );

  const handleUserUnpublishStream = (event: { userId: string; mediaType: MediaType }) => {
    const { userId, mediaType } = event;
    if (mediaType & MediaType.VIDEO) {
      rtc.current?.setRemoteVideoPlayer(userId, undefined);
    }
  };

  const handleUserJoin = (e: onUserJoinedEvent) => {
    console.log('handleUserJoin', e);
  };

  const handleUserLeave = (e: onUserLeaveEvent) => {
    const { userInfo } = e;
    const remoteUserId = userInfo.userId;
    if (remoteStreams[remoteUserId]) {
      delete remoteStreams[remoteUserId];
    }
    setRemoteStreams({
      ...remoteStreams,
    });
  };

  const addFailUser = (userId: string) => {
    const index = autoPlayFailUser.findIndex((item) => item === userId);
    if (index === -1) {
      autoPlayFailUser.push(userId);
    }
    setAutoPlayFailUser([...autoPlayFailUser]);
  };


  const handleAutoPlayFail = (event: AutoPlayFailedEvent) => {
    console.log('handleAutoPlayFail', event.userId, event);
    const { userId, kind } = event;

    let playUser = playStatus.current?.[userId] || {};
    playUser = { ...playUser, [kind]: false };
    playStatus.current[userId] = playUser;

    addFailUser(userId);
  };

  const handleEventError = (e: any, VERTC: any) => {
    if (e.errorCode === VERTC.ErrorCode.DUPLICATE_LOGIN) {
      // message.error('你的账号被其他人顶下线了');
      leaveRoom();
      setIsCall(false);
    }
  };


  const playerFail = (params: { type: 'audio' | 'video'; userId: string }) => {
    const { type, userId } = params;
    let playUser = playStatus.current?.[userId] || {};
    playUser = { ...playUser, [type]: false };
    const { audio, video } = playUser;
    if (audio === false || video === false) {
      addFailUser(userId);
    }
  };

  const handlePlayerEvent = (event: PlayerEvent) => {
    const { userId, rawEvent, type } = event;
    let playUser = playStatus.current?.[userId] || {};
    if (!playStatus.current) return;
    if (rawEvent.type === 'playing') {
      playUser = { ...playUser, [type]: true };
      const { audio, video } = playUser;
      if (audio !== false && video !== false) {
        const _autoPlayFailUser = autoPlayFailUserdRef.current.filter((item) => item !== userId);
        setAutoPlayFailUser([..._autoPlayFailUser]);
      }
    } else if (rawEvent.type === 'pause') {
      playerFail({ userId, type });
    }

    playStatus.current[userId] = playUser;
  };

  // 解包二进制数据并验证
  const unpackSubtitleMessage = (message: ArrayBuffer): string | null => {
    const kSubtitleHeaderSize = 8;
    if (message.byteLength < kSubtitleHeaderSize) {
      console.warn('Message size too small');
      return null;
    }

    const uint8Array = new Uint8Array(message);
    
    // 验证魔数 "subv" (0x73756276)
    const magicNumber = 
      (uint8Array[0] << 24) |
      (uint8Array[1] << 16) |
      (uint8Array[2] << 8) |
      uint8Array[3];
    
    if (magicNumber !== 0x73756276) {
      console.warn('Invalid magic number, not a subtitle message');
      return null;
    }

    // 获取内容长度
    const length = 
      (uint8Array[4] << 24) |
      (uint8Array[5] << 16) |
      (uint8Array[6] << 8) |
      uint8Array[7];

    if (message.byteLength - kSubtitleHeaderSize !== length) {
      console.warn('Message length mismatch');
      return null;
    }

    if (length === 0) {
      return '';
    }

    // 提取字幕内容
    const subtitleBytes = uint8Array.slice(kSubtitleHeaderSize);
    return new TextDecoder('utf-8').decode(subtitleBytes);
  };

  // 解析字幕数据
  const parseSubtitleData = (jsonString: string): SubtitleMessage | null => {
    try {
      const parsed = JSON.parse(jsonString) as SubtitleMessage;
      
      if (parsed.type !== 'subtitle' || !Array.isArray(parsed.data)) {
        console.warn('Invalid subtitle message format');
        return null;
      }

      return parsed;
    } catch (error) {
      console.error('Failed to parse subtitle JSON:', error);
      return null;
    }
  };

  // 更新状态的辅助函数
  const updateSubtitleState = (newState: SubtitleState) => {
    if (newState.isAiThinking) {
      setTimeout(() => {
        setSubtitleState({ ...newState });
        // rtc.current?.changeAudioState(false);
      }, 200);
      return;
    }
    subtitleStateRef.current = newState;
    setSubtitleState({ ...newState });
  };
  
  // 结合本地音频检测和服务器回调的用户说话状态
  // const combinedUserSpeaking = subtitleState.isUserSpeaking || audioActivityDetection.isSpeaking;
  const combinedUserSpeaking = isUserMicSpeaking;

  // 处理字幕消息
  const handleSubtitleMessage = (subtitleMessage: SubtitleMessage) => {
    subtitleMessage.data.forEach((subtitle) => {
      console.log('Subtitle:', {
        text: subtitle.text,
        language: subtitle.language,
        userId: subtitle.userId,
        sequence: subtitle.sequence,
        isComplete: subtitle.definite,
        isParagraphEnd: subtitle.paragraph,
        roundId: subtitle.roundId
      });

      const isCurrentUser = subtitle.userId === String(`${userId}`);
      const userKey = isCurrentUser ? 'user' : 'ai';
      
      // 检查sequence序列，确保按序处理
      const lastSequence = lastSequenceRef.current[userKey] || 0;
      if (subtitle.sequence <= lastSequence) {
        console.log('跳过过期的字幕消息:', subtitle.sequence, '当前最新:', lastSequence);
        return;
      }
      
      // 更新sequence
      lastSequenceRef.current[userKey] = subtitle.sequence;
      
      // 获取当前状态（从ref中获取最新状态）
      const currentState = subtitleStateRef.current;
      const newState = { ...currentState };

      if (isCurrentUser) {
        // 处理用户字幕
        if (subtitle.paragraph === false && subtitle.definite === false) {
          // 用户实时说话
          console.log('用户实时字幕:', subtitle.text);
          newState.userSubtitle = subtitle.text;
          newState.isUserSpeaking = true;
          // 用户开始说话时清空AI字幕和完整消息，准备接收新的AI回复
          // newState.aiSubtitle = '';
          newState.aiCompleteMessage = '';
          newState.currentAiSentence = '';
          newState.isAiSpeaking = false; // 现在明确设置为false，切换到listening状态
          newState.isAiThinking = false;
        } else if (subtitle.paragraph === true) {
          // 用户说话结束
          console.log('用户说话结束:', subtitle.text);
          newState.isUserSpeaking = false;
          newState.isAiThinking = true;
        }
      } else {
        // 处理AI字幕
        if (subtitle.paragraph === false && subtitle.definite === false) {
          // AI实时字幕 - 显示当前句子的实时内容
          console.log('AI实时字幕:', subtitle.text);
          
          // AI开始说话时清除防抖定时器
          clearAiSpeechEndTimer();
          
          newState.currentAiSentence = subtitle.text;
          newState.aiSubtitle = newState.aiCompleteMessage + subtitle.text;
          
          // AI开始说话时禁用用户麦克风
          // if (!currentState.isAiSpeaking) {
          //   console.log('AI1开始说话，禁用用户麦克风');
          //   rtc.current?.changeAudioState(false);
          // }
          rtc.current?.changeAudioState(false);
          newState.isAiSpeaking = true;
          newState.isAiThinking = false;
          newState.userSubtitle = '';
          newState.isUserSpeaking = false;
          newState.hideInterrupt = false;
        } else if (subtitle.paragraph === false && subtitle.definite === true) {
          // AI确定字幕 - 将确定的句子添加到完整消息中
          console.log('AI确定字幕:', subtitle.text);
          // 防重复处理
          if (lastCallbackMessageRef.current === subtitle.text) {
            return;
          }
          lastCallbackMessageRef.current = subtitle.text;
          
          // 将确定的文本添加到完整消息中
          newState.aiCompleteMessage = newState.aiCompleteMessage + subtitle.text;
          newState.currentAiSentence = ''; // 清空当前句子缓冲
          newState.aiSubtitle = newState.aiCompleteMessage; // 更新显示
          newState.isAiSpeaking = true;
          newState.isAiThinking = false;
          newState.hideInterrupt = false;
        } else if (subtitle.paragraph === true) {
          // AI段落结束 - 完整回复结束
          console.log('AI回复完成:', subtitle.text);
          // 如果还有剩余文本，添加到完整消息中
          if (subtitle.text && !newState.aiCompleteMessage.includes(subtitle.text)) {
            newState.aiCompleteMessage = newState.aiCompleteMessage + subtitle.text;
            newState.aiSubtitle = newState.aiCompleteMessage;
          }
          newState.currentAiSentence = '';
          
          // 不立即设置 hideInterrupt 和 changeAudioState，而是使用防抖处理
          // newState.hideInterrupt = true;
          // rtc.current?.changeAudioState(true);
          
          // AI说完话后，保持显示状态，不立即切换到listening
          // newState.isAiSpeaking = false; // 注释掉这行，让AI字幕继续显示
          newState.isAiThinking = false;
          
          // 输出完整的AI回复用于调试
          console.log('AI完整回复:', newState.aiCompleteMessage);
          
          // 使用防抖处理AI说话结束
          handleAiSpeechEndDebounced();
        }
      }

      // 更新状态并触发页面刷新
      updateSubtitleState(newState);

      // 判断字幕来源
      if (isCurrentUser) {
        console.log('Human user subtitle:', subtitle.text);
      } else {
        console.log('AI agent subtitle:', subtitle.text);
      }
    });
  };

  const handleRoomBinaryMessageReceived = (event: { userId: string; message: ArrayBuffer }) => {
    console.log('handleRoomBinaryMessageReceived', event);
    const { message } = event;
    
    // 记录收到AI开场白时间
    if (!rtcTimingRef.current.aiGreetingReceived) {
      rtcTimingRef.current.aiGreetingReceived = Date.now();
      const totalDuration = rtcTimingRef.current.aiGreetingReceived - rtcTimingRef.current.rtcJoinStart!;
      const startToGreetingDuration = rtcTimingRef.current.aiGreetingReceived - rtcTimingRef.current.startApiSuccess!;
      console.log('🎉 收到AI开场白:', new Date().toLocaleString());
      console.log('📊 RTC完整流程耗时统计:');
      console.log(`  - RTC加入房间: ${rtcTimingRef.current.rtcJoinEnd! - rtcTimingRef.current.rtcJoinStart!}ms`);
      console.log(`  - 创建本地流: ${rtcTimingRef.current.localStreamEnd! - rtcTimingRef.current.localStreamStart!}ms`);
      console.log(`  - START接口调用: ${rtcTimingRef.current.startApiSuccess! - rtcTimingRef.current.startApiCall!}ms`);
      console.log(`  - START接口到AI开场白: ${startToGreetingDuration}ms`);
      console.log(`  - 总耗时: ${totalDuration}ms`);
    }
    
    setHasReceivedAiGreeting(true);
    if (connectingAudioRef.current) {
      connectingAudioRef.current.pause();
      connectingAudioRef.current.currentTime = 0;
      connectingAudioRef.current = null;
    }
    
    // 尝试解包字幕消息
    const subtitleJson = unpackSubtitleMessage(message);
    
    if (subtitleJson !== null) {
      // 是字幕消息，进行解析
      const subtitleMessage = parseSubtitleData(subtitleJson);
      
      if (subtitleMessage) {
        handleSubtitleMessage(subtitleMessage);
        return;
      }
    }
  }

  const handleLocalAudioPropertiesReport = (event: LocalAudioPropertiesInfo[]) => {
    console.log('handleLocalAudioPropertiesReport', event);
    // 如果用户麦克风正在说话，则设置isUserMicSpeaking为true
    if (event.some((item) => item.audioPropertiesInfo.linearVolume > 25)) {
      setisUserMicSpeaking(true);
    } else {
      setisUserMicSpeaking(false);
    }
  }

  const leaveRoom = useCallback(
    async () => {
      if (!rtc.current) return;
      // off the event
      rtc.current.removeEventListener();

      try {
        await rtc.current.leave();  
      } catch (error) {
        console.log('leaveRoom error', error);
      }

      setAutoPlayFailUser([]);
      setSubtitleState({
        userSubtitle: '',
        aiSubtitle: '',
        aiCompleteMessage: '',
        currentAiSentence: '',
        isUserSpeaking: false,
        isAiSpeaking: false,
        isAiThinking: false,
        hideInterrupt: false,
      });
      // 重置通话开始时间和AI开场白状态
      callStartTimeRef.current = null;
      setHasReceivedAiGreeting(false);
      isJoiningRef.current = false;
      rtcComponentRef.current = null; // 清理RtcComponent引用
      taskIdRef.current = null; // 清理taskId，为下次通话做准备
      
      // 重置RTC时间记录
      rtcTimingRef.current = {};
      
      // 清理 AbortController
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
        abortControllerRef.current = null;
      }
      
      // 清理连接音频
      if (connectingAudioRef.current) {
        connectingAudioRef.current.pause();
        connectingAudioRef.current.currentTime = 0;
        connectingAudioRef.current = null;
      }
      
      // 停止本地音频活动检测
      audioActivityDetection.stopDetection();
      
      // 清理音频流引用
      if (currentAudioStreamRef.current) {
        currentAudioStreamRef.current.getTracks().forEach(track => track.stop());
        currentAudioStreamRef.current = null;
      }
      
      // 清理用户麦克风说话状态定时器
      if (userMicSpeakingTimerRef.current) {
        clearTimeout(userMicSpeakingTimerRef.current);
        userMicSpeakingTimerRef.current = null;
      }

      setIsConnected(false);
    },
    [setHasReceivedAiGreeting]
  );

  useEffect(() => {
    (async () => {
      if (!roomId || !userId || !rtc.current || !rtcToken || isJoiningRef.current) return;
      
      // 在每次开始新通话时生成新的 taskId
      const currentTaskId = generateNewTaskId();
      isJoiningRef.current = true;
      
      // 重置AI开场白状态
      setHasReceivedAiGreeting(false);
      
      // 记录RTC加入开始时间
      rtcTimingRef.current.rtcJoinStart = Date.now();
      console.log('🚀 RTC加入房间开始:', new Date().toLocaleString());
      
      try {
        await rtc.current.join((rtcToken as any) || null, roomId, `${userId}`);
        
        // 记录RTC加入成功时间
        rtcTimingRef.current.rtcJoinEnd = Date.now();
        const rtcJoinDuration = rtcTimingRef.current.rtcJoinEnd - rtcTimingRef.current.rtcJoinStart!;
        console.log('✅ RTC加入房间成功:', new Date().toLocaleString(), `耗时: ${rtcJoinDuration}ms`);
        
        // 记录通话开始时间
        callStartTimeRef.current = Date.now();
        
        rtc?.current?.createLocalStream(`${userId}`, async (res: any) => {
          // 记录创建本地流开始时间
          rtcTimingRef.current.localStreamStart = Date.now();
          console.log('🎤 创建本地流开始:', new Date().toLocaleString());
          
          // rtc.current?.changeAudioState(true);
          
          // 启动本地音频活动检测
          try {
            const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
            currentAudioStreamRef.current = stream;
            audioActivityDetection.startDetection(stream);
            console.log('本地音频活动检测已启动');
          } catch (error) {
            console.error('启动本地音频检测失败:', error);
          }
          
          try {
            // 记录创建本地流结束时间
            rtcTimingRef.current.localStreamEnd = Date.now();
            const localStreamDuration = rtcTimingRef.current.localStreamEnd - rtcTimingRef.current.localStreamStart!;
            console.log('✅ 创建本地流完成:', new Date().toLocaleString(), `耗时: ${localStreamDuration}ms`);
            
            // 创建新的 AbortController 用于这次请求
            const abortController = new AbortController();
            abortControllerRef.current = abortController;
            
            // 记录START接口调用开始时间
            rtcTimingRef.current.startApiCall = Date.now();
            console.log('📞 调用START接口开始:', new Date().toLocaleString());
            
            await doRtcOperation({
              data: {
                roomId,
                optType: RtcOperation.START,
                aiId,
                taskId: currentTaskId,
              },
              signal: abortController.signal
            });

            await rtc.current?.enableAudioPropertiesReport({
              interval: 300,
            });

            // 记录START接口调用成功时间
            rtcTimingRef.current.startApiSuccess = Date.now();
            const startApiDuration = rtcTimingRef.current.startApiSuccess - rtcTimingRef.current.startApiCall!;
            console.log('✅ START接口调用成功:', new Date().toLocaleString(), `耗时: ${startApiDuration}ms`);

            setHasStartAICall(true);
            // 请求成功完成，清理 AbortController
            abortControllerRef.current = null;
          } catch (error: any) {
            // 清理 AbortController
            abortControllerRef.current = null;
            
            // 如果是用户主动取消的请求，不需要处理错误
            if (error.name === 'AbortError' || error.name === 'CanceledError') {
              console.log('START 请求已被用户取消');
              return;
            }
            
            if (error.errorCode && error.errorCode === COIN_INSUFFICIENT_ERROR_CODE) {
              setIsCall(false);
              leaveRoom();
              setIsCoinInsufficient(true);
            }
          }
          
          // startVoiceChat({
          //   roomId,
          //   aiId,
          //   taskId: currentTaskId,
          //   userId,
          // });
          setIsConnected(true);
        });
      } catch (error: any) {
        console.log('join error', error);
        isJoiningRef.current = false;
        leaveRoom();
        setIsCall(false);
      }
    })();
  }, [roomId, userId, rtcToken, doRtcOperation, aiId, generateNewTaskId, leaveRoom, setIsCall, setHasReceivedAiGreeting, setHasStartAICall]);

  useEffect(() => {
    if (!isCall) return;
    const handleCallCoinInsufficient = () => {
      queryClient.invalidateQueries({ queryKey: walletKeys.getWalletBalance() })
      leaveRoom();
      setIsCall(false);
      setIsCoinInsufficient(true);
    }
    window.addEventListener('call-coin-insufficient', handleCallCoinInsufficient);
    return () => {
      window.removeEventListener('call-coin-insufficient', handleCallCoinInsufficient);
    }
  }, [isCall]);

  // 监听 isCall 变化，当用户关闭通话时取消正在进行的请求
  useEffect(() => {
    if (!isCall && abortControllerRef.current) {
      console.log('用户关闭通话，取消正在进行的 START 请求');
      abortControllerRef.current.abort();
      abortControllerRef.current = null;
    }
  }, [isCall]);

  // 控制连接音频播放
  useEffect(() => {
    if (!hasReceivedAiGreeting && isCall) {
      // 创建或获取音频元素
      if (!connectingAudioRef.current) {
        connectingAudioRef.current = new Audio('/voice/connecting.mp3');
        connectingAudioRef.current.loop = true;
      }
      
      // 播放音频
      connectingAudioRef.current.play().catch(error => {
        console.log('音频播放失败:', error);
      });
    } else {
      // 停止音频播放
      if (connectingAudioRef.current) {
        connectingAudioRef.current.pause();
        connectingAudioRef.current.currentTime = 0;
      }
    }

    return () => {
      if (connectingAudioRef.current) {
        connectingAudioRef.current.pause();
        connectingAudioRef.current.currentTime = 0;
        connectingAudioRef.current = null;
      }
    }
  }, [hasReceivedAiGreeting, isCall]);

  // 组件卸载时清理防抖定时器
  useEffect(() => {
    return () => {
      clearAiSpeechEndTimer();
      // 清理用户麦克风说话状态定时器
      if (userMicSpeakingTimerRef.current) {
        clearTimeout(userMicSpeakingTimerRef.current);
        userMicSpeakingTimerRef.current = null;
      }
    };
  }, [clearAiSpeechEndTimer]);

  return (
    <>
      <div className="fixed inset-0 backdrop-blur-2xl z-50">
        <div className="absolute inset-0 bg-background-default opacity-65" />
        <div className="opacity-30 absolute left-[50px] right-[50px] -bottom-[500px] h-[612px] rounded-full blur-[100px]" style={{ background: "linear-gradient(117deg, #FF9CB5 16.41%, #BC97EF 46.49%, #8BE6F0 77.76%)" }} />
        <div className="absolute inset-0 overflow-auto flex justify-center items-center py-[156px]">
          <div className="flex flex-col justify-between items-center min-h-[712px]">
            <div>
              <CrushLevelAvatar size="large" noLink showAnimation hideIcon />
            </div>

            <ChatCallStatus 
              isConnected={isConnected} 
              subtitleState={{
                ...subtitleState,
                isUserSpeaking: combinedUserSpeaking, // 使用结合后的状态
              }} 
              onInterrupt={handleInterrupt}
            />

            <ChatEndButton 
              roomId={roomId} 
              taskId={taskIdRef.current || ''} 
              onLeave={leaveRoom} 
              callStartTime={callStartTimeRef.current}
              abortController={abortControllerRef.current}
            />
          </div>
        </div>
      </div>
      {!rtcComponentRef.current && (
        <RtcComponent
          onRef={(ref) => {
            rtc.current = ref;
            rtcComponentRef.current = ref;
          }}
          config={{
            appId: process.env.NEXT_PUBLIC_RTC_APP_ID,
            roomId,
          }} 
          streamOptions={{
            audio: true,
            video: false,
          }}
          handleUserPublishStream={handleUserPublishStream}
          handleUserUnpublishStream={handleUserUnpublishStream}
          handleUserJoin={handleUserJoin}
          handleUserLeave={handleUserLeave}
          handleAutoPlayFail={handleAutoPlayFail}
          handleEventError={handleEventError}
          handlePlayerEvent={handlePlayerEvent}
          handleRoomBinaryMessageReceived={handleRoomBinaryMessageReceived}
          handleLocalAudioPropertiesReport={handleLocalAudioPropertiesReport}
        />
      )}
    </>
  );
}
 
export default ChatCallContainer;