import { useState, useEffect, useRef } from 'react';
import { useParams, useSearchParams } from 'react-router';
// import { ClassroomAPI } from '../../api/index.ts';
// @ts-types="../../../share/aliyun-rtc-sdk.d.ts"
// @ts-types="./alivc-im.iife.d.ts"
import AliRtcEngine, { AliRtcSubscribeState, AliRtcVideoTrack } from 'aliyun-rtc-sdk';
import { toast } from 'sonner';
import { User } from '../../hooks/AuthProvider';
import { aliyunClient, fileClient, chatMessageClient } from '@/client/api';
import { UserType } from '@/server/modules/users/user.enum';
export enum Role {
  Teacher = UserType.TEACHER,
  Student = UserType.STUDENT
}

// 从SDK中提取需要的类型和枚举
type ImEngine = InstanceType<typeof AliVCInteraction.ImEngine>;
type ImGroupManager = AliVCInteraction.AliVCIMGroupManager;
type ImMessageManager = AliVCInteraction.AliVCIMMessageManager;
type ImLogLevel = AliVCInteraction.ImLogLevel;
type ImMessageLevel = AliVCInteraction.ImMessageLevel;
const { ERROR } = AliVCInteraction.ImLogLevel;
const { NORMAL, HIGH } = AliVCInteraction.ImMessageLevel;

interface ImUser {
  userId: string;
  userExtension?: string;
}

interface ImGroupMessage {
  groupId: string;
  type: number;
  data: string;
  sender?: ImUser;
  timestamp?: number;
}

// 互动消息类型
enum InteractionAction {
  HandUp = 'hand_up',
  CancelHandUp = 'cancel_hand_up',
  AnswerHandUp = 'answer_hand_up',
  KickStudent = 'kick_student'
}

interface InteractionMessage {
  action: InteractionAction;
  studentId: string;
  studentName?: string;
  timestamp?: number;
  question?: string;
}

interface HandUpRequest {
  studentId: string;
  studentName?: string;
  timestamp: number;
  question?: string;
}

interface Question {
  studentId: string;
  studentName?: string;
  question: string;
  timestamp: number;
}

export enum ClassStatus {
  NOT_STARTED = 'not_started',
  IN_PROGRESS = 'in_progress',
  ENDED = 'ended',
  PRIVATE_ACCESS_DENIED = 'private_access_denied'
}


// 定义消息类型
export interface Message {
  type: 'text' | 'image' | 'system';
  content: string;
  sender?: string;
  senderId?: string;
  senderType?: UserType;
  timestamp: number;
  fileId?: number; // 用于图片消息的文件ID
}

