import { computed, ref, watch } from 'vue';

import { defineStore } from 'pinia';

import { playOnceAndDestroySys } from '#/util/tool';
import {
  getChatFriendsListApi,
  getChatMessageListApi,
} from '#/views/business/chat/api';

import { useWebRTC } from '../composables/useWebRTC';
import { useUserStore } from '../stores/user';
// import { chatDB } from '../utils/db';
import { callAPI, sendCallSignal } from '../utils/request.ts';

export const useChatStore = defineStore('chat', () => {
  const friends = ref([]);
  const currentFriend = ref(null);
  const messages = ref([]);
  const connectionStatus = ref('disconnected');
  const socket = ref(null);

  // 通话相关状态增强
  const currentCall = ref(null);
  const incomingCall = ref(null);
  const callStatus = ref('idle'); // idle, calling, ringing, connecting, ongoing, ended, disconnected, hangup
  const callError = ref(null);
  const callConnectionStatus = ref('');
  const callTimeout = ref(null);
  const hasMore = ref(true);

  // 新挂号通知 - 当收到 message_type=10 时更新，用于触发患者列表刷新
  const newRegisterNotification = ref<{ timestamp: number; data: any } | null>(null);

  const webrtc = useWebRTC();
  const userStore = useUserStore();

  const lastMessageId = ref(0);

  // 计算属性
  const isConnected = computed(() => connectionStatus.value === 'connected');
  const isInCall = computed(() =>
    ['calling', 'connecting', 'ongoing', 'ringing'].includes(callStatus.value),
  );
  const isCalling = computed(() => callStatus.value === 'calling');
  const isRinging = computed(() => callStatus.value === 'ringing');
  const isConnecting = computed(() => callStatus.value === 'connecting');
  const isOngoingCall = computed(() => callStatus.value === 'ongoing');
  const isDisconnected = computed(() => callStatus.value === 'disconnected');
  const isHangup = computed(() => callStatus.value === 'hangup');

  // 获取历史消息
  const generateOldMessages = () => {
    getChatMessageListApi({
      room_id: currentFriend.value.room_id,
      last_message_id: lastMessageId.value,
    }).then((res) => {
      lastMessageId.value = res.last_message_id;

      if (res.count === 0) {
        hasMore.value = false;
        return;
      }
      // 使用当前用户的ID（doctor_id）来判断消息是否是自己发送的
      const currentUserDoctorId = userStore.currentUser?.doctor_id;
      const newMessages = checkMyMessage(res.list, currentUserDoctorId);
      messages.value.unshift(...newMessages);
      console.log('load message ok', hasMore.value);
    });
  };
  // 时间戳日志函数
  const logWithTime = (level, message, ...args) => {
    const timestamp = new Date().toLocaleTimeString('zh-CN', {
      hour12: false,
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      fractionalSecondDigits: 3,
    });

    switch (level) {
      case 'error': {
        console.error(`[${timestamp}] ${message}`, ...args);
        break;
      }
      case 'log': {
        console.log(`[${timestamp}] ${message}`, ...args);
        break;
      }
      case 'warn': {
        console.warn(`[${timestamp}] ${message}`, ...args);
        break;
      }
      default: {
        console.log(`[${timestamp}] ${message}`, ...args);
      }
    }
  };

  // 监听通话状态变化
  watch(
    () => callStatus.value,
    (newStatus) => {
      logWithTime('log', '通话状态变化:', newStatus);
    },
  );

  // 重置所有通话状态
  const resetCallState = () => {
    clearCallTimeout();
    callStatus.value = 'idle';
    callError.value = null;
    callConnectionStatus.value = '';
    currentCall.value = null;
    incomingCall.value = null;
  };

  // 清除通话超时
  const clearCallTimeout = () => {
    if (callTimeout.value) {
      clearTimeout(callTimeout.value);
      callTimeout.value = null;
    }
  };

  // 设置通话超时
  const setCallTimeout = (callback, duration = 30_000) => {
    clearCallTimeout();
    callTimeout.value = setTimeout(() => {
      callback();
      clearCallTimeout();
    }, duration);
  };

  // 发送通话信令
  const sendCallSignalInternal = async (signal) => {
    try {
      logWithTime('log', '发送通话信令:', signal);

      if (!userStore.currentUser?.doctor_id) {
        throw new Error('用户未登录');
      }

      if (!signal.receiver_user_id) {
        throw new Error('缺少接收方用户ID');
      }

      if (!signal.call_id) {
        throw new Error('缺少通话ID');
      }

      if (!signal.call_status) {
        throw new Error('缺少通话状态');
      }

      // 确保 sender_user_id 有 doctor- 前缀
      const senderId = userStore.currentUser.doctor_id.toString();
      const normalizedSenderId = senderId.startsWith('doctor-') ? senderId : `doctor-${senderId}`;

      const requestData = {
        sender_user_id: normalizedSenderId,
        receiver_user_id: signal.receiver_user_id,
        message_type:
          signal.call_type || (signal.call_status === 'invite' ? 6 : 7),
        message_content: JSON.stringify(signal.data || {}),
        call_id: signal.call_id,
        call_status: signal.call_status,
      };

      logWithTime('log', '发送通话信令请求数据:', requestData);

      const response = await sendCallSignal(requestData);
      logWithTime('log', '发送通话信令成功:', signal);
      return response;
    } catch (error) {
      logWithTime('error', '发送通话信令失败:', error);
      throw error;
    }
  };

  // 初始化数据库
  const initDB = async () => {
    try {
      // await chatDB.init();
      logWithTime('log', '数据库初始化成功');
    } catch (error) {
      logWithTime('error', '数据库初始化失败:', error);
    }
  };

  // 加载好友列表
  const loadFriends = async (presetUsers, currentUserId) => {
    try {
      getChatFriendsListApi().then((res) => {
        friends.value = res;
      });
    } catch (error) {
      logWithTime('error', '加载好友列表失败:', error);
      const friendList = presetUsers.filter(
        (user) => user.id !== currentUserId,
      );
      friendList.forEach((friend) => {
        friend.last_message = '';
        friend.un_read_count = 0;
      });
      friends.value = friendList;
    }
  };

  // 设置当前好友
  const setCurrentFriend = (friend) => {
    currentFriend.value = friend;
    if (friend) {
      friend.un_read_count = 0;
    }
  };

  // 切换当前聊天好友
  const switchFriend = async (friend, currentUserId) => {
    friend.un_read_count = 0;
    // 循环好友列表，找到该好友，然后吧 un_read_count 设置为0
    friends.value.forEach((friend) => {
      if (friend.id === currentFriend.value.id) {
        friend.un_read_count = 0;
      }
    });
    currentFriend.value = friend;

    hasMore.value = true;
    // getChatMessageListApi
    getChatMessageListApi({
      room_id: friend.room_id,
    }).then((res) => {
      lastMessageId.value = res.last_message_id;
      // 使用当前用户的ID（doctor_id）来判断消息是否是自己发送的
      const currentUserDoctorId = userStore.currentUser?.doctor_id;
      messages.value = checkMyMessage(res.list, currentUserDoctorId);
    });
  };
  /**
   * 转化消息格式 - 直接返回数据库字段，不进行转换
   * @param messages
   * @param currentUserId
   */
  const checkMyMessage = (messages, currentUserId) => {
    return messages.map((message) => {
      // isSent 表示消息是否是自己发送的
      // 需要处理不同的 sender_user_id 格式：
      // - 如果 sender_user_id 等于 currentUserId，说明是自己发送的
      // - 如果 sender_user_id 是 "doctor-{currentUserId}" 格式，说明是自己发送的
      // - 如果 sender_user_id 是 "user-{currentUserId}" 格式，说明是自己发送的
      // 使用 == 而不是 === 进行类型宽松比较，避免类型转换
      const senderId = message.sender_user_id;
      // 只在需要调用 startsWith 时才检查类型
      const currentUserIdStr = typeof currentUserId === 'string' ? currentUserId : (currentUserId != null ? String(currentUserId) : '');
      const isSent = 
        senderId == currentUserId ||
        senderId == `doctor-${currentUserId}` ||
        senderId == `user-${currentUserId}` ||
        (typeof currentUserIdStr === 'string' && currentUserIdStr.startsWith('doctor-') && senderId == currentUserIdStr.replace('doctor-', '')) ||
        (typeof currentUserIdStr === 'string' && currentUserIdStr.startsWith('user-') && senderId == currentUserIdStr.replace('user-', ''));
      
      return {
        id: message.id,
        sender_user_id: message.sender_user_id,
        senderId: message.sender_user_id, // 添加senderId字段用于兼容
        receiver_user_id: message.receiver_user_id,
        message_type: message.message_type,
        message_content: message.message_content,
        duration: message.duration,
        room_id: message.room_id,
        created_at: message.created_at,
        created_at_text: message.created_at_text,
        timestamp: message.created_at,
        read: true,
        chatKey: message.id,
        isSent: isSent,
      };
    });
  };

  // 添加消息
  const addMessage = async (message, currentUserId) => {
    messages.value.push(message);

    const friend = friends.value.find(
      (f) => f.id === message.sender_user_id || f.id === currentFriend.value?.id,
    );
    if (friend) {
      let lastMessage = getParsedContent(message.message_type, message.message_content);
      if (typeof lastMessage === 'object') {
        lastMessage = JSON.stringify(lastMessage);
      }
      const messageTypeName = getMessageTypeName(message.message_type);
      if (messageTypeName === 'image') lastMessage = '[图片]';
      if (messageTypeName === 'video') lastMessage = '[视频]';
      if (messageTypeName === 'audio') lastMessage = '[语音]';
      if (messageTypeName === 'prescription') lastMessage = '[处方信息]';
      if (messageTypeName === 'register') lastMessage = '[挂号信息]';
      if (messageTypeName === 'video-call' || messageTypeName === 'audio-call')
        lastMessage = '[通话]';

      friend.last_message =
        lastMessage.length > 20
          ? `${lastMessage.slice(0, 20)}...`
          : lastMessage;

      // await chatDB.updateFriendLastMessage(
      //   friend.id,
      //   currentUserId,
      //   friend.last_message,
      //   0,
      // );
    }

    // if (currentFriend.value && friend && friend.id === currentFriend.value.id) {
    //   try {
    //     await chatDB.saveMessage(
    //       message,
    //       currentUserId,
    //       currentFriend.value.id,
    //     );
    //   } catch (error) {
    //     logWithTime('error', '保存消息失败:', error);
    //   }
    // }
  };

  // 辅助函数：移除ID前缀，统一格式比较
  const getIdWithoutPrefix = (id) => {
    if (!id) return '';
    return String(id).replace(/^(user-|doctor-)/, '');
  };

  // 处理接收到的消息
  const handleIncomingMessage = async (messageData, currentUserId) => {
    // if (messageData.isFromHttp) {
    //   logWithTime("log", "忽略来自HTTP的消息，避免循环")
    //   return
    // }

    const senderId = messageData.sender_user_id;
    const receiverId = messageData.receiver_user_id;

    // 首先检查房间号匹配，确保只显示当前房间的消息
    const currentRoomId = currentFriend.value?.room_id;
    if (messageData.room_id && currentRoomId && messageData.room_id !== currentRoomId) {
      return; // 房间号不匹配，忽略消息
    }

    // 确保 receiver_user_id 匹配时使用正确的前缀
    // 如果当前用户是医生，接收者应该是患者（user-前缀）
    // 如果当前用户是患者，接收者应该是医生（doctor-前缀）
    // 使用 == 而不是 === 进行类型宽松比较，避免类型转换
    // 只在需要调用 startsWith 时才检查类型
    const currentUserIdStr = typeof currentUserId === 'string' ? currentUserId : (currentUserId != null ? String(currentUserId) : '');
    const expectedReceiverId = typeof currentUserIdStr === 'string' && currentUserIdStr.startsWith('doctor-') 
      ? `user-${currentUserIdStr.replace('doctor-', '')}` 
      : `doctor-${currentUserId}`;
    
    // 如果 receiverId 匹配预期值，或者是当前用户ID，或者是当前好友的ID，则显示消息
    // 使用 == 而不是 === 进行类型宽松比较
    const friendId = currentFriend.value?.id;
    if (receiverId != expectedReceiverId && receiverId != currentUserId && receiverId != friendId) {
      return;
    }

    if (messageData.call_id || messageData.call_status) {
      handleCallSignal(messageData);
      return;
    }

    // 判断消息是否是自己发送的（使用 checkMyMessage 的逻辑）
    // currentUserIdStr 已在第346行声明，直接使用
    const isSent = 
      senderId == currentUserId ||
      senderId == `doctor-${currentUserId}` ||
      senderId == `user-${currentUserId}` ||
      (typeof currentUserIdStr === 'string' && currentUserIdStr.startsWith('doctor-') && senderId == currentUserIdStr.replace('doctor-', '')) ||
      (typeof currentUserIdStr === 'string' && currentUserIdStr.startsWith('user-') && senderId == currentUserIdStr.replace('user-', ''));

    const newMessage = {
      id: messageData.id || Date.now(),
      sender_user_id: senderId,
      receiver_user_id: receiverId,
      message_type: messageData.message_type,
      message_content: messageData.message_content || messageData.content,
      duration: messageData.duration || 0,
      room_id: messageData.room_id,
      created_at: messageData.created_at || Date.now(),
      created_at_text: messageData.created_at_text || new Date().toLocaleTimeString().slice(0, 5),
      timestamp: messageData.created_at || Date.now(),
      read: false,
      isSent: isSent,
    };

    // 检测挂号消息(message_type=10)、患者就诊经历消息(message_type=11)或转诊消息(message_type=14)，触发患者列表刷新通知
    if (messageData.message_type === 10 || messageData.message_type === 11 || messageData.message_type === 14) {
      newRegisterNotification.value = {
        timestamp: Date.now(),
        data: messageData,
      };
      logWithTime('log', `收到新消息(type=${messageData.message_type})，触发患者列表刷新通知`);
    }

    try {
      // 不再需要手动解析，getParsedContent 会在组件中按需解析
      // await chatDB.saveMessage(newMessage, currentUserId, senderId);

      // 如果房间号匹配，说明是当前聊天窗口的消息，应该直接添加
      if (currentRoomId && messageData.room_id === currentRoomId) {
        // 使用统一的ID比较方式判断是否是当前好友发送的消息
        const senderIdWithoutPrefix = getIdWithoutPrefix(senderId);
        const currentFriendIdWithoutPrefix = getIdWithoutPrefix(currentFriend.value?.id);
        
        if (senderIdWithoutPrefix === currentFriendIdWithoutPrefix) {
          // 是当前好友发送的消息，标记为已读并添加到消息列表
        newMessage.read = true;
        messages.value.push(newMessage);
      } else {
          // 不是当前好友发送的，但房间号匹配，可能是系统消息或其他情况，也添加到消息列表
          messages.value.push(newMessage);
        }
      } else {
        // 房间号不匹配，只更新未读数
        const friend = friends.value.find((f) => {
          const friendIdWithoutPrefix = getIdWithoutPrefix(f.id);
          const senderIdWithoutPrefix = getIdWithoutPrefix(senderId);
          return friendIdWithoutPrefix === senderIdWithoutPrefix;
        });
        if (friend) {
          friend.un_read_count = (friend.un_read_count || 0) + 1;
        }
      }

      const friend = friends.value.find((f) => f.id == senderId);
      if (friend) {
        let lastMessage = getParsedContent(newMessage.message_type, newMessage.message_content);
        if (typeof lastMessage === 'object') {
          lastMessage = JSON.stringify(lastMessage);
        }
        const messageTypeName = getMessageTypeName(newMessage.message_type);
        if (messageTypeName === 'image') lastMessage = '[图片]';
        if (messageTypeName === 'video') lastMessage = '[视频]';
        if (messageTypeName === 'audio') lastMessage = '[语音]';
        if (messageTypeName === 'prescription') lastMessage = '[处方信息]';
        if (newMessage.type === 'register') lastMessage = '[挂号信息]';
        if (
          newMessage.type === 'video-call' ||
          newMessage.type === 'audio-call'
        )
          lastMessage = '[通话]';
        friend.last_message = lastMessage;
        // 使用js 播放这个音频一次 SysAudioMp3
        playOnceAndDestroySys();

        // await chatDB.updateFriendLastMessage(
        //   friend.id,
        //   currentUserId,
        //   lastMessage,
        //   friend.un_read_count,
        // );
      }
    } catch (error) {
      logWithTime('error', '处理接收消息失败:', error);
    }
  };

  // 辅助函数：根据消息类型编号获取类型名称（不转换字段名）
  const getMessageTypeName = (type) => {
    const types = [
      'text',
      'image',
      'audio',
      'video',
      'prescription',
      'medical-record',
      'video-call',
      'audio-call',
      'file',
      'system',
      'register',
      'patient-experience',
      'product-card',
      'end-consultation',
    ];
    return types[type] || 'unknown';
  };

  // 辅助函数：按需解析消息内容
  const getParsedContent = (messageType, messageContent) => {
    // 对于需要 JSON 解析的消息类型：4, 10, 11, 12, 13
    if ([4, 10, 11, 12, 13].includes(messageType)) {
      try {
        return JSON.parse(messageContent);
      } catch (e) {
        console.error('解析消息内容失败:', e);
        return messageContent;
      }
    }
    return messageContent;
  };

  // 处理通话信令
  const handleCallSignal = (data) => {
    logWithTime('log', '处理通话信令:', data);
    logWithTime('log', '通话状态:', data.call_status);

    switch (data.call_status) {
      case 'accepted': {
        handleCallAccepted(data);
        break;
      }
      case 'answer': {
        handleAnswer(data);
        break;
      }
      case 'busy': {
        handleCallBusy(data);
        break;
      }
      case 'candidate': {
        handleIceCandidate(data);
        break;
      }
      case 'connecting': {
        handleCallConnecting(data);
        break;
      }
      case 'disconnected': {
        handleCallDisconnected(data);
        break;
      }
      case 'ended': {
        handleCallEnded(data);
        break;
      }
      case 'failed': {
        handleCallFailed(data);
        break;
      }
      case 'hangup': {
        handleCallHangup(data);
        break;
      }
      case 'invite': {
        handleIncomingCall(data);
        break;
      }
      case 'no-answer': {
        handleCallNoAnswer(data);
        break;
      }
      case 'offer': {
        handleOffer(data);
        break;
      }
      case 'rejected': {
        handleCallRejected(data);
        break;
      }
      case 'terminated': {
        handleCallTerminated(data);
        break;
      }
    }
  };

  // 修复问题2: 改进Offer处理，允许重新协商
  const handleOffer = async (data) => {
    if (incomingCall.value && incomingCall.value.callId === data.call_id) {
      // 修复问题1&2: 不再严格检查ongoing状态，允许重新协商
      if (callStatus.value === 'ongoing' && webrtc.isConnected.value) {
        logWithTime('log', '通话已稳定连接，忽略重复的 Offer');
        return;
      }

      // 允许在connecting状态下重新处理offer（重新协商）
      if (callStatus.value === 'connecting' || callStatus.value === 'failed') {
        logWithTime('log', '连接中或失败状态，允许重新处理 Offer');
      }

      try {
        const offer = JSON.parse(data.content || data.message_content || '{}');

        logWithTime('log', '🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯');
        logWithTime('log', '📥 收到对方 OFFER 信令:');
        logWithTime('log', '📋 Offer 类型:', offer.type);
        logWithTime(
          'log',
          '📋 Offer SDP (前200字符):',
          offer.sdp ? `${offer.sdp.slice(0, 200)}...` : '无SDP',
        );
        logWithTime('log', '📋 通话ID:', data.call_id);
        logWithTime('log', '📋 发送方:', data.sender_user_id);
        logWithTime('log', '📋 当前通话状态:', callStatus.value);
        logWithTime(
          'log',
          '📋 WebRTC连接状态:',
          webrtc.peerConnection.value?.connectionState,
        );
        logWithTime('log', '🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯');

        // 修复问题3: 如果连接失败或不存在，重新创建
        if (
          !webrtc.peerConnection.value ||
          webrtc.peerConnection.value.connectionState === 'failed' ||
          webrtc.peerConnection.value.connectionState === 'closed'
        ) {
          logWithTime('log', '重新创建 WebRTC 连接以处理 Offer');
          webrtc.createPeerConnection(data.call_id, data.sender_user_id);
        }

        const answer = await webrtc.createAnswer(
          offer,
          data.call_id,
          data.sender_user_id,
        );

        logWithTime('log', '🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯');
        logWithTime('log', '📤 准备发送 ANSWER 信令:');
        logWithTime('log', '📋 Answer 类型:', answer.type);
        logWithTime(
          'log',
          '📋 Answer SDP (前200字符):',
          answer.sdp ? `${answer.sdp.slice(0, 200)}...` : '无SDP',
        );
        logWithTime('log', '📋 通话ID:', data.call_id);
        logWithTime('log', '📋 接收方:', data.sender_user_id);
        logWithTime('log', '🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯');

        await callAPI.sendAnswer(
          userStore.currentUser.id,
          data.sender_user_id,
          data.call_id,
          answer,
          data.message_type,
        );

        // 更新状态为连接中
        if (callStatus.value !== 'ongoing') {
          callStatus.value = 'connecting';
          callConnectionStatus.value = '正在建立连接...';
        }

        logWithTime('log', '✅ 发送Answer成功');
      } catch (error) {
        logWithTime('error', '❌ 处理Offer失败:', error);

        // 修复问题3: 处理失败时尝试重连而不是直接拒绝
        if (webrtc.connectionAttempts.value < 3) {
          logWithTime('log', '🔄 Offer处理失败，尝试重连');
          setTimeout(() => {
            webrtc.attemptReconnection(data.call_id, data.sender_user_id);
          }, 2000);
        } else {
          rejectCall('failed');
        }
      }
    }
  };

  // 修复问题2: 改进Answer处理，允许重新协商
  const handleAnswer = async (data) => {
    if (currentCall.value && currentCall.value.callId === data.call_id) {
      // 修复问题1&2: 不再严格检查ongoing状态，允许重新协商
      if (callStatus.value === 'ongoing' && webrtc.isConnected.value) {
        logWithTime('log', '通话已稳定连接，忽略重复的 Answer');
        return;
      }

      // 允许在connecting状态下重新处理answer（重新协商）
      if (callStatus.value === 'connecting' || callStatus.value === 'failed') {
        logWithTime('log', '连接中或失败状态，允许重新处理 Answer');
      }

      try {
        const answer = JSON.parse(data.content || data.message_content || '{}');

        logWithTime('log', '🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯');
        logWithTime('log', '📥 收到对方 ANSWER 信令:');
        logWithTime('log', '📋 Answer 类型:', answer.type);
        logWithTime(
          'log',
          '📋 Answer SDP (前200字符):',
          answer.sdp ? `${answer.sdp.slice(0, 200)}...` : '无SDP',
        );
        logWithTime('log', '📋 通话ID:', data.call_id);
        logWithTime('log', '📋 发送方:', data.sender_user_id);
        logWithTime('log', '📋 当前通话状态:', callStatus.value);
        logWithTime(
          'log',
          '📋 WebRTC连接状态:',
          webrtc.peerConnection.value?.connectionState,
        );
        logWithTime('log', '🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯');

        await webrtc.setRemoteAnswer(answer);

        callStatus.value = 'connecting';
        callConnectionStatus.value = '正在建立连接...';

        logWithTime('log', '✅ Answer处理成功，开始建立连接');
      } catch (error) {
        logWithTime('error', '❌ 处理Answer失败:', error);

        // 修复问题3: 处理失败时尝试重连而不是直接结束
        if (webrtc.connectionAttempts.value < 3) {
          logWithTime('log', '🔄 Answer处理失败，尝试重连');
          setTimeout(() => {
            webrtc.attemptReconnection(data.call_id, currentCall.value.peerId);
          }, 2000);
        } else {
          endCall('failed');
        }
      }
    }
  };

  // 处理连接中状态
  const handleCallConnecting = (data) => {
    callConnectionStatus.value = '正在连接...';
    if (currentCall.value?.callId === data.call_id) {
      callStatus.value = 'connecting';
    }
  };

  // 修复问题3: 改进通话失败处理，增加重连逻辑
  const handleCallFailed = (data) => {
    if (
      (currentCall.value && currentCall.value.callId === data.call_id) ||
      (incomingCall.value && incomingCall.value.callId === data.call_id)
    ) {
      callError.value = 'failed';
      callConnectionStatus.value = '连接失败';

      const peerId = currentCall.value?.peerId || incomingCall.value?.callerId;
      const friend = friends.value.find((f) => f.id === peerId);

      // 修复问题3: 失败时尝试重连
      if (webrtc.connectionAttempts.value < 3) {
        logWithTime('log', '🔄 通话失败，尝试重连');
        callConnectionStatus.value = `连接失败，正在重试 (${webrtc.connectionAttempts.value + 1}/3)`;

        setTimeout(() => {
          webrtc.attemptReconnection(data.call_id, peerId);
        }, 3000);
      } else {
        // 达到最大重试次数，记录失败消息
        if (friend) {
          const callMessage = {
            type:
              currentCall.value?.callType === 'video' ||
              incomingCall.value?.callType === 'video'
                ? 'video-call'
                : 'audio-call',
            content: '[连接失败]',
            time: new Date().toLocaleTimeString().slice(0, 5),
            senderId: peerId,
            read: true,
            timestamp: Date.now(),
            duration: 0,
          };
          // chatDB.saveMessage(callMessage, userStore.currentUser.id, friend.id);

          friend.last_message = '[连接失败]';
          // chatDB.updateFriendLastMessage(
          //   friend.id,
          //   userStore.currentUser.id,
          //   '[连接失败]',
          //   friend.un_read_count,
          // );
        }

        setTimeout(() => {
          resetCallState();
        }, 5000);
      }
    }
  };

  // 处理来电
  const handleIncomingCall = (data) => {
    if (isInCall.value) {
      logWithTime('log', '当前正在通话中，发送忙线状态');
      callAPI.sendBusy(
        userStore.currentUser.id,
        data.sender_user_id,
        data.call_id,
        data.message_type,
      );

      const friend = friends.value.find((f) => f.id === data.sender_user_id);
      if (friend) {
        friend.last_message = '[未接来电]';
        // chatDB.updateFriendLastMessage(
        //   friend.id,
        //   userStore.currentUser.id,
        //   '[未接来电]',
        //   friend.un_read_count,
        // );

        const callMessage = {
          type: data.message_type === 6 ? 'video-call' : 'audio-call',
          content: '[未接来电]',
          time: new Date().toLocaleTimeString().slice(0, 5),
          senderId: data.sender_user_id,
          read: true,
          timestamp: Date.now(),
          duration: 0,
        };
        // chatDB.saveMessage(callMessage, userStore.currentUser.id, friend.id);
      }

      return;
    }

    resetCallState();

    incomingCall.value = {
      callId: data.call_id,
      callerId: data.sender_user_id,
      callType: data.message_type === 6 ? 'video' : 'audio',
      content: data.content,
    };
    callStatus.value = 'ringing';
    callError.value = null;
    callConnectionStatus.value = '收到来电';

    logWithTime('log', '收到来电:', incomingCall.value);

    setCallTimeout(() => {
      if (callStatus.value === 'ringing' && incomingCall.value) {
        logWithTime('log', '来电超时，自动拒绝');
        rejectCall('no-answer');
      }
    }, 30_000);
  };

  // 修复问题2&3: 改进通话接受处理，增加重连机制
  const handleCallAccepted = async (data) => {
    if (currentCall.value && currentCall.value.callId === data.call_id) {
      // 修复问题2: 允许在连接失败后重新接受
      if (callStatus.value === 'ongoing' && webrtc.isConnected.value) {
        logWithTime('log', '通话已稳定连接，忽略重复的 accepted 信令');
        return;
      }

      callStatus.value = 'connecting';
      callError.value = null;
      callConnectionStatus.value = '对方已接听，正在连接...';
      logWithTime('log', '通话已被接受，开始交换信令');

      setTimeout(() => {
        if (callStatus.value === 'connecting') {
          callConnectionStatus.value = '对方已接听，正在建立连接...';
        }
      }, 1000);

      try {
        if (!webrtc.localStream.value) {
          logWithTime('log', '获取本地媒体用于创建Offer');
          await webrtc.getLocalMedia({
            audio: true,
            video: currentCall.value.callType === 'video',
          });
        }

        // 修复问题3: 如果连接失败，重新创建连接
        if (
          !webrtc.peerConnection.value ||
          webrtc.peerConnection.value.connectionState === 'failed' ||
          webrtc.peerConnection.value.connectionState === 'closed'
        ) {
          logWithTime('log', '重新创建 WebRTC 连接');
          webrtc.createPeerConnection(
            currentCall.value.callId,
            currentCall.value.peerId,
          );
        }

        const offer = await webrtc.createOffer(
          currentCall.value.callId,
          currentCall.value.peerId,
        );

        logWithTime('log', '🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯');
        logWithTime('log', '📤 准备发送 OFFER 信令:');
        logWithTime('log', '📋 Offer 类型:', offer.type);
        logWithTime(
          'log',
          '📋 Offer SDP (前200字符):',
          offer.sdp ? `${offer.sdp.slice(0, 200)}...` : '无SDP',
        );
        logWithTime('log', '📋 通话ID:', currentCall.value.callId);
        logWithTime('log', '📋 接收方:', currentCall.value.peerId);
        logWithTime('log', '📋 连接尝试次数:', webrtc.connectionAttempts.value);
        logWithTime('log', '🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯🎯');

        await callAPI.sendOffer(
          userStore.currentUser.id,
          currentCall.value.peerId,
          currentCall.value.callId,
          offer,
          currentCall.value.callType === 'video' ? 6 : 7,
        );

        logWithTime('log', '✅ 发送Offer成功');
      } catch (error) {
        logWithTime('error', '❌ 创建Offer失败:', error);

        // 修复问题3: 创建失败时尝试重连
        if (webrtc.connectionAttempts.value < 3) {
          logWithTime('log', '🔄 创建Offer失败，尝试重连');
          setTimeout(() => {
            webrtc.attemptReconnection(
              currentCall.value.callId,
              currentCall.value.peerId,
            );
            // 重连后重新尝试处理accepted信令
            setTimeout(() => {
              handleCallAccepted(data);
            }, 1000);
          }, 2000);
        } else {
          endCall('failed');
        }
      }
    }
  };

  // 处理通话拒绝
  const handleCallRejected = (data) => {
    if (currentCall.value && currentCall.value.callId === data.call_id) {
      resetCallState();
      callConnectionStatus.value = '对方已拒绝';
      logWithTime('log', '通话已被拒绝');

      const friend = friends.value.find(
        (f) => f.id === currentCall.value.peerId,
      );
      if (friend) {
        const callMessage = {
          type:
            currentCall.value.callType === 'video'
              ? 'video-call'
              : 'audio-call',
          content: '[对方已拒绝]',
          time: new Date().toLocaleTimeString().slice(0, 5),
          senderId: userStore.currentUser?.doctor_id,
          read: true,
          timestamp: Date.now(),
          duration: 0,
        };
        // chatDB.saveMessage(callMessage, userStore.currentUser.id, friend.id);

        friend.last_message = '[对方已拒绝]';
        // chatDB.updateFriendLastMessage(
        //   friend.id,
        //   userStore.currentUser.id,
        //   '[对方已拒绝]',
        //   friend.un_read_count,
        // );
      }

      setTimeout(() => {
        callConnectionStatus.value = '';
      }, 5000);
    }
  };

  // 处理通话结束
  const handleCallEnded = (data) => {
    if (
      (currentCall.value && currentCall.value.callId === data.call_id) ||
      (incomingCall.value && incomingCall.value.callId === data.call_id)
    ) {
      const peerId = currentCall.value?.peerId || incomingCall.value?.callerId;
      const friend = friends.value.find((f) => f.id === peerId);
      if (friend) {
        const duration =
          callStatus.value === 'ongoing'
            ? Math.floor(
                (Date.now() -
                  (currentCall.value?.startTime ||
                    incomingCall.value?.startTime)) /
                  1000,
              )
            : 0;

        const callMessage = {
          type:
            currentCall.value?.callType === 'video' ||
            incomingCall.value?.callType === 'video'
              ? 'video-call'
              : 'audio-call',
          content:
            callStatus.value === 'ongoing'
              ? `[${currentCall.value?.callType === 'video' ? '视频' : '语音'}通话] ${Math.floor(duration / 60)}分${duration % 60}秒`
              : '[通话结束]',
          time: new Date().toLocaleTimeString().slice(0, 5),
          senderId: peerId,
          read: true,
          timestamp: Date.now(),
          duration,
        };
        // chatDB.saveMessage(callMessage, userStore.currentUser.id, friend.id);

        friend.last_message = callMessage.content;
        // chatDB.updateFriendLastMessage(
        //   friend.id,
        //   userStore.currentUser.id,
        //   callMessage.content,
        //   friend.un_read_count,
        // );
      }

      resetCallState();
      callConnectionStatus.value = '通话已结束';
      logWithTime('log', '通话已结束');

      setTimeout(() => {
        callConnectionStatus.value = '';
      }, 5000);
    }
  };

  // 处理ICE候选
  const handleIceCandidate = (data) => {
    if (
      (currentCall.value && currentCall.value.callId === data.call_id) ||
      (incomingCall.value && incomingCall.value.callId === data.call_id)
    ) {
      try {
        const candidate = JSON.parse(
          data.content || data.message_content || '{}',
        );
        logWithTime('log', '收到ICE候选:', candidate);

        webrtc.addIceCandidate(candidate);
      } catch (error) {
        logWithTime('error', '处理ICE候选失败:', error);
      }
    }
  };

  // 处理无人接听
  const handleCallNoAnswer = (data) => {
    if (currentCall.value && currentCall.value.callId === data.call_id) {
      const friend = friends.value.find(
        (f) => f.id === currentCall.value.peerId,
      );
      if (friend) {
        const callMessage = {
          type:
            currentCall.value.callType === 'video'
              ? 'video-call'
              : 'audio-call',
          content: '[未接来电]',
          time: new Date().toLocaleTimeString().slice(0, 5),
          senderId: userStore.currentUser?.doctor_id,
          read: true,
          timestamp: Date.now(),
          duration: 0,
        };
        // chatDB.saveMessage(callMessage, userStore.currentUser.id, friend.id);

        friend.last_message = '[未接来电]';
        // chatDB.updateFriendLastMessage(
        //   friend.id,
        //   userStore.currentUser.id,
        //   '[未接来电]',
        //   friend.un_read_count,
        // );
      }

      resetCallState();
      callConnectionStatus.value = '对方无人接听';
      logWithTime('log', '对方无人接听');

      setTimeout(() => {
        callConnectionStatus.value = '';
      }, 5000);
    }
  };

  // 处理对方忙线
  const handleCallBusy = (data) => {
    if (currentCall.value && currentCall.value.callId === data.call_id) {
      const friend = friends.value.find(
        (f) => f.id === currentCall.value.peerId,
      );
      if (friend) {
        const callMessage = {
          type:
            currentCall.value.callType === 'video'
              ? 'video-call'
              : 'audio-call',
          content: '[对方忙线]',
          time: new Date().toLocaleTimeString().slice(0, 5),
          senderId: userStore.currentUser?.doctor_id,
          read: true,
          timestamp: Date.now(),
          duration: 0,
        };
        // chatDB.saveMessage(callMessage, userStore.currentUser.id, friend.id);

        friend.last_message = '[对方忙线]';
        // chatDB.updateFriendLastMessage(
        //   friend.id,
        //   userStore.currentUser.id,
        //   '[对方忙线]',
        //   friend.un_read_count,
        // );
      }

      resetCallState();
      callConnectionStatus.value = '对方忙线中';
      logWithTime('log', '对方忙线中');

      setTimeout(() => {
        callConnectionStatus.value = '';
      }, 5000);
    }
  };

  // 处理对方挂断
  const handleCallHangup = (data) => {
    const callId =
      data?.call_id || currentCall.value?.callId || incomingCall.value?.callId;
    const peerId =
      data?.sender_user_id ||
      currentCall.value?.peerId ||
      incomingCall.value?.callerId;

    if (callId && peerId) {
      const friend = friends.value.find((f) => f.id === peerId);
      if (friend) {
        const duration =
          callStatus.value === 'ongoing'
            ? Math.floor(
                (Date.now() -
                  (currentCall.value?.startTime ||
                    incomingCall.value?.startTime)) /
                  1000,
              )
            : 0;

        const callMessage = {
          type:
            currentCall.value?.callType ||
            incomingCall.value?.callType === 'video'
              ? 'video-call'
              : 'audio-call',
          content:
            duration > 0
              ? `[对方已挂断] ${Math.floor(duration / 60)}分${duration % 60}秒`
              : '[对方已挂断]',
          time: new Date().toLocaleTimeString().slice(0, 5),
          senderId: peerId,
          read: true,
          timestamp: Date.now(),
          duration,
        };
        // chatDB.saveMessage(callMessage, userStore.currentUser.id, friend.id);

        friend.last_message = callMessage.content;
        // chatDB.updateFriendLastMessage(
        //   friend.id,
        //   userStore.currentUser.id,
        //   friend.last_message,
        //   friend.un_read_count,
        // );
      }

      callStatus.value = 'hangup';
      callConnectionStatus.value = '对方已挂断';
      logWithTime('log', '对方已挂断通话');

      setTimeout(() => {
        resetCallState();
      }, 3000);
    }
  };

  // 处理对方掉线
  const handleCallDisconnected = (data) => {
    const callId =
      data?.call_id || currentCall.value?.callId || incomingCall.value?.callId;
    const peerId =
      data?.sender_user_id ||
      currentCall.value?.peerId ||
      incomingCall.value?.callerId;

    if (callId && peerId) {
      const friend = friends.value.find((f) => f.id === peerId);
      if (friend) {
        const duration =
          callStatus.value === 'ongoing'
            ? Math.floor(
                (Date.now() -
                  (currentCall.value?.startTime ||
                    incomingCall.value?.startTime)) /
                  1000,
              )
            : 0;

        const callMessage = {
          type:
            currentCall.value?.callType ||
            incomingCall.value?.callType === 'video'
              ? 'video-call'
              : 'audio-call',
          content:
            duration > 0
              ? `[网络中断] ${Math.floor(duration / 60)}分${duration % 60}秒`
              : '[网络中断]',
          time: new Date().toLocaleTimeString().slice(0, 5),
          senderId: peerId,
          read: true,
          timestamp: Date.now(),
          duration,
        };
        // chatDB.saveMessage(callMessage, userStore.currentUser.id, friend.id);

        friend.last_message = callMessage.content;
        // chatDB.updateFriendLastMessage(
        //   friend.id,
        //   userStore.currentUser.id,
        //   friend.last_message,
        //   friend.un_read_count,
        // );
      }

      callStatus.value = 'disconnected';
      callConnectionStatus.value = '网络连接已断开';
      logWithTime('log', '网络连接已断开');

      setTimeout(() => {
        resetCallState();
      }, 3000);
    }
  };

  // 处理对方终止呼叫
  const handleCallTerminated = (data) => {
    const callId = data.call_id;
    const peerId = data.sender_user_id;

    if (
      (currentCall.value && currentCall.value.callId === callId) ||
      (incomingCall.value && incomingCall.value.callId === callId)
    ) {
      const friend = friends.value.find((f) => f.id === peerId);
      if (friend) {
        const callMessage = {
          type:
            currentCall.value?.callType ||
            incomingCall.value?.callType === 'video'
              ? 'video-call'
              : 'audio-call',
          content: '[对方已终止呼叫]',
          time: new Date().toLocaleTimeString().slice(0, 5),
          senderId: peerId,
          read: true,
          timestamp: Date.now(),
          duration: 0,
        };
        // chatDB.saveMessage(callMessage, userStore.currentUser.id, friend.id);

        friend.last_message = '[对方已终止呼叫]';
        // chatDB.updateFriendLastMessage(
        //   friend.id,
        //   userStore.currentUser.id,
        //   '[对方已终止呼叫]',
        //   friend.un_read_count,
        // );
      }

      resetCallState();
      callConnectionStatus.value = '对方已终止呼叫';
      logWithTime('log', '对方已终止呼叫');

      setTimeout(() => {
        callConnectionStatus.value = '';
      }, 5000);
    }
  };

  // 发起通话
  const startCall = async (peerId, type) => {
    if (isInCall.value) {
      alert('您正在通话中，请先结束当前通话。');
      return;
    }

    const friend = friends.value.find((f) => f.id === peerId);
    if (!friend) {
      alert('好友信息无效');
      return;
    }

    if (!userStore.currentUser?.doctor_id) {
      alert('用户未登录，无法发起通话');
      return;
    }

    resetCallState();

    const callId =
      Date.now().toString() + Math.random().toString(36).slice(2, 11);

    currentCall.value = {
      callId,
      peerId,
      callType: type,
      startTime: Date.now(),
      status: 'calling',
    };

    callStatus.value = 'calling';
    callConnectionStatus.value = '等待对方接听...';

    // 立即获取本地媒体并显示
    try {
      logWithTime('log', '发起通话，立即获取本地媒体...');
      await webrtc.getLocalMedia({
        audio: true,
        video: type === 'video',
      });
      logWithTime('log', '本地媒体获取成功，可以显示自己的摄像头');
    } catch (error) {
      logWithTime('warn', '获取本地媒体失败，但继续通话流程:', error);
    }

    // 设置30秒超时
    setCallTimeout(() => {
      if (callStatus.value === 'calling') {
        resetCallState();
        callConnectionStatus.value = '对方无人接听';
        logWithTime('log', '呼叫超时，对方无人接听');

        callAPI.sendNoAnswer(
          userStore.currentUser.id,
          peerId,
          callId,
          type === 'video' ? 6 : 7,
        );

        friend.last_message = '[未接来电]';
        // chatDB.updateFriendLastMessage(
        //   friend.id,
        //   userStore.currentUser.id,
        //   '[未接来电]',
        //   friend.un_read_count,
        // );

        const callMessage = {
          type: type === 'video' ? 'video-call' : 'audio-call',
          content: '[未接来电]',
          time: new Date().toLocaleTimeString().slice(0, 5),
          senderId: userStore.currentUser?.doctor_id,
          read: true,
          timestamp: Date.now(),
          duration: 0,
        };
        // chatDB.saveMessage(callMessage, userStore.currentUser.id, friend.id);

        setTimeout(() => {
          callConnectionStatus.value = '';
        }, 5000);
      }
    }, 30_000);

    // 发送通话请求
    try {
      logWithTime('log', '准备发送通话邀请:', {
        senderUserId: userStore.currentUser.doctor_id,
        receiverUserId: peerId,
        callId,
        callType: type === 'video' ? 6 : 7,
      });

      await callAPI.invite(
        userStore.currentUser.id,
        peerId,
        callId,
        type === 'video' ? 6 : 7,
      );

      logWithTime('log', '发起通话成功:', currentCall.value);
    } catch (error) {
      logWithTime('error', '发起通话失败:', error);
      resetCallState();

      let errorMessage = '发起通话失败';
      if (error.response?.status === 400) {
        errorMessage = '请求参数错误，请检查网络连接';
      } else if (error.response?.status === 500) {
        errorMessage = '服务器错误，请稍后重试';
      } else if (error.message) {
        errorMessage = error.message;
      }

      alert(errorMessage);
    }
  };

  // 接听来电
  const acceptCall = async () => {
    if (!incomingCall.value) {
      logWithTime('log', '没有来电，无法接听');
      return;
    }

    if (callStatus.value === 'connecting' || callStatus.value === 'ongoing') {
      logWithTime('log', '通话已在进行中，忽略重复接听');
      return;
    }

    clearCallTimeout();

    logWithTime('log', '开始接听通话:', incomingCall.value);

    callStatus.value = 'connecting';
    callConnectionStatus.value = '正在连接...';

    try {
      // 获取本地媒体
      try {
        await webrtc.getLocalMedia({
          audio: true,
          video: incomingCall.value.callType === 'video',
        });
        logWithTime('log', '接听时获取本地媒体成功');
      } catch (mediaError) {
        logWithTime(
          'warn',
          '接听时获取本地媒体失败，但继续通话流程:',
          mediaError,
        );
      }

      // 发送接受信号
      await callAPI.accept(
        userStore.currentUser.id,
        incomingCall.value.callerId,
        incomingCall.value.callId,
        incomingCall.value.callType === 'video' ? 6 : 7,
      );

      currentCall.value = {
        callId: incomingCall.value.callId,
        peerId: incomingCall.value.callerId,
        callType: incomingCall.value.callType,
        startTime: Date.now(),
        status: 'connecting',
      };

      logWithTime('log', '接听通话成功，等待信令交换...');
    } catch (error) {
      logWithTime('error', '接听通话失败:', error);
      rejectCall('failed');
    }
  };

  // 拒绝来电
  const rejectCall = async (reason = 'rejected') => {
    if (!incomingCall.value) {
      logWithTime('log', '没有来电，无法拒绝');
      return;
    }

    if (callStatus.value === 'connecting' || callStatus.value === 'ongoing') {
      logWithTime('log', '通话已在进行中，无法拒绝');
      return;
    }

    logWithTime('log', '开始拒绝通话:', reason);

    try {
      await (reason === 'rejected'
        ? callAPI.reject(
            userStore.currentUser.id,
            incomingCall.value.callerId,
            incomingCall.value.callId,
            incomingCall.value.callType === 'video' ? 6 : 7,
          )
        : callAPI.sendFailed(
            userStore.currentUser.id,
            incomingCall.value.callerId,
            incomingCall.value.callId,
            incomingCall.value.callType === 'video' ? 6 : 7,
          ));

      const friend = friends.value.find(
        (f) => f.id === incomingCall.value.callerId,
      );
      if (friend) {
        const content =
          reason === 'busy'
            ? '[对方忙线]'
            : (reason === 'no-answer'
              ? '[未接来电]'
              : '[已拒绝]');

        const callMessage = {
          type:
            incomingCall.value.callType === 'video'
              ? 'video-call'
              : 'audio-call',
          content,
          time: new Date().toLocaleTimeString().slice(0, 5),
          senderId: userStore.currentUser?.doctor_id,
          read: true,
          timestamp: Date.now(),
          duration: 0,
        };
        // chatDB.saveMessage(callMessage, userStore.currentUser.id, friend.id);

        friend.last_message = content;
        // chatDB.updateFriendLastMessage(
        //   friend.id,
        //   userStore.currentUser.id,
        //   content,
        //   friend.un_read_count,
        // );
      }

      resetCallState();
      callConnectionStatus.value =
        reason === 'busy'
          ? '对方忙线'
          : (reason === 'no-answer'
            ? '无人接听'
            : '已拒绝');

      setTimeout(() => {
        callConnectionStatus.value = '';
      }, 5000);

      logWithTime('log', '拒绝通话成功');
    } catch (error) {
      logWithTime('error', '拒绝通话失败:', error);
    }
  };

  // 结束通话
  const endCall = async (reason = 'ended') => {
    const callId = currentCall.value?.callId || incomingCall.value?.callId;
    const peerId = currentCall.value?.peerId || incomingCall.value?.callerId;
    const callTypeVal =
      currentCall.value?.callType || incomingCall.value?.callType;

    if (!callId || !peerId) {
      resetCallState();
      return;
    }

    try {
      await callAPI.end(
        userStore.currentUser.id,
        peerId,
        callId,
        callTypeVal === 'video' ? 6 : 7,
      );

      const friend = friends.value.find((f) => f.id === peerId);
      if (friend) {
        const duration =
          callStatus.value === 'ongoing'
            ? Math.floor(
                (Date.now() -
                  (currentCall.value?.startTime ||
                    incomingCall.value?.startTime)) /
                  1000,
              )
            : 0;

        let content = '';
        if (reason === 'no-answer') {
          content = '[未接来电]';
        } else if (duration > 0) {
          content = `[${callTypeVal === 'video' ? '视频' : '语音'}通话] ${Math.floor(duration / 60)}分${duration % 60}秒`;
        } else {
          content = '[通话结束]';
        }

        const callMessage = {
          type: callTypeVal === 'video' ? 'video-call' : 'audio-call',
          content,
          time: new Date().toLocaleTimeString().slice(0, 5),
          senderId: userStore.currentUser?.doctor_id,
          read: true,
          timestamp: Date.now(),
          duration,
        };
        // chatDB.saveMessage(callMessage, userStore.currentUser.id, friend.id);

        friend.last_message = content;
        // chatDB.updateFriendLastMessage(
        //   friend.id,
        //   userStore.currentUser.id,
        //   content,
        //   friend.un_read_count,
        // );
      }

      resetCallState();
      callConnectionStatus.value =
        reason === 'no-answer' ? '对方无人接听' : '通话结束';

      setTimeout(() => {
        callConnectionStatus.value = '';
      }, 5000);

      logWithTime('log', '结束通话成功');
    } catch (error) {
      logWithTime('error', '结束通话失败:', error);
      resetCallState();
    }
  };

  return {
    friends,
    hasMore,
    currentFriend,
    messages,
    connectionStatus,
    socket,
    currentCall,
    incomingCall,
    callStatus,
    callError,
    callConnectionStatus,
    newRegisterNotification,
    isConnected,
    isInCall,
    isCalling,
    isRinging,
    isConnecting,
    isOngoingCall,
    isDisconnected,
    isHangup,
    generateOldMessages,
    initDB,
    loadFriends,
    setCurrentFriend,
    switchFriend,
    addMessage,
    handleIncomingMessage,
    handleCallSignal,
    startCall,
    acceptCall,
    rejectCall,
    endCall,
    resetCallState,
    sendCallSignal: sendCallSignalInternal,
    clearCallTimeout,
    getMessageTypeName,
    getParsedContent,
  };
});