export const useClassroom = ({ user }:{ user : User }) => {
  // 状态管理
  // const [userId, setUserId] = useState<string>(''); // 保持string类型

  const pathParams = useParams()
  const userId = user.id.toString();
  const [isCameraOn, setIsCameraOn] = useState<boolean>(false);
  const [isAudioOn, setIsAudioOn] = useState<boolean>(false);
  const [isScreenSharing, setIsScreenSharing] = useState<boolean>(false);
  const [className, setClassName] = useState<string>('');
  const [role, setRole] = useState<Role>(pathParams['role'] === Role.Teacher ? Role.Teacher : Role.Student);
  const [classId, setClassId] = useState<string>(pathParams['classId'] || '');
  const [isLoggedIn, setIsLoggedIn] = useState<boolean>(false);
  const [isJoinedClass, setIsJoinedClass] = useState<boolean>(false);
  const [msgText, setMsgText] = useState<string>('');
  const [messageList, setMessageList] = useState<Message[]>([]);
  const [errorMessage, setErrorMessage] = useState<string>('');
  const [classStatus, setClassStatus] = useState<ClassStatus>(ClassStatus.NOT_STARTED);
  const [handUpList, setHandUpList] = useState<HandUpRequest[]>([]);
  const [isPrivateClass, setIsPrivateClass] = useState<boolean>(false);
  const [questions, setQuestions] = useState<Question[]>([]);
  const [students, setStudents] = useState<Array<{id: string, name: string}>>([]);
  const [shareLink, setShareLink] = useState<string>('');
  const [showCameraOverlay, setShowCameraOverlay] = useState<boolean>(true);
  const [onlineCount, setOnlineCount] = useState<number>(0);
  const [pvCount, setPvCount] = useState<number>(0);
  const [showVideo, setShowVideo] = useState<boolean>(false);

  // SDK实例
  const imEngine = useRef<ImEngine | null>(null);
  const imGroupManager = useRef<ImGroupManager | null>(null);
  const imMessageManager = useRef<ImMessageManager | null>(null);
  const aliRtcEngine = useRef<AliRtcEngine | null>(null);
  const remoteVideoElMap = useRef<Record<string, HTMLVideoElement>>({});
  const remoteScreenContainer = useRef<HTMLDivElement>(null); // 主屏幕共享容器(重命名)
  const remoteCameraContainer = useRef<HTMLDivElement>(null); // 摄像头小窗容器

  const showMessage = (text: string, sender?: string, senderId?: string, senderType?: UserType): void => {
    const message: Message = {
      type: 'text',
      content: text,
      sender,
      senderId,
      senderType,
      timestamp: Date.now()
    };
    setMessageList((prevMessageList) => [...prevMessageList, message]);
  };

  const showImageMessage = (imageUrl: string, senderName: string, senderId?: string, senderType?: UserType): void => {
    const message: Message = {
      type: 'image',
      content: imageUrl,
      sender: senderName,
      senderId,
      senderType,
      timestamp: Date.now()
    };
    setMessageList((prevMessageList) => [...prevMessageList, message]);
  };

  const showSystemMessage = (text: string): void => {
    const message: Message = {
      type: 'system',
      content: text,
      timestamp: Date.now()
    };
    setMessageList((prevMessageList) => [...prevMessageList, message]);
  };

  // 同步版本的用户名获取，用于需要立即返回的场景
  const getUserNameByIdSync = (userId: string): string => {
    // 1. If RTC engine is available, try to get user info which may contain display name
    if (aliRtcEngine.current) {
      try {
        const userInfo = aliRtcEngine.current.getUserInfo(userId);
        // Check if userInfo has displayName or other name fields
        // Note: This depends on the RTC SDK implementation and whether display name was set during joinChannel
        if (userInfo && userInfo.displayName ) {
          return userInfo.displayName;
        }
      } catch (error) {
        console.error('获取RTC用户信息失败:', error);
      }
    }
    
    // 2. Fallback to default
    return `用户${userId}`;
  };

  // 保存消息到数据库
  const saveMessageToDatabase = async (message: Message): Promise<void> => {
    if (!classId) return;
    
    try {
      await chatMessageClient.$post({
        json: {
          classId,
          type: message.type,
          content: message.content,
          senderId: message.senderId || null,
          senderName: message.sender || null,
          senderType: message.senderType || null, // 添加senderType字段
          timestamp: message.timestamp,
          fileId: message.fileId || null // 添加fileId字段
        }
      });
    } catch (error) {
      console.error('保存消息到数据库失败:', error);
      // 静默失败，不影响用户体验
    }
  };

  // 重试操作函数
  const retryOperation = async <T>(
    operation: () => Promise<T>,
    maxRetries = 3,
    delay = 1000
  ): Promise<T> => {
    for (let i = 0; i < maxRetries; i++) {
      try {
        return await operation();
      } catch (error) {
        if (i === maxRetries - 1) throw error;
        await new Promise(resolve => setTimeout(resolve, delay * (i + 1)));
      }
    }
    throw new Error('Max retries exceeded');
  };

  // 保存IM消息到数据库（直接从IM消息对象创建）
  const saveImMessageToDatabase = async (
    msg: AliVCInteraction.ImMessage, 
    type: 'text' | 'image' | 'system',
    content: string,
    senderName?: string
  ): Promise<void> => {
    if (!classId) return;
    
    try {
      await chatMessageClient.$post({
        json: {
          classId,
          type,
          content,
          senderId: msg.sender?.userId || null,
          senderName: senderName || msg.sender?.userId || '系统',
          timestamp: msg.timestamp || Date.now()
        }
      });
    } catch (error) {
      console.error('保存IM消息到数据库失败:', error);
      // 静默失败，不影响用户体验
    }
  };

  // 批量保存消息到数据库
  const saveMessagesToDatabase = async (messages: Message[]): Promise<void> => {
    if (!classId || messages.length === 0) return;
    
    try {
      // 由于API只支持单条创建，这里逐条保存
      for (const message of messages) {
        await saveMessageToDatabase(message);
      }
    } catch (error) {
      console.error('批量保存消息到数据库失败:', error);
    }
  };

  const showToast = (type: 'info' | 'success' | 'error', message: string): void => {
    if (type === 'info') {
      toast.info(message);
    } else if (type === 'success') {
      toast.success(message);
    } else if (type === 'error') {
      toast.error(message);
    }
  };




  // 事件监听函数
  const listenImEvents = (): void => {
    if (!imEngine.current) return;    
    if(!role) {
      showToast('error', '角色不存在');
      return;
    }
    const loginRole = role === Role.Teacher ? 'admin' : Role.Student;

    imEngine.current.on('connectsuccess', () => {
      showSystemMessage('IM连接成功');
    });

    imEngine.current.on('disconnect', async (code: number) => {
      showSystemMessage(`IM断开连接: ${code}`);
      // 自动重连
      try {
        const res = await aliyunClient.im_token.$post({
          json: { role: loginRole }
        });
        if(!res.ok) { 
          const { message } = await res.json()
          throw new Error(message)
        }
        const { token, nonce, timestamp } = await res.json()
        await imEngine.current!.login({
          user: {
            userId,
            userExtension: JSON.stringify({ 
              nickname: user?.nickname || user?.username || '',
              userType: user.userType
            })
          },
          userAuth: {
            nonce,
            timestamp,
            token,
            role: loginRole
          }
        });
        showSystemMessage('IM自动重连成功');
      } catch (err: unknown) {
        const error = err as Error;
        showSystemMessage(`IM自动重连失败: ${error.message}`);
      }
    });
  };

  const listenGroupEvents = (): void => {
    if (!imGroupManager.current) return;

    imGroupManager.current.on('memberchange', (groupId: string, memberCount: number, joinUsers: ImUser[], leaveUsers: ImUser[]) => {
      showSystemMessage(`成员变更: 加入${joinUsers.length}人, 离开${leaveUsers.length}人`);
      
      // 更新学生列表
      setStudents(prevStudents => {
        let updatedStudents = [...prevStudents];
        
        // 处理离开的用户
        updatedStudents = updatedStudents.filter(student =>
          !leaveUsers.some(leaveUser => leaveUser.userId === student.id)
        );
        
        // 处理新加入的用户（排除老师自己）
        joinUsers.forEach(joinUser => {
          if (joinUser.userId !== userId) { // 排除老师自己
            const existingStudent = updatedStudents.find(s => s.id === joinUser.userId);
            if (!existingStudent) {
              try {
                const userExtension = joinUser.userExtension ? JSON.parse(joinUser.userExtension) : {};
                updatedStudents.push({
                  id: joinUser.userId,
                  name: userExtension.nickname || userExtension.username || joinUser.userId
                });
              } catch {
                updatedStudents.push({
                  id: joinUser.userId,
                  name: joinUser.userId
                });
              }
            }
          }
        });
        
        return updatedStudents;
      });
    });

    // 监听群组成员变化事件（1.4.1版本新增）
    imGroupManager.current.on('memberdatachange', (data: any) => {
      console.log('群组成员统计变化:', data);
      if (data.onlineCount !== undefined) {
        setOnlineCount(data.onlineCount);
      }
      if (data.pv !== undefined) {
        setPvCount(data.pv);
      }
    });
  };

  const listenMessageEvents = (): void => {
    if (!imMessageManager.current) return;

    imMessageManager.current.on('recvgroupmessage', async (msg: AliVCInteraction.ImMessage, groupId: string) => {
      if (msg.type === 88889) { // 课堂状态消息
        try {
          const data = JSON.parse(msg.data);
          if (data.action === 'start_class') {
            setClassStatus(ClassStatus.IN_PROGRESS);
            showSystemMessage('老师已开始上课');
          } else if (data.action === 'end_class') {
            setClassStatus(ClassStatus.ENDED);
            showSystemMessage('老师已结束上课');
            
            // 学生端收到结束课堂消息后，立即自动离开群组
            if (role === Role.Student) {
              try {
                if (imGroupManager.current && classId) {
                  await imGroupManager.current.leaveGroup(classId);
                  showSystemMessage('已自动离开课堂群组');
                }
                if (aliRtcEngine.current) {
                  await leaveRtcChannel();
                }
                // 清理学生端状态
                setIsJoinedClass(false);
                setClassId('');
                setStudents([]);
                setHandUpList([]);
                setQuestions([]);
                setMessageList([]);
              } catch (err) {
                console.error('自动离开群组失败:', err);
              }
            }
          }
        } catch (err) {
          console.error('解析课堂状态消息失败', err);
        }
      } else if (msg.type === 88890) { // 静音指令
        try {
          const data = JSON.parse(msg.data);
          if (data.action === 'toggle_mute' && data.userId === userId) {
            showSystemMessage(data.mute ? '你已被老师静音' : '老师已取消你的静音');
          }
        } catch (err) {
          console.error('解析静音指令失败', err);
        }
      } else if (msg.type === 88891) { // 举手消息
        try {
          const data = JSON.parse(msg.data) as InteractionMessage;
          if (data.action === InteractionAction.HandUp) {
            const handUpData: HandUpRequest = {
              ...data,
              timestamp: data.timestamp || Date.now()
            };
            setHandUpList([...handUpList, handUpData]);
            showSystemMessage(`${data.studentName || getUserNameByIdSync(data.studentId)} 举手了`);
          } else if (data.action === InteractionAction.CancelHandUp) {
            setHandUpList(handUpList.filter(h => h.studentId !== data.studentId));
          }
        } catch (err) {
          console.error('解析举手消息失败', err);
        }
      } else if (msg.type === 88892) { // 问题消息
        try {
          const data = JSON.parse(msg.data) as {question: string};
          if (typeof data.question === 'string') {
            const question: Question = {
              studentId: msg.sender?.userId || 'unknown',
              studentName: (() => {
                try {
                  return msg.sender?.userExtension ? JSON.parse(msg.sender.userExtension)?.nickname : null;
                } catch {
                  return null;
                }
              })() || msg.sender?.userId || '未知用户',
              question: data.question,
              timestamp: msg.timestamp || Date.now()
            };
            setQuestions([...questions, question]);
          }
          showSystemMessage(`收到问题: ${data.question}`);
        } catch (err) {
          console.error('解析问题消息失败', err);
        }
      } else if (msg.type === 88893) { // 应答消息
        try {
          const data = JSON.parse(msg.data) as InteractionMessage;
          if (data.action === InteractionAction.AnswerHandUp && data.studentId === userId) {
            showSystemMessage('老师已应答你的举手');
            setHandUpList(handUpList.filter(h => h.studentId !== data.studentId));
          }
        } catch (err) {
          console.error('解析应答消息失败', err);
        }
      } else if (msg.type === 88894) { // 踢人消息
        try {
          const data = JSON.parse(msg.data) as InteractionMessage;
          if (data.action === InteractionAction.KickStudent && data.studentId === userId) {
            showSystemMessage('您已被老师移出课堂');
            // 学生被踢出后自动离开课堂
            setTimeout(() => {
              leaveClass();
            }, 2000);
          }
        } catch (err) {
          console.error('解析踢人消息失败', err);
        }
      } else if (msg.type === 88888) { // 普通文本消息
        const sender = msg.sender;  console.log('sender', sender)
        // 使用正确的 ImUser 类型处理发送者信息
        const userExtension = (sender?.userExtension ? JSON.parse(sender.userExtension) : {}) as User;
        const senderName = userExtension.nickname || userExtension.username || sender?.userId || '未知用户';
        const senderType = userExtension.userType // 从用户扩展信息中获取类型
        showMessage(msg.data, senderName, sender?.userId, senderType);
      } else if (msg.type === 88895) { // 图片消息
        try {
          const data = JSON.parse(msg.data);
          if (data.type === 'image' && data.fileId) {
            const sender = msg.sender;
            // 使用正确的 ImUser 类型处理发送者信息
            const userExtension = (sender?.userExtension ? JSON.parse(sender.userExtension) : {}) as User;
            const senderName = userExtension.nickname || userExtension.username || sender?.userId || '未知用户';
            const senderType = userExtension.userType // 从用户扩展信息中获取类型
            
            // 收到文件ID后获取文件详情
            const response = await fileClient[':id']['$get']({ param: { id: data.fileId.toString() } });
            if (response.status === 200) {
              const fileInfo = await response.json();
              showImageMessage(fileInfo.fullUrl, senderName, sender?.userId, senderType);
            } else {
              showSystemMessage(`${senderName}: 图片获取失败`);
            }
          }
        } catch (err) {
          console.error('解析图片消息失败', err);
          showSystemMessage('图片消息解析失败');
        }
      }
    });
  };

  // RTC相关函数
  const removeRemoteVideo = (userId: string, type: 'camera' | 'screen' = 'camera') => {
    const vid = `${type}_${userId}`;
    const el = remoteVideoElMap.current[vid];
    if (el) {
      aliRtcEngine.current!.setRemoteViewConfig(null, userId, type === 'camera' ? AliRtcVideoTrack.AliRtcVideoTrackCamera : AliRtcVideoTrack.AliRtcVideoTrackScreen);
      el.pause();
      
      // 根据流类型从不同容器移除
      if (type === 'camera') {
        remoteCameraContainer.current?.removeChild(el);
      } else {
        remoteScreenContainer.current?.removeChild(el);
      }
      delete remoteVideoElMap.current[vid];
    }
  };

  const listenRtcEvents = () => {
    if (!aliRtcEngine.current) return;

    showSystemMessage('注册rtc事件监听')

    aliRtcEngine.current.on('remoteUserOnLineNotify', (userId: string) => {
      // showMessage(`用户 ${userId} 加入课堂`);
      console.log('用户上线通知:', userId);
    });

    aliRtcEngine.current.on('remoteUserOffLineNotify', (userId: string) => {
      // showMessage(`用户 ${userId} 离开课堂`);
      console.log('用户下线通知:', userId);
      removeRemoteVideo(userId, 'camera');
      removeRemoteVideo(userId, 'screen');
    });

    aliRtcEngine.current.on('videoSubscribeStateChanged', (
      userId: string,
      oldState: AliRtcSubscribeState,
      newState: AliRtcSubscribeState,
      interval: number,
      channelId: string
    ) => {
      console.log(`视频订阅状态变化: 用户 ${userId}, 旧状态 ${oldState}, 新状态 ${newState}`);

      switch(newState) {
        case 3: // 订阅成功
          try {
            console.log('开始创建远程视频元素');
            
            if (remoteVideoElMap.current[`camera_${userId}`]) {
              console.log(`用户 ${userId} 的视频元素已存在`);
              return;
            }
            
            const video = document.createElement('video');
            video.autoplay = true;
            video.playsInline = true;
            video.className = 'w-80 h-45 mr-2 mb-2 bg-black';
            
            if (!remoteCameraContainer.current) {
              console.error('摄像头视频容器未找到');
              return;
            }
            
            remoteCameraContainer.current.appendChild(video);
            remoteVideoElMap.current[`camera_${userId}`] = video;
            
            aliRtcEngine.current!.setRemoteViewConfig(
              video,
              userId,
              AliRtcVideoTrack.AliRtcVideoTrackCamera
            );
            
            console.log(`已订阅用户 ${userId} 的视频流`);
            showSystemMessage(`已显示用户 ${getUserNameByIdSync(userId)} 的视频`);
            // 自动显示视频区域
            setShowVideo(true);
          } catch (err) {
            console.error(`订阅用户 ${userId} 视频流失败:`, err);
            showSystemMessage(`订阅用户 ${getUserNameByIdSync(userId)} 视频流失败`);
          }
          break;
          
        case 1: // 取消订阅
          console.log(`取消订阅用户 ${userId} 的视频流`);
          showSystemMessage(`取消订阅用户 ${getUserNameByIdSync(userId)} 的视频流`);
          removeRemoteVideo(userId, 'camera');
          // 如果没有其他视频流，隐藏视频区域
          hideVideoAreaIfNoStreams();
          break;
          
        case 2: // 订阅中
          console.log(`正在订阅用户 ${userId} 的视频流...`);
          break;
          
        default:
          console.warn(`未知订阅状态: ${newState}`);
      }
    });

    aliRtcEngine.current.on('screenShareSubscribeStateChanged', (
      userId: string,
      oldState: AliRtcSubscribeState,
      newState: AliRtcSubscribeState,
      elapseSinceLastState: number,
      channel: string
    ) => {
      console.log(`屏幕分享订阅状态变更：uid=${userId}, oldState=${oldState}, newState=${newState}`);

      switch(newState) {
        case 3: // 订阅成功
          try {
            console.log('开始创建屏幕分享视频元素');
            
            if (remoteVideoElMap.current[`screen_${userId}`]) {
              console.log(`用户 ${userId} 的屏幕分享元素已存在`);
              return;
            }
            
            const video = document.createElement('video');
            video.autoplay = true;
            video.playsInline = true;
            video.className = 'w-full h-full bg-black';
            
            if (!remoteScreenContainer.current) {
              console.error('屏幕共享容器未找到');
              return;
            }
            
            remoteScreenContainer.current.appendChild(video);
            remoteVideoElMap.current[`screen_${userId}`] = video;
            
            aliRtcEngine.current!.setRemoteViewConfig(
              video,
              userId,
              AliRtcVideoTrack.AliRtcVideoTrackScreen
            );
            
            console.log(`已订阅用户 ${userId} 的屏幕分享流`);
            showSystemMessage(`已显示用户 ${getUserNameByIdSync(userId)} 的屏幕分享`);
            // 自动显示视频区域
            setShowVideo(true);
          } catch (err) {
            console.error(`订阅用户 ${userId} 屏幕分享流失败:`, err);
            showSystemMessage(`订阅用户 ${getUserNameByIdSync(userId)} 屏幕分享流失败`);
          }
          break;
          
        case 1: // 取消订阅
          console.log(`取消订阅用户 ${userId} 的屏幕分享流`);
          showSystemMessage(`取消订阅用户 ${getUserNameByIdSync(userId)} 的屏幕分享流`);
          removeRemoteVideo(userId, 'screen');
          // 如果没有其他视频流，隐藏视频区域
          hideVideoAreaIfNoStreams();
          break;
          
        case 2: // 订阅中
          console.log(`正在订阅用户 ${userId} 的屏幕分享流...`);
          break;
          
        default:
          console.warn(`未知屏幕分享订阅状态: ${newState}`);
      }
    });
  };

  // 课堂操作方法
  const login = async (role: Role): Promise<void> => {
    if(!role) {
      showToast('error', '角色不存在');
      return;
    }
    const loginRole = role === Role.Teacher ? 'admin' : Role.Student;

    try {
      const { ImEngine: ImEngineClass } = window.AliVCInteraction;
      const res = await aliyunClient.im_token.$post({
        json: { role: loginRole }
      });
      if(!res.ok) { 
        const { message } = await res.json()
        throw new Error(message)
      }
      const {appId, appSign, timestamp, nonce, token} = await res.json();
      imEngine.current = ImEngineClass.createEngine();
      await imEngine.current.init({
        deviceId: 'xxxx',
        appId,
        appSign,
        logLevel: ERROR,
      });
      await imEngine.current.login({
        user: {
          userId,
          userExtension: JSON.stringify({ 
            nickname: user?.nickname || user?.username || '',
            userType: user.userType
          })
        },
        userAuth: {
          nonce,
          timestamp,
          token,
          role: loginRole
        }
      });
      
      aliRtcEngine.current = AliRtcEngine.getInstance();
      AliRtcEngine.setLogLevel(0);
      
      listenImEvents();
      listenRtcEvents();
      
      setIsLoggedIn(true);
      setErrorMessage('');
      showToast('success', '登录成功');
    } catch (err: any) {
      setErrorMessage(`登录失败: ${err.message}`);
      showToast('error', '登录失败');
      console.error('登录失败', err)
    }
  };

  const joinClass = async (classId: string): Promise<void> => {
    if (!imEngine.current || !aliRtcEngine.current) return;

    try {
      const gm = imEngine.current.getGroupManager();
      const mm = imEngine.current.getMessageManager();
      imGroupManager.current = gm || null;
      imMessageManager.current = mm || null;

      // 得先加入群组才能获取到群组信息
      await gm!.joinGroup(classId);

      // 先获取群组信息并检查闭门标识
      let groupInfo;
      let hasPermission = true; // 权限检查标志
      try {
        groupInfo = await gm!.queryGroup(classId);

        // 检查闭门课堂权限
        if (groupInfo && groupInfo.groupMeta) {
          try {
            const meta = JSON.parse(groupInfo.groupMeta);
            if (meta.isPrivate) {
              // 设置闭门标识状态
              setIsPrivateClass(true);
              // 闭门课堂，允许老师和学员身份进入
              console.log('user.userType', user.userType)
              if (user.userType !== UserType.TRAINEE && user.userType !== UserType.TEACHER) {
                // 不抛出错误，而是设置错误状态并阻止后续操作
                setErrorMessage('该课堂为闭门会议，只有老师和学员身份可以进入');
                setIsPrivateClass(true);
                hasPermission = false;
              }
            } else {
              setIsPrivateClass(false);
            }
          } catch (parseError) {
            console.error('解析群组元数据失败:', parseError);
            setIsPrivateClass(false);
          }
        }
      } catch (err) {
        console.error('获取群组信息失败:', err);
      }

      // 如果没有权限，设置课堂状态为权限不足
      if (!hasPermission) {
        console.log('该课堂为闭门会议，只有老师和学员身份可以进入')
        setClassStatus(ClassStatus.PRIVATE_ACCESS_DENIED);
        return;
      }

      listenGroupEvents();
      listenMessageEvents();

      // 加载历史聊天消息
      try {
        const response = await chatMessageClient.$get({
          query: {
            page: 1,
            pageSize: 50, 
            filters: JSON.stringify({classId}),
            sortBy: 'timestamp',
            sortOrder: 'ASC'
          }
        });
        
        if (response.status === 200) {
          const historyData = await response.json();
          if (historyData.data && historyData.data.length > 0) {
            // 将历史消息添加到消息列表
            const historyMessages: Message[] = historyData.data.map((msg) => ({
              type: msg.type,
              content: msg.type === 'image' && msg.file ? msg.file.fullUrl : msg.content,
              sender: msg.senderName || '',
              senderId: msg.senderId?.toString() || '',
              senderType: msg.senderType as UserType, // 添加senderType字段
              timestamp: msg.timestamp
            }));
            
            setMessageList(prev => [...historyMessages, ...prev]);
            showSystemMessage(`已加载 ${historyData.data.length} 条历史消息`);
          }
        }
      } catch (error) {
        console.error('加载历史消息失败:', error);
        // 静默失败，不影响主要功能
      }

      // 只有老师角色需要获取现有的群组成员列表
      if (role === Role.Teacher) {
        try {
          const membersResponse = await gm!.listRecentGroupUser(classId);
          if (membersResponse && membersResponse.userList) {
            const existingMembers = membersResponse.userList
              // .filter(member => member.userId !== userId) // 排除老师自己
              .map(member => {
                try {
                  const userExtension = member.userExtension ? JSON.parse(member.userExtension) : {};
                  return {
                    id: member.userId,
                    name: userExtension.nickname || userExtension.username || member.userId
                  };
                } catch {
                  return {
                    id: member.userId,
                    name: member.userId
                  };
                }
              });
            
            setStudents(existingMembers);
            showSystemMessage(`已加载 ${existingMembers.length} 名现有学生`);
          }
        } catch (err) {
          console.error('获取群组成员失败:', err);
          showSystemMessage('获取现有学生列表失败，将只显示新加入的学生');
        }
      }

      // 获取群组统计信息
      if (groupInfo && groupInfo.statistics) {
        setOnlineCount(groupInfo.statistics.onlineCount || 0);
        setPvCount(groupInfo.statistics.pv || 0);
        console.log('群组统计信息:', groupInfo.statistics);
      }
      await joinRtcChannel(classId);

      buildShareLink(classId)

      setIsJoinedClass(true);
      setErrorMessage('');
      showToast('success', '加入课堂成功');
    } catch (err: any) {
      // 处理群组不存在或已删除的错误（错误码440）
      if (err.message?.includes('440') || err.message?.includes('group not exists')) {
        // 直接设置课堂状态为已结束，显示全屏提示
        setClassStatus(ClassStatus.ENDED);
      } else {
        setErrorMessage(`加入课堂失败: ${err.message}`);
        showToast('error', '加入课堂失败');
        console.error('加入课堂失败', err)
      }
      
      if (imGroupManager.current) {
        try {
          await imGroupManager.current.leaveGroup(classId);
        } catch (leaveErr) {
          console.error('离开IM群组失败:', leaveErr);
        }
      }
    }
  };

  const leaveClass = async (): Promise<void> => {
    try {
      if (imGroupManager.current && classId) {
        await imGroupManager.current.leaveGroup(classId);
      }
      if (aliRtcEngine.current) {
        await leaveRtcChannel();
      }
      
      setIsJoinedClass(false);
      showToast('info', '已离开课堂');
    } catch (err) {
      console.error('离开课堂失败:', err);
      showToast('error', '离开课堂时发生错误');
    }
  };

  const sendMessage = async (): Promise<void> => {
    if (!imMessageManager.current || !classId) return;

    if (!msgText.trim()) {
      showToast('error', '消息不能为空');
      return;
    }

    try {
      // 先发送IM消息（包含禁言等权限检查）
      await imMessageManager.current.sendGroupMessage({
        groupId: classId,
        data: msgText,
        type: 88888,
        level: NORMAL,
      });
      
      // IM发送成功后再保存到数据库
      const message: Message = {
        type: 'text',
        content: msgText,
        sender: user?.nickname || user?.username || '',
        senderId: userId,
        senderType: user?.userType, // 添加用户类型
        timestamp: Date.now()
      };
      
      try {
        await saveMessageToDatabase(message);
      } catch (dbError) {
        console.error('数据库保存失败（消息已发送）:', dbError);
        // 静默失败，不影响用户体验
      }
      
      setMsgText('');
      setErrorMessage('');
      
    } catch (err: any) {
      // 检查是否为禁言错误 (错误码442)
      if (err.message?.includes('code:442') || err.message?.includes('not allowed to send message')) {
        showToast('error', '您已被禁言，无法发送消息');
      } else {
        showToast('error', `消息发送失败: ${err.message}`);
      }
    }
  };

  const sendImageMessageById = async (fileId: number): Promise<void> => {
    if (!imMessageManager.current || !classId) return;

    try {
      // 先发送IM消息（包含禁言等权限检查）
      await imMessageManager.current!.sendGroupMessage({
        groupId: classId,
        data: JSON.stringify({
          type: 'image',
          fileId: fileId
        }),
        type: 88895, // 使用单一消息类型用于图片
        level: NORMAL,
      });
      
      // IM发送成功后再保存到数据库
      const message: Message = {
        type: 'image',
        content: '[图片]', // 内容字段保存描述文本
        sender: user?.nickname || user?.username || '',
        senderId: userId,
        senderType: user?.userType, // 添加用户类型
        timestamp: Date.now(),
        fileId: fileId // 新增fileId字段
      };
      
      try {
        await saveMessageToDatabase(message);
      } catch (dbError) {
        console.error('数据库保存失败（图片消息已发送）:', dbError);
        // 静默失败，不影响用户体验
      }
      
    } catch (err: any) {
      // 检查是否为禁言错误 (错误码442)
      if (err.message?.includes('code:442') || err.message?.includes('not allowed to send message')) {
        showToast('error', '您已被禁言，无法发送图片');
      } else {
        showToast('error', `图片发送失败: ${err.message}`);
      }
    }
  };


  const startClass = async (): Promise<void> => {
    if (!imMessageManager.current || !classId || role !== Role.Teacher) return;
    
    try {
      // 先保存开始上课消息到数据库
      await saveMessageToDatabase({
        type: 'system',
        content: '老师已开始上课',
        sender: user?.nickname || user?.username || '老师',
        senderId: userId,
        timestamp: Date.now()
      });
      
      await imMessageManager.current.sendGroupMessage({
        groupId: classId,
        data: JSON.stringify({ action: 'start_class' }),
        type: 88889,
        level: HIGH,
      });
      setClassStatus(ClassStatus.IN_PROGRESS);
      showToast('success', '课堂已开始');
    } catch (err: any) {
      setErrorMessage(`开始上课失败: ${err.message}`);
    }
  };

  const endClass = async (): Promise<void> => {
    if (!imMessageManager.current || !classId || role !== Role.Teacher) return;
    
    try {
      // 先保存结束上课消息到数据库
      await saveMessageToDatabase({
        type: 'system',
        content: '老师已结束上课',
        sender: user?.nickname || user?.username || '老师',
        senderId: userId,
        timestamp: Date.now()
      });
      
      // 1. 发送结束课堂消息
      await imMessageManager.current.sendGroupMessage({
        groupId: classId,
        data: JSON.stringify({ action: 'end_class' }),
        type: 88889,
        level: HIGH,
      });
      setClassStatus(ClassStatus.ENDED);
      showToast('success', '课堂已结束');
      
      try {
        // 2. 离开RTC频道
        await leaveRtcChannel();
      } catch (err: any) {
        console.error('离开RTC频道失败:', err);
        showToast('error', '离开RTC频道失败');
      }

      try {
        // 3. 关闭群组（删除群组）
        if (imGroupManager.current) {
          await imGroupManager.current.closeGroup(classId);
          showSystemMessage('群组已关闭');
          
          // 4. 清理状态
          setIsJoinedClass(false);
          setClassId('');
          setStudents([]);
          setHandUpList([]);
          setQuestions([]);
          setMessageList([]);
        }
      } catch (err: any) {
        console.error('关闭群组失败:', err);
        showToast('error', '关闭群组失败');
      }
    } catch (err: any) {
      setErrorMessage(`结束上课失败: ${err.message}`);
    }
  };

  const toggleMuteMember = async (userId: string, mute: boolean): Promise<void> => {
    if (!imMessageManager.current || !classId || role !== Role.Teacher) return;
    
    try {
      // 先保存静音消息到数据库
      await saveMessageToDatabase({
        type: 'system',
        content: mute ? `老师已将用户 ${getUserNameByIdSync(userId)} 静音` : `老师已取消用户 ${getUserNameByIdSync(userId)} 的静音`,
        sender: user?.nickname || user?.username || '老师',
        senderId: userId,
        timestamp: Date.now()
      });
      
      // 1. 发送IM消息通知静音状态变化
      await imMessageManager.current.sendGroupMessage({
        groupId: classId,
        data: JSON.stringify({
          action: 'toggle_mute',
          userId,
          mute
        }),
        type: 88890,
        level: HIGH,
      });
      
      // 2. 执行真正的RTC静音/取消静音操作
      if (aliRtcEngine.current) {
        aliRtcEngine.current.muteRemoteAudioPlaying(userId, mute);
      }
      
      showToast('info', mute ? `已静音用户 ${getUserNameByIdSync(userId)}` : `已取消静音用户 ${getUserNameByIdSync(userId)}`);
    } catch (err: any) {
      setErrorMessage(`操作失败: ${err.message}`);
    }
  };

  const buildShareLink = (classId: string) => {
    const getBaseUrl = () => {
      const protocol = window.location.protocol;
      const host = window.location.host;
      return `${protocol}//${host}`;
  }
    // const baseUrl = window.location.href.split('?')[0].replace(/\/[^/]*$/, '');
    const baseUrl = getBaseUrl();
    setShareLink(`${baseUrl}/mobile/classroom/${classId}/student`);
  }

  const createClass = async (className: string, maxMembers = 200, isPrivate = false): Promise<string | null> => {
    if (!imEngine.current || !isLoggedIn || role !== Role.Teacher) {
      showToast('error', '只有老师可以创建课堂');
      return null;
    }
    
    try {
      const gm = imEngine.current.getGroupManager();
      if (!gm) {
        throw new Error('群组管理器未初始化');
      }

      if(isPrivate)
        showToast('info', '正在创建闭门课堂...');
      else
        showToast('info', '正在创建公开课堂...');
      
      const response = await gm.createGroup({
        groupName: className,
        groupMeta: JSON.stringify({
          classType: 'interactive',
          creator: userId,
          createdAt: Date.now(),
          maxMembers,
          isPrivate: isPrivate
        })
      });

      if (!response?.groupId) {
        throw new Error('创建群组失败: 未返回群组ID');
      }

      const mm = imEngine.current.getMessageManager();
      
      await gm.joinGroup(response.groupId);
      
      showToast('success', '课堂创建并加入成功');
      showSystemMessage(`课堂 ${className} 创建成功，ID: ${response.groupId}`);
      
      setClassId(response.groupId);
      setIsJoinedClass(true);
      
      imGroupManager.current = gm;
      listenGroupEvents();
      
      if (mm) {
        imMessageManager.current = mm;
        listenMessageEvents();
      }
      
      await joinRtcChannel(response.groupId);
      buildShareLink(response.groupId);
      
      return response.groupId;
    } catch (err: any) {
      const errorMsg = err.message.includes('alreadyExist')
        ? '课堂已存在'
        : `课堂创建失败: ${err.message}`;
      
      setErrorMessage(errorMsg);
      showToast('error', errorMsg);
      return null;
    }
  };

  const joinRtcChannel = async (classId: string, publishOptions?: {
    publishVideo?: boolean
    publishAudio?: boolean
    publishScreen?: boolean
  }) => {
    if (!aliRtcEngine.current) return;
    const {
      publishVideo = false,
      publishAudio = false,
      publishScreen = false,
    } = publishOptions || {};
    const res = await aliyunClient.rtc_token.$post({
      json: { channelId: classId }
    });
    if(!res.ok) { 
      const { message } = await res.json()
      throw new Error(message)
    }
    const { appId, token, timestamp } = await res.json()
    await aliRtcEngine.current.publishLocalVideoStream(publishVideo);
    await aliRtcEngine.current.publishLocalAudioStream(publishAudio);
    await aliRtcEngine.current.publishLocalScreenShareStream(publishScreen);
    await aliRtcEngine.current.joinChannel(
      {
        channelId: classId,
        userId,
        appId,
        token,
        timestamp,
      },
      user?.nickname || user?.username || userId
    );
  };

  const leaveRtcChannel = async () => {
    if (!aliRtcEngine.current) return;
    await aliRtcEngine.current.leaveChannel();
  };

  // 切换摄像头状态
  const toggleCamera = async () => {
    if(!aliRtcEngine.current?.isInCall){
      showToast('error', '先加入课堂');
      return;
    }

    try {
      if (isCameraOn) {
        await aliRtcEngine.current?.stopPreview();
        await aliRtcEngine.current?.enableLocalVideo(false)
        await aliRtcEngine.current?.publishLocalVideoStream(false)
      } else {
        await aliRtcEngine.current?.setLocalViewConfig('localPreviewer', AliRtcVideoTrack.AliRtcVideoTrackCamera);
        await aliRtcEngine.current?.enableLocalVideo(true)
        await aliRtcEngine.current?.startPreview();
        await aliRtcEngine.current?.publishLocalVideoStream(true)
   
      }
      setIsCameraOn(!isCameraOn);
    } catch (err) {
      console.error('切换摄像头状态失败:', err);
      showToast('error', '切换摄像头失败');
    }
  };

  // 切换音频状态
  const toggleAudio = async () => {
    if(!aliRtcEngine.current?.isInCall){
      showToast('error', '先加入课堂');
      return;
    }

    try {
      if (isAudioOn) {
        await aliRtcEngine.current?.stopAudioCapture();
        await aliRtcEngine.current?.publishLocalAudioStream(false);
      } else {
        await aliRtcEngine.current?.publishLocalAudioStream(true);
      }
      setIsAudioOn(!isAudioOn);
    } catch (err) {
      console.error('切换麦克风状态失败:', err);
      showToast('error', '切换麦克风失败');
    }
  };

  // 切换屏幕分享状态
  const toggleScreenShare = async () => {
    if(!aliRtcEngine.current?.isInCall){
      showToast('error', '先加入课堂');
      return;
    }

    try {
      if (isScreenSharing) {
        await aliRtcEngine.current?.publishLocalScreenShareStream(false)
        await aliRtcEngine.current?.stopScreenShare()
      } else {
        await aliRtcEngine.current?.publishLocalScreenShareStream(true)
        await aliRtcEngine.current?.setLocalViewConfig(
          'screenPreviewer',
          AliRtcVideoTrack.AliRtcVideoTrackScreen
        );
      }
      setIsScreenSharing(!isScreenSharing);
    } catch (err) {
      console.error('切换屏幕分享失败:', err);
      showToast('error', '切换屏幕分享失败');
    }
  };

  const handUp = async (question?: string): Promise<void> => {
    if (!imMessageManager.current || !classId || role !== 'student') return;
    
    try {
      // 先保存举手消息到数据库
      await saveMessageToDatabase({
        type: 'system',
        content: question ? `学生 ${getUserNameByIdSync(userId)} 举手提问: ${question}` : `学生 ${getUserNameByIdSync(userId)} 举手`,
        sender: user?.nickname || user?.username || `学生${getUserNameByIdSync(userId)}`,
        senderId: userId,
        timestamp: Date.now()
      });
      
      await imMessageManager.current.sendGroupMessage({
        groupId: classId,
        data: JSON.stringify({
          action: 'hand_up',
          studentId: userId,
          timestamp: Date.now(),
          question
        }),
        type: 88891,
        level: NORMAL,
      });
    } catch (err: any) {
      // 检查是否为禁言错误 (错误码442)
      if (err.message?.includes('code:442') || err.message?.includes('not allowed to send message')) {
        setErrorMessage('您已被禁言，无法举手提问');
      } else {
        setErrorMessage(`举手失败: ${err.message}`);
      }
    }
  };

  const muteStudent = async (studentId: string): Promise<void> => {
    if (!imMessageManager.current || !classId || role !== Role.Teacher) return;
    
    try {
      // 1. 发送IM消息通知学生被静音
      await imMessageManager.current.sendGroupMessage({
        groupId: classId,
        data: JSON.stringify({
          action: 'toggle_mute',
          userId: studentId,
          mute: true
        }),
        type: 88890,
        level: HIGH,
      });
      
      // 2. 执行真正的RTC静音操作
      if (aliRtcEngine.current) {
        aliRtcEngine.current.muteRemoteAudioPlaying(studentId, true);
      }
      
      showToast('info', `已静音学生 ${getUserNameByIdSync(studentId)}`);
    } catch (err: any) {
      setErrorMessage(`静音失败: ${err.message}`);
    }
  };

  const kickStudent = async (studentId: string): Promise<void> => {
    if (!imGroupManager.current || !classId || role !== Role.Teacher) return;
    
    try {
      // 先保存踢人消息到数据库
      await saveMessageToDatabase({
        type: 'system',
        content: `老师已将用户 ${getUserNameByIdSync(studentId)} 移出课堂`,
        sender: user?.nickname || user?.username || '老师',
        senderId: userId,
        timestamp: Date.now()
      });
      
      // 使用InteractionAction发送踢人消息
      await imMessageManager.current?.sendGroupMessage({
        groupId: classId,
        data: JSON.stringify({
          action: InteractionAction.KickStudent,
          studentId: studentId,
          timestamp: Date.now()
        }),
        type: 88894, // 使用新的消息类型表示踢人操作
        level: HIGH,
      });
      
      showToast('info', `已发送移出指令给学生 ${getUserNameByIdSync(studentId)}`);
    } catch (err: any) {
      setErrorMessage(`移出失败: ${err.message}`);
    }
  };

  // IM禁言功能 - 禁止学生在聊天室发送消息
  const muteStudentIM = async (studentId: string): Promise<void> => {
    if (!imGroupManager.current || !classId || role !== Role.Teacher) return;
    
    try {
      await imGroupManager.current.muteUser({
        groupId: classId,
        userList: [studentId],
      });
      showToast('info', `已禁言学生 ${getUserNameByIdSync(studentId)}（IM聊天）`);
    } catch (err: any) {
      setErrorMessage(`IM禁言失败: ${err.message}`);
    }
  };

  // 取消IM禁言
  const unmuteStudentIM = async (studentId: string): Promise<void> => {
    if (!imGroupManager.current || !classId || role !== Role.Teacher) return;
    
    try {
      await imGroupManager.current.cancelMuteUser({
        groupId: classId,
        userList: [studentId],
      });
      showToast('info', `已取消禁言学生 ${getUserNameByIdSync(studentId)}（IM聊天）`);
    } catch (err: any) {
      setErrorMessage(`取消IM禁言失败: ${err.message}`);
    }
  };

  // 全体IM禁言
  const muteAllIM = async (): Promise<void> => {
    if (!imGroupManager.current || !classId || role !== Role.Teacher) return;
    
    try {
      await imGroupManager.current.muteAll({
        groupId: classId,
      });
      showToast('info', '已全体禁言（IM聊天）');
    } catch (err: any) {
      // setErrorMessage(`全体IM禁言失败: ${err.message}`);
      showToast('error', `全体IM禁言失败: ${err.message}`);
      throw err;
    }
  };

  // 取消全体IM禁言
  const unmuteAllIM = async (): Promise<void> => {
    if (!imGroupManager.current || !classId || role !== Role.Teacher) return;
    
    try {
      await imGroupManager.current.cancelMuteAll({
        groupId: classId
      });
      showToast('info', '已取消全体禁言（IM聊天）');
    } catch (err: any) {
      // setErrorMessage(`取消全体IM禁言失败: ${err.message}`);
      showToast('error', `取消全体IM禁言失败: ${err.message}`);
      throw err;
    }
  };

  // 查询用户禁言状态
  const checkMuteStatus = async (userId: string): Promise<boolean> => {
    if (!imGroupManager.current || !classId) return false;
    
    try {
      const muteStatus = await imGroupManager.current.listMuteUsers({ groupId: classId });
      return muteStatus.muteUserList.includes(userId);
    } catch (error) {
      console.error('查询禁言状态失败:', error);
      return false;
    }
  };

  // 查询全员禁言状态
  const checkAllMuteStatus = async (): Promise<boolean> => {
    if (!imGroupManager.current || !classId) return false;
    
    try {
      const groupInfo = await imGroupManager.current.queryGroup(classId);
      return groupInfo.muteStatus?.muteAll || false;
    } catch (error) {
      console.error('查询全员禁言状态失败:', error);
      return false;
    }
  };

  // 查询RTC用户静音状态
  const checkRtcMuteStatus = (userId: string): boolean => {
    if (!aliRtcEngine.current) return false;
    
    try {
      const userInfo = aliRtcEngine.current.getUserInfo(userId);
      return userInfo ? userInfo.isMuteAudioPlaying : false;
    } catch (error) {
      console.error('查询RTC静音状态失败:', error);
      return false;
    }
  };

  // 批量查询RTC用户静音状态
  const checkRtcMuteStatusBatch = (userIds: string[]): Record<string, boolean> => {
    if (!aliRtcEngine.current) return {};
    
    const result: Record<string, boolean> = {};
    try {
      userIds.forEach(userId => {
        const userInfo = aliRtcEngine.current!.getUserInfo(userId);
        result[userId] = userInfo ? userInfo.isMuteAudioPlaying : false;
      });
      return result;
    } catch (error) {
      console.error('批量查询RTC静音状态失败:', error);
      return {};
    }
  };

  // 获取所有在线用户的RTC静音状态
  const getAllRtcMuteStatus = (): Record<string, boolean> => {
    if (!aliRtcEngine.current) return {};
    
    try {
      const onlineUsers = aliRtcEngine.current.getOnlineRemoteUsers();
      const result: Record<string, boolean> = {};
      
      onlineUsers.forEach(userId => {
        const userInfo = aliRtcEngine.current!.getUserInfo(userId);
        result[userId] = userInfo ? userInfo.isMuteAudioPlaying : false;
      });
      
      return result;
    } catch (error) {
      console.error('获取所有用户RTC静音状态失败:', error);
      return {};
    }
  };

  // 检查如果没有视频流则隐藏视频区域
  const hideVideoAreaIfNoStreams = () => {
    if (!aliRtcEngine.current) return;
    
    setShowVideo(false);
  };

  const answerHandUp = async (studentId: string): Promise<void> => {
    if (!imMessageManager.current || !classId || role !== Role.Teacher) return;
    
    try {
      // 先保存应答举手消息到数据库
      await saveMessageToDatabase({
        type: 'system',
        content: `老师已应答学生 ${getUserNameByIdSync(studentId)} 的举手`,
        sender: user?.nickname || user?.username || '老师',
        senderId: userId,
        timestamp: Date.now()
      });
      
      await imMessageManager.current.sendGroupMessage({
        groupId: classId,
        data: JSON.stringify({
          action: 'answer_hand_up',
          studentId
        }),
        type: 88893,
        level: HIGH,
      });
      showToast('info', `已应答学生 ${getUserNameByIdSync(studentId)} 的举手`);
    } catch (err: any) {
      setErrorMessage(`应答失败: ${err.message}`);
    }
  };

  const sendQuestion = async (question: string): Promise<void> => {
    if (!imMessageManager.current || !classId) return;
    
    try {
      // 先保存问题消息到数据库
      await saveMessageToDatabase({
        type: 'system',
        content: `问题: ${question}`,
        sender: user?.nickname || user?.username || `用户${getUserNameByIdSync(userId)}`,
        senderId: userId,
        timestamp: Date.now()
      });
      
      await imMessageManager.current.sendGroupMessage({
        groupId: classId,
        data: question,
        type: 88892,
        level: NORMAL,
      });
    } catch (err: any) {
      // 检查是否为禁言错误 (错误码442)
      if (err.message?.includes('code:442') || err.message?.includes('not allowed to send message')) {
        setErrorMessage('您已被禁言，无法发送问题');
      } else {
        setErrorMessage(`问题发送失败: ${err.message}`);
      }
    }
  };

  // 清理资源
  useEffect(() => {
    return () => {
      if (imGroupManager.current) {
        imGroupManager.current.removeAllListeners();
      }
      if (imMessageManager.current) {
        imMessageManager.current.removeAllListeners();
      }
      if (imEngine.current) {
        imEngine.current.removeAllListeners();
      }
      if (aliRtcEngine.current) {
        aliRtcEngine.current.destroy();
      }
    };
  }, []);

  return {
    // 状态
    userId,
    isCameraOn,
    isAudioOn,
    isScreenSharing,
    className,
    setClassName,
    role,
    setRole,
    classId,
    setClassId,
    isLoggedIn,
    isJoinedClass,
    msgText,
    setMsgText,
    messageList,
    errorMessage,
    classStatus,
    handUpList,
    questions,
    students,
    shareLink,
    isPrivateClass,
    remoteScreenContainer, // 重命名为remoteScreenContainer
    remoteCameraContainer, // 导出摄像头容器ref
    showCameraOverlay,
    setShowCameraOverlay,
    showVideo,
    setShowVideo,

    // 方法
    login,
    joinClass,
    leaveClass,
    sendMessage,
    startClass,
    endClass,
    toggleMuteMember,
    createClass,
    toggleCamera,
    toggleAudio,
    toggleScreenShare,
    handUp,
    answerHandUp,
    sendQuestion,
    muteStudent,
    kickStudent,
    muteStudentIM,
    unmuteStudentIM,
    muteAllIM,
    unmuteAllIM,
    checkMuteStatus,
    checkAllMuteStatus,
    checkRtcMuteStatus,
    checkRtcMuteStatusBatch,
    getAllRtcMuteStatus,
    sendImageMessageById,
    showToast,

    // 统计信息
    onlineCount,
    pvCount
  };
};

