/**
 * Copyright (c) 2025 TDCAT.CN
 */

import { hilog } from '@kit.PerformanceAnalysisKit';
import logManager, { LogCategory, LogEventType } from './logtext';
import settingsService from './SettingsService';
import { DatabaseService } from './DatabaseService';
import http from '@ohos.net.http';

// 课堂会话状态
export enum ClassSessionStatus {
  ACTIVE = 'active',
  ENDED = 'ended'
}

// 学生状态
export enum StudentStatus {
  ONLINE = 'online',
  OFFLINE = 'offline'
}

// 题目状态
export enum QuestionStatus {
  ACTIVE = 'active',
  ENDED = 'ended'
}

// 发送者角色
export enum SenderRole {
  TEACHER = 'teacher',
  STUDENT = 'student'
}

// 题目选项
export interface QuestionOption {
  index: number;
  content: string;
}

// 课堂模型
export class ClassSessionModel {
  sessionId: string = '';           // 课堂ID（由系统生成）
  className: string = '';           // 课堂名称
  classCode: string = '';           // 课堂暗号（由教师设置，学生使用此暗号加入）
  teacherAccount: string = '';      // 教师账号ID
  teacherName: string = '';         // 教师姓名
  startTime: Date = new Date();     // 课堂开始时间
  endTime?: Date;                   // 课堂结束时间（未结束为空）
  status: ClassSessionStatus = ClassSessionStatus.ACTIVE; // 课堂状态
  students: StudentSession[] = [];  // 参与学生列表
  questions: QuestionModel[] = [];  // 课堂题目列表
  messages: MessageModel[] = [];    // 课堂消息列表

  constructor(sessionId: string = '', 
              className: string = '', 
              classCode: string = '',
              teacherAccount: string = '',
              teacherName: string = '') {
    this.sessionId = sessionId || this.generateSessionId();
    this.className = className;
    this.classCode = classCode;
    this.teacherAccount = teacherAccount;
    this.teacherName = teacherName;
    this.startTime = new Date();
    this.status = ClassSessionStatus.ACTIVE;
  }

  // 生成唯一会话ID
  private generateSessionId(): string {
    return Date.now().toString(36) + Math.random().toString(36).substring(2);
  }
}

// 学生会话信息
export class StudentSession {
  studentAccount: string = '';      // 学生账号
  studentName: string = '';         // 学生姓名
  joinTime: Date = new Date();      // 加入时间
  status: StudentStatus = StudentStatus.ONLINE; // 学生状态

  constructor(studentAccount: string = '', studentName: string = '') {
    this.studentAccount = studentAccount;
    this.studentName = studentName;
    this.joinTime = new Date();
    this.status = StudentStatus.ONLINE;
  }
}

// 课堂消息模型
export class MessageModel {
  id: string = '';                   // 消息ID
  senderId: string = '';             // 发送者账号
  senderName: string = '';           // 发送者姓名
  senderRole: SenderRole;            // 发送者角色
  content: string = '';              // 消息内容
  timestamp: Date = new Date();      // 发送时间

  constructor(senderId: string = '', 
              senderName: string = '', 
              senderRole: SenderRole,
              content: string = '') {
    this.id = Date.now().toString(36) + Math.random().toString(36).substring(2);
    this.senderId = senderId;
    this.senderName = senderName;
    this.senderRole = senderRole;
    this.content = content;
    this.timestamp = new Date();
  }
}

// 题目模型
export class QuestionModel {
  questionId: string = '';           // 题目ID
  title: string = '';                // 题目标题
  options: QuestionOption[] = [];    // 题目选项
  correctOption: number = 0;         // 正确选项的索引
  startTime: Date = new Date();      // 题目开始时间
  endTime?: Date;                    // 题目结束时间（未结束为空）
  duration: number = 30;             // 答题时间(秒)
  status: QuestionStatus = QuestionStatus.ACTIVE; // 题目状态
  answers: QuestionAnswer[] = [];    // 学生答案列表
  classCode: string = '';            // 关联的课堂暗号

  constructor(title: string = '', 
              options: QuestionOption[] = [], 
              correctOption: number = 0,
              duration: number = 30,
              classCode: string = '') {
    this.questionId = Date.now().toString(36) + Math.random().toString(36).substring(2);
    this.title = title;
    this.options = options;
    this.correctOption = correctOption;
    this.duration = duration;
    this.startTime = new Date();
    this.status = QuestionStatus.ACTIVE;
    this.classCode = classCode;
  }
}

// 学生答案
export class QuestionAnswer {
  studentAccount: string = '';        // 学生账号
  studentName: string = '';           // 学生姓名
  selectedOption: number = 0;         // 所选选项索引
  timestamp: Date = new Date();       // 提交时间
  isCorrect: boolean = false;         // 是否正确

  constructor(studentAccount: string = '', 
              studentName: string = '', 
              selectedOption: number = 0,
              correctOption: number = 0) {
    this.studentAccount = studentAccount;
    this.studentName = studentName;
    this.selectedOption = selectedOption;
    this.timestamp = new Date();
    this.isCorrect = selectedOption === correctOption;
  }
}

// 事件类型
export enum WebSocketEventType {
  JOIN_CLASS = 'joinClass',
  LEAVE_CLASS = 'leaveClass',
  SEND_MESSAGE = 'sendMessage',
  PUBLISH_QUESTION = 'publishQuestion',
  SUBMIT_ANSWER = 'submitAnswer',
  END_QUESTION = 'endQuestion',
  END_CLASS = 'endClass'
}

// API响应接口定义
export interface ChannelApiResponse {
  success: boolean;
  message?: string;
  data?: ClassSessionModel | QuestionModel | MessageModel | QuestionAnswer | Array<MessageModel> | Array<QuestionModel> | boolean | null;
}

// HTTP请求选项接口
export interface HttpRequestOptions {
  method: number;  // http.RequestMethod enum value
  header?: object;
  extraData?: string;
  connectTimeout?: number; 
  readTimeout?: number;
}

// HTTP响应接口
export interface HttpResponseResult {
  responseCode: number;
  result?: string | object | ArrayBuffer;
}

// 事件数据接口
export interface EventConnection {
  status: string;
}

export interface QuestionAnswerEvent {
  questionId: string;
  answer: QuestionAnswer;
}

// 请求数据类型接口
export interface CreateSessionRequest {
  className: string;
  classCode: string;
  teacherAccount: string;
  teacherName: string;
}

export interface JoinSessionRequest {
  classCode: string; 
  studentAccount: string;
  studentName: string;
}

export interface SendMessageRequest {
  classCode: string;
  message: MessageModel;
}

export interface SubmitAnswerRequest {
  questionId: string;
  classCode: string;
  answer: QuestionAnswer;
}

export interface EndQuestionRequest {
  questionId: string;
  classCode: string;
}

export interface EndSessionRequest {
  classCode: string;
}

// API配置接口
export interface ApiConfig {
  baseUrl: string;
  pollInterval: number;
  timeout: number;
}

// 事件数据联合类型
export type EventData = ClassSessionModel | QuestionModel | MessageModel | QuestionAnswer | EventConnection | QuestionAnswerEvent | null;

// 事件回调类型
export type EventCallback = (data: EventData) => void;

// API配置
const CHANNEL_API_CONFIG: ApiConfig = {
  baseUrl: 'http://139.155.155.67:5243', // 使用这个确认工作的地址
  pollInterval: 1000,
  timeout: 10000
};

// 定义日志频道ID和TAG常量
const TIAN_CHANNEL_DOMAIN_ID = 0x00201;  // 自定义域ID
const TIAN_CHANNEL_TAG = 'tianChannel';  // 自定义TAG用于筛选日志

// 课堂通信服务
export class ClassRoomService {
  private static instance: ClassRoomService;
  private dbService: DatabaseService = DatabaseService.getInstance();
  
  // 当前课堂会话
  private currentSession: ClassSessionModel | null = null;
  private currentClassCode: string = '';
  
  // 回调函数集合
  private eventCallbacks: Map<string, Array<EventCallback>> = new Map();
  
  // 是否已连接
  private connected: boolean = false;
  
  // 是否为教师
  private isTeacher: boolean = false;
  
  // 消息轮询定时器ID
  private pollTimerId: number = -1;
  
  // 最后接收的消息ID
  private lastMessageId: string = '';
  
  // 最后接收的题目ID
  private lastQuestionId: string = '';
  
  private constructor() {
    // 初始化
    hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, 'ClassRoom Service Initialized');
  }
  
  public static getInstance(): ClassRoomService {
    if (!ClassRoomService.instance) {
      ClassRoomService.instance = new ClassRoomService();
    }
    return ClassRoomService.instance;
  }
  
  // 创建HTTP请求客户端
  private createHttpClient(): http.HttpRequest {
    let httpRequest = http.createHttp();
    return httpRequest;
  }
  
  // 发起HTTP POST请求
  private async postRequest(endpoint: string, data: object): Promise<ChannelApiResponse> {
    hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `开始POST请求: ${endpoint}`);
    try {
      hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `创建HTTP客户端`);
      const httpRequest = this.createHttpClient();
      
      // 记录请求数据摘要
      let dataStr = "";
      try {
        dataStr = JSON.stringify(data).substring(0, 100) + (JSON.stringify(data).length > 100 ? '...' : '');
      } catch (e) {
        dataStr = "无法序列化数据";
      }
      hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `请求数据(摘要): ${dataStr}`);
      
      hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `发送请求到: ${CHANNEL_API_CONFIG.baseUrl}/${endpoint}`);
      const response = await httpRequest.request(
        `${CHANNEL_API_CONFIG.baseUrl}/${endpoint}`,
        {
          method: http.RequestMethod.POST,
          header: {
            'Content-Type': 'application/json'
          },
          extraData: JSON.stringify(data),
          connectTimeout: CHANNEL_API_CONFIG.timeout,
          readTimeout: CHANNEL_API_CONFIG.timeout
        }
      );
      
      hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `请求完成，销毁HTTP客户端`);
      httpRequest.destroy();
      
      hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `响应状态码: ${response.responseCode}`);
      
      if (response.responseCode === 200) {
        try {
          hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `开始解析响应JSON`);
          const jsonString: string = response.result ? response.result.toString() : '{}';
          const responseData = JSON.parse(jsonString) as ChannelApiResponse;
          hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `解析成功，响应success: ${responseData.success}`);
          return responseData;
        } catch (parseError) {
          hilog.error(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `解析响应JSON失败: ${parseError}`);
          logManager.error(LogCategory.NETWORK, `Error parsing response: ${parseError}`);
          const errorResponse: ChannelApiResponse = {
            success: false,
            message: `Parse error: ${parseError}`
          };
          return errorResponse;
        }
      }
      
      hilog.warn(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `HTTP错误状态码: ${response.responseCode}`);
      const errorResponse: ChannelApiResponse = {
        success: false,
        message: `HTTP error: ${response.responseCode}`
      };
      return errorResponse;
    } catch (error) {
      // 详细记录网络错误
      const errorMsg = error instanceof Error ? error.message : String(error);
      const errorStack = error instanceof Error ? error.stack : 'No stack trace';
      
      hilog.error(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `网络请求错误: ${errorMsg}`);
      hilog.error(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `错误堆栈: ${errorStack}`);
      
      logManager.error(LogCategory.NETWORK, `Network request error: ${error}`);
      const errorResponse: ChannelApiResponse = {
        success: false,
        message: `Request error: ${error}`
      };
      return errorResponse;
    }
  }
  
  // 发起HTTP GET请求
  private async getRequest(endpoint: string): Promise<ChannelApiResponse> {
    try {
      const httpRequest = this.createHttpClient();
      
      const response = await httpRequest.request(
        `${CHANNEL_API_CONFIG.baseUrl}/${endpoint}`,
        {
          method: http.RequestMethod.GET,
          connectTimeout: CHANNEL_API_CONFIG.timeout,
          readTimeout: CHANNEL_API_CONFIG.timeout
        }
      );
      
      httpRequest.destroy();
      
      if (response.responseCode === 200) {
        const jsonString: string = response.result ? response.result.toString() : '{}';
        try {
          const responseData = JSON.parse(jsonString) as ChannelApiResponse;
          return responseData;
        } catch (parseError) {
          logManager.error(LogCategory.NETWORK, `Error parsing response: ${parseError}`);
          const errorResponse: ChannelApiResponse = {
            success: false,
            message: `Parse error: ${parseError}`
          };
          return errorResponse;
        }
      }
      
      const errorResponse: ChannelApiResponse = {
        success: false,
        message: `HTTP error: ${response.responseCode}`
      };
      return errorResponse;
    } catch (error) {
      logManager.error(LogCategory.NETWORK, `Network request error: ${error}`);
      const errorResponse: ChannelApiResponse = {
        success: false,
        message: `Request error: ${error}`
      };
      return errorResponse;
    }
  }
  
  // 检查当前用户是否为教师
  public checkIsTeacher(): boolean {
    const currentAccount = settingsService.getCurrentAccount();
    hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `检查用户 ${currentAccount} 是否为教师`);
    
    const category = this.dbService.getUserCategory(currentAccount);
    hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `用户类别: ${category}`);
    
    // 首先通过数据库类别判断
    if (category === 'teacher') {
      this.isTeacher = true;
    } else if (category === 'student') {
      this.isTeacher = false;
    } else {
      // 如果类别不明确，通过账号判断（备用）
      hilog.warn(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `用户类别不明确，尝试通过账号号码判断`);
      this.isTeacher = currentAccount.includes('0');
      hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `通过账号判断用户身份为${this.isTeacher ? '教师' : '学生'}`);
    }
    
    logManager.info(LogCategory.USER, LogEventType.SYSTEM_INFO, 
      `用户 ${currentAccount} 的角色为: ${this.isTeacher ? '教师' : '学生'}`);
    return this.isTeacher;
  }
  
  // 启动消息轮询
  private startPolling(): void {
    if (this.pollTimerId !== -1) {
      clearInterval(this.pollTimerId);
    }
    
    this.pollTimerId = setInterval(() => {
      this.pollForUpdates();
    }, CHANNEL_API_CONFIG.pollInterval);
  }
  
  // 停止消息轮询
  private stopPolling(): void {
    if (this.pollTimerId !== -1) {
      clearInterval(this.pollTimerId);
      this.pollTimerId = -1;
    }
  }
  
  // 轮询更新
  private async pollForUpdates(): Promise<void> {
    if (!this.connected || !this.currentClassCode) {
      return;
    }
    
    try {
      // 查询新消息
      const messagesResponse = await this.getRequest(`messages/${this.currentClassCode}?since=${this.lastMessageId}`);
      
      if (messagesResponse.success && messagesResponse.data && Array.isArray(messagesResponse.data)) {
        const messages = messagesResponse.data as MessageModel[];
        
        if (messages.length > 0) {
          // 更新最后接收的消息ID
          this.lastMessageId = messages[messages.length - 1].id;
          
          // 将消息添加到当前会话
          if (this.currentSession) {
            messages.forEach(message => {
              // 避免添加自己发送的消息（通过发送者ID比较而不是消息ID）
              if (message.senderId !== settingsService.getCurrentAccount()) {
                // 检查消息是否已存在（防止重复）
                const isDuplicate = this.currentSession?.messages.some(m => m.id === message.id);
                if (!isDuplicate) {
                  // 添加到消息列表
                  this.currentSession?.messages.push(message);
                  // 确保消息被添加后立即通知UI
                  this.notifyEvent(WebSocketEventType.SEND_MESSAGE, message);
                  
                  // 记录接收到的新消息（来自他人）
                  logManager.info(LogCategory.CLASS, LogEventType.SYSTEM_INFO, 
                    `收到新消息 - ID: ${message.id}, 发送者: ${message.senderName}, 内容: ${message.content}`);
                }
              }
            });
          }
        }
      }
      
      // 查询新题目
      const questionsResponse = await this.getRequest(`questions/${this.currentClassCode}?since=${this.lastQuestionId}`);
      
      if (questionsResponse.success && questionsResponse.data && Array.isArray(questionsResponse.data)) {
        const questions = questionsResponse.data as QuestionModel[];
        
        if (questions.length > 0) {
          // 更新最后接收的题目ID
          this.lastQuestionId = questions[questions.length - 1].questionId;
          
          // 处理题目
          questions.forEach(question => {
            if (this.currentSession) {
              // 检查题目是否已存在
              const existingQuestionIndex = this.currentSession.questions.findIndex(q => q.questionId === question.questionId);
              
              if (existingQuestionIndex === -1) {
                // 新题目
                this.currentSession.questions.push(question);
                this.notifyEvent(WebSocketEventType.PUBLISH_QUESTION, question);
                
                // 如果题目处于活动状态且有结束时间，设置倒计时
                if (question.status === QuestionStatus.ACTIVE && question.duration > 0) {
                  setTimeout(() => {
                    this.checkQuestionStatus(question.questionId);
                  }, question.duration * 1000);
                }
              } else {
                // 更新已有题目
                const oldQuestion = this.currentSession.questions[existingQuestionIndex];
                const oldStatus = oldQuestion.status;
                
                // 更新题目
                this.currentSession.questions[existingQuestionIndex] = question;
                
                // 如果状态从活动变为结束，通知题目结束
                if (oldStatus === QuestionStatus.ACTIVE && question.status === QuestionStatus.ENDED) {
                  this.notifyEvent(WebSocketEventType.END_QUESTION, question);
                }
              }
            }
          });
        }
      }
      
      // 查询课堂状态
      const sessionResponse = await this.getRequest(`session/${this.currentClassCode}`);
      
      if (sessionResponse.success && sessionResponse.data) {
        const session = sessionResponse.data as ClassSessionModel;
        
        // 检查课堂是否已结束
        if (session.status === ClassSessionStatus.ENDED && this.currentSession?.status === ClassSessionStatus.ACTIVE) {
          // 更新当前会话状态
          if (this.currentSession) {
            this.currentSession.status = ClassSessionStatus.ENDED;
            this.currentSession.endTime = session.endTime ? new Date(session.endTime) : new Date();
          }
          
          // 通知课堂结束
          this.notifyEvent(WebSocketEventType.END_CLASS, session);
          
          // 如果不是教师，停止轮询
          if (!this.isTeacher) {
            this.disconnect();
          }
        }
      }
    } catch (error) {
      logManager.error(LogCategory.NETWORK, `Polling error: ${error}`);
    }
  }
  
  // 检查题目状态
  private async checkQuestionStatus(questionId: string): Promise<void> {
    try {
      const response = await this.getRequest(`question/${questionId}`);
      
      if (response.success && response.data) {
        const question = response.data as QuestionModel;
        
        // 如果题目仍处于活动状态，结束题目
        if (question.status === QuestionStatus.ACTIVE && this.currentSession) {
          // 查找并更新本地题目
          const questionIndex = this.currentSession.questions.findIndex(q => q.questionId === questionId);
          
          if (questionIndex !== -1) {
            // 更新题目状态
            this.currentSession.questions[questionIndex].status = QuestionStatus.ENDED;
            this.currentSession.questions[questionIndex].endTime = new Date();
            
            // 提交题目状态更新
            const request: EndQuestionRequest = {
              questionId: questionId,
              classCode: this.currentClassCode
            };
            
            await this.postRequest('endQuestion', request);
            
            // 通知题目结束
            this.notifyEvent(WebSocketEventType.END_QUESTION, this.currentSession.questions[questionIndex]);
          }
        }
      }
    } catch (error) {
      logManager.error(LogCategory.CLASS, `Error checking question status: ${error}`);
    }
  }
  
  // 连接服务
  public async connect(): Promise<boolean> {
    if (this.connected) return true;
    
    try {
      // 验证服务器连接
      const response = await this.getRequest('ping');
      
      if (response.success) {
        this.connected = true;
        const connectionEvent: EventConnection = { status: 'connected' };
        this.notifyEvent('connection', connectionEvent);
        logManager.info(LogCategory.NETWORK, LogEventType.SYSTEM_INFO, 'Channel service connected');
        return true;
      } else {
        logManager.error(LogCategory.NETWORK, `Connection failed: ${response.message}`);
        return false;
      }
    } catch (error) {
      logManager.error(LogCategory.NETWORK, `Connection error: ${error}`);
      return false;
    }
  }
  
  // 断开连接
  public disconnect(): void {
    if (!this.connected) return;
    
    // 停止轮询
    this.stopPolling();
    
    this.connected = false;
    this.notifyEvent('connection', { status: 'disconnected' });
    logManager.info(LogCategory.NETWORK, LogEventType.SYSTEM_INFO, 'Channel service disconnected');
    
    // 清空当前会话
    this.currentSession = null;
    this.currentClassCode = '';
  }
  
  // 创建新课堂（教师）
  public async createClassSession(className: string, classCode: string): Promise<ClassSessionModel | null> {
    try {
      // 发送创建请求
      const reqData: CreateSessionRequest = {
        className: className,
        classCode: classCode,
        teacherAccount: settingsService.getCurrentAccount(),
        teacherName: settingsService.getUserNickname()
      };
      
      const response = await this.postRequest('createSession', reqData);
      
      if (response.success && response.data) {
        // 设置当前会话
        this.currentSession = response.data as ClassSessionModel;
        this.currentClassCode = classCode;
        this.isTeacher = true;
        this.connected = true;
        
        // 开始消息轮询
        this.startPolling();
        
        // 通知连接状态
        const connectionEvent: EventConnection = { status: 'connected' };
        this.notifyEvent(WebSocketEventType.JOIN_CLASS, connectionEvent);
        
        return this.currentSession;
      } else {
        logManager.error(LogCategory.CLASS, `Create session failed: ${response.message}`);
        return null;
      }
    } catch (error) {
      logManager.error(LogCategory.CLASS, `Create session error: ${error}`);
      return null;
    }
  }
  
  // 加入课堂（学生）
  public async joinClassSession(classCode: string): Promise<boolean> {
    try {
      // 发送加入请求
      const reqData: JoinSessionRequest = {
        classCode: classCode,
        studentAccount: settingsService.getCurrentAccount(),
        studentName: settingsService.getUserNickname()
      };
      
      const response = await this.postRequest('joinSession', reqData);
      
      if (response.success && response.data) {
        // 设置当前会话
        this.currentSession = response.data as ClassSessionModel;
        this.currentClassCode = classCode;
        this.isTeacher = false;
        this.connected = true;
        
        // 开始消息轮询
        this.startPolling();
        
        // 通知连接状态
        const connectionEvent: EventConnection = { status: 'connected' };
        this.notifyEvent(WebSocketEventType.JOIN_CLASS, connectionEvent);
        
        return true;
      } else {
        logManager.error(LogCategory.CLASS, `Join session failed: ${response.message}`);
        return false;
      }
    } catch (error) {
      logManager.error(LogCategory.CLASS, `Join session error: ${error}`);
      return false;
    }
  }
  
  // 发送消息
  public async sendMessage(content: string): Promise<boolean> {
    hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `========= 开始发送消息 =========`);
    
    // 检查前提条件
    if (!this.currentSession) {
      hilog.error(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `发送失败: currentSession为空`);
      return false;
    }
    if (!this.connected) {
      hilog.error(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `发送失败: 未连接`);
      return false;
    }
    if (!this.currentClassCode) {
      hilog.error(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `发送失败: currentClassCode为空`);
      return false;
    }
    
    if (!this.currentSession || !this.connected || !this.currentClassCode) {
      logManager.error(LogCategory.CLASS, `Cannot send message: No active session or not connected`);
      return false;
    }
    
    // Debug message: Log session and connection information
    hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `会话ID: ${this.currentSession.sessionId}`);
    hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `课堂码: ${this.currentClassCode}`);
    hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `连接状态: ${this.connected}`);
    
    logManager.info(LogCategory.CLASS, LogEventType.SYSTEM_INFO, `[DEBUG] Message sending attempt - Session ID: ${this.currentSession.sessionId}, Class Code: ${this.currentClassCode}, Connection status: ${this.connected}`);
    
    // 获取用户信息
    hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `获取用户信息`);
    const currentAccount = settingsService.getCurrentAccount();
    const senderName = this.dbService.getUserNickname(currentAccount) || currentAccount;
    const role = this.isTeacher ? SenderRole.TEACHER : SenderRole.STUDENT;
    
    hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `用户账号: ${currentAccount}`);
    hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `用户名称: ${senderName}`);
    hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `用户角色: ${role}`);
    
    // Debug message: Log user information
    logManager.info(LogCategory.CLASS, LogEventType.SYSTEM_INFO, `[DEBUG] Message sender info - Account: ${currentAccount}, Name: ${senderName}, Role: ${role}`);
    
    // 创建消息对象
    hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `创建消息对象`);
    try {
      // 单独记录消息创建过程
      hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `消息内容: ${content}`);
      
      const message = new MessageModel(currentAccount, senderName, role, content);
      
      hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `消息创建成功，ID: ${message.id}`);
      hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `消息时间戳: ${message.timestamp.toISOString()}`);
      
      logManager.info(LogCategory.CLASS, LogEventType.SYSTEM_INFO, `Creating message: ID=${message.id}, Content=${content}, Sender=${senderName}, Role=${role}`);
      
      // 构建请求
      hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `构建发送请求`);
      const request: SendMessageRequest = {
        classCode: this.currentClassCode,
        message: message
      };
      
      // 打印请求对象，但避免过长内容
      let requestStr = "";
      try {
        requestStr = JSON.stringify(request).substring(0, 200) + (JSON.stringify(request).length > 200 ? '...' : '');
        hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `请求对象(摘要): ${requestStr}`);
      } catch (e) {
        hilog.error(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `无法序列化请求: ${e}`);
      }
      
      logManager.info(LogCategory.CLASS, LogEventType.SYSTEM_INFO, `发送消息请求: classCode=${this.currentClassCode}, messageId=${message.id}`);
      
      // 发送请求
      hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `开始发送POST请求到sendMessage`);
      const response = await this.postRequest('sendMessage', request);
      hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `请求完成，响应success: ${response.success}`);
      
      // 详细记录响应
      if (response.message) {
        hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `响应消息: ${response.message}`);
      }
      if (response.data) {
        try {
          const dataStr = JSON.stringify(response.data).substring(0, 100) + 
                         (JSON.stringify(response.data).length > 100 ? '...' : '');
          hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `响应数据(摘要): ${dataStr}`);
        } catch (e) {
          hilog.error(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `无法序列化响应数据: ${e}`);
        }
      }
      
      logManager.info(LogCategory.CLASS, LogEventType.SYSTEM_INFO, `服务器响应: success=${response.success}, message=${response.message || "无"}`);
      
      if (response.success) {
        hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `消息发送成功，更新lastMessageId: ${message.id}`);
        // 不再将消息添加到currentSession，因为UI层已经添加了本地消息
        // (已删除): this.currentSession.messages.push(message); 
        
        // 不需要再次通知UI，因为UI层已经添加了本地消息
        // (已删除): this.notifyEvent(WebSocketEventType.SEND_MESSAGE, message);
        
        // 只添加到lastMessageId，确保轮询时不重复获取
        this.lastMessageId = message.id;
        
        logManager.info(LogCategory.CLASS, LogEventType.SYSTEM_INFO, `Message sent successfully: ${message.id}`);
        hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `========= 消息发送成功 =========`);
        
        return true;
      } else {
        // Enhanced error logging with response details
        hilog.error(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `消息发送失败: ${response.message || '未知错误'}`);
        logManager.error(LogCategory.CLASS, `Send message failed: ${response.message || 'Unknown error'}, Response data: ${JSON.stringify(response.data || {})}`);
        hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `========= 消息发送失败 =========`);
        return false;
      }
    } catch (error) {
      // 增强错误处理，确保不会崩溃
      const errorMessage = error instanceof Error ? error.message : String(error);
      const errorStack = error instanceof Error ? error.stack : 'No stack trace';
      
      hilog.error(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `发送消息异常: ${errorMessage}`);
      hilog.error(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `错误堆栈: ${errorStack}`);
      
      logManager.error(LogCategory.CLASS, `发送消息严重错误: ${errorMessage}`);
      logManager.error(LogCategory.CLASS, `错误详情: ${errorStack}`);
      
      hilog.info(TIAN_CHANNEL_DOMAIN_ID, TIAN_CHANNEL_TAG, `========= 消息发送异常 =========`);
      
      // 确保返回false而不是崩溃
      return false;
    }
  }
  
  // 发布题目（教师）
  public async publishQuestion(title: string, options: QuestionOption[], correctOption: number, duration: number): Promise<QuestionModel | null> {
    if (!this.isTeacher || !this.currentSession || !this.connected || !this.currentClassCode) {
      logManager.error(LogCategory.CLASS, 'Cannot publish question: Not a teacher, no active session or not connected');
      return null;
    }
    
    // 创建题目
    const question = new QuestionModel(title, options, correctOption, duration, this.currentClassCode);
    
    try {
      // 发送发布题目请求
      const response = await this.postRequest('publishQuestion', question);
      
      if (response.success && response.data) {
        // 使用服务器返回的题目
        const publishedQuestion = response.data as QuestionModel;
        
        // 添加到当前会话
        this.currentSession.questions.push(publishedQuestion);
        
        // 设置题目结束倒计时
        setTimeout(() => {
          this.checkQuestionStatus(publishedQuestion.questionId);
        }, duration * 1000);
        
        // 通知题目发布
        this.notifyEvent(WebSocketEventType.PUBLISH_QUESTION, publishedQuestion);
        
        return publishedQuestion;
      } else {
        logManager.error(LogCategory.CLASS, `Publish question failed: ${response.message}`);
        return null;
      }
    } catch (error) {
      logManager.error(LogCategory.CLASS, `Publish question error: ${error}`);
      return null;
    }
  }
  
  // 提交答案（学生）
  public async submitAnswer(questionId: string, selectedOption: number): Promise<boolean> {
    if (this.isTeacher || !this.currentSession || !this.connected || !this.currentClassCode) {
      logManager.error(LogCategory.CLASS, 'Cannot submit answer: Is a teacher, no active session or not connected');
      return false;
    }
    
    // 查找题目
    const question = this.currentSession.questions.find(q => q.questionId === questionId);
    if (!question || question.status === QuestionStatus.ENDED) {
      logManager.error(LogCategory.CLASS, 'Cannot submit answer: Question not found or already ended');
      return false;
    }
    
    const currentAccount = settingsService.getCurrentAccount();
    const studentName = this.dbService.getUserNickname(currentAccount) || currentAccount;
    
    // 创建答案
    const answer = new QuestionAnswer(
      currentAccount,
      studentName,
      selectedOption,
      question.correctOption
    );
    
    try {
      // 发送提交答案请求
      const request: SubmitAnswerRequest = {
        questionId: questionId,
        classCode: this.currentClassCode,
        answer: answer
      };
      
      const response = await this.postRequest('submitAnswer', request);
      
      if (response.success) {
        // 检查是否已答题
        const existingAnswerIndex = question.answers.findIndex(a => a.studentAccount === currentAccount);
        if (existingAnswerIndex !== -1) {
          // 更新已有答案
          question.answers[existingAnswerIndex] = answer;
        } else {
          // 添加新答案
          question.answers.push(answer);
        }
        
        // 通知答案提交
        const answerEvent: QuestionAnswerEvent = {
          questionId: questionId,
          answer: answer
        };
        
        this.notifyEvent(WebSocketEventType.SUBMIT_ANSWER, answerEvent);
        
        return true;
      } else {
        logManager.error(LogCategory.CLASS, `Submit answer failed: ${response.message}`);
        return false;
      }
    } catch (error) {
      logManager.error(LogCategory.CLASS, `Submit answer error: ${error}`);
      return false;
    }
  }
  
  // 结束课堂（教师）
  public async endClassSession(): Promise<boolean> {
    if (!this.isTeacher || !this.currentSession || !this.connected || !this.currentClassCode) {
      logManager.error(LogCategory.CLASS, 'Cannot end class: Not a teacher, no active session or not connected');
      return false;
    }
    
    try {
      // 发送结束课堂请求
      const request: EndSessionRequest = {
        classCode: this.currentClassCode
      };
      
      const response = await this.postRequest('endSession', request);
      
      if (response.success) {
        // 更新课堂状态
        this.currentSession.status = ClassSessionStatus.ENDED;
        this.currentSession.endTime = new Date();
        
        // 通知课堂结束
        this.notifyEvent(WebSocketEventType.END_CLASS, this.currentSession);
        
        // 停止轮询
        this.stopPolling();
        
        // 清空当前会话
        const endedSession = this.currentSession;
        this.currentSession = null;
        this.currentClassCode = '';
        
        return true;
      } else {
        logManager.error(LogCategory.CLASS, `End class failed: ${response.message}`);
        return false;
      }
    } catch (error) {
      logManager.error(LogCategory.CLASS, `End class error: ${error}`);
      return false;
    }
  }
  
  // 获取当前课堂
  public getCurrentSession(): ClassSessionModel | null {
    return this.currentSession;
  }
  
  // 获取当前题目（如果有）
  public getCurrentQuestion(): QuestionModel | null {
    if (!this.currentSession) return null;
    
    // 查找最新的活动题目
    const activeQuestions = this.currentSession.questions.filter(q => q.status === QuestionStatus.ACTIVE);
    if (activeQuestions.length === 0) return null;
    
    // 返回最新发布的题目
    return activeQuestions[activeQuestions.length - 1];
  }
  
  // 注册事件回调
  public addEventListener(event: string, callback: EventCallback): void {
    if (!this.eventCallbacks.has(event)) {
      this.eventCallbacks.set(event, []);
    }
    
    const callbacks = this.eventCallbacks.get(event);
    if (callbacks) {
      callbacks.push(callback);
    }
  }
  
  // 移除事件回调
  public removeEventListener(event: string, callback: EventCallback): void {
    if (!this.eventCallbacks.has(event)) return;
    
    const callbacks = this.eventCallbacks.get(event);
    if (callbacks) {
      const index = callbacks.indexOf(callback);
      if (index !== -1) {
        callbacks.splice(index, 1);
      }
    }
  }
  
  // 通知事件
  private notifyEvent(event: string, data: EventData): void {
    if (!this.eventCallbacks.has(event)) return;
    
    const callbacks = this.eventCallbacks.get(event);
    if (callbacks) {
      callbacks.forEach(callback => {
        try {
          callback(data);
        } catch (error) {
          logManager.error(LogCategory.ERROR, `Error in event callback: ${error}`);
        }
      });
    }
  }
  
  // 获取连接状态
  public isConnected(): boolean {
    return this.connected;
  }
  
  // 重新连接方法
  public async reconnect(): Promise<boolean> {
    // 先断开连接
    this.stopPolling();
    
    // 记录重连尝试
    logManager.info(LogCategory.NETWORK, LogEventType.SYSTEM_INFO, 
                    `尝试重新连接 - 当前状态: ${this.connected}, 课堂码: ${this.currentClassCode}`);
    
    // 保存当前课堂码
    const classCode = this.currentClassCode;
    
    if (!classCode) {
      logManager.error(LogCategory.NETWORK, `重连失败: 无课堂码`);
      return false;
    }
    
    // 重置连接状态
    this.connected = false;
    
    // 尝试重新连接
    try {
      // 验证服务器连接
      const response = await this.getRequest('ping');
      
      if (response.success) {
        this.connected = true;
        
        // 重新获取课堂数据
        const sessionResponse = await this.getRequest(`session/${classCode}`);
        if (sessionResponse.success && sessionResponse.data) {
          this.currentSession = sessionResponse.data as ClassSessionModel;
          this.currentClassCode = classCode;
          
          // 重新开始轮询
          this.startPolling();
          
          const connectionEvent: EventConnection = { status: 'reconnected' };
          this.notifyEvent('connection', connectionEvent);
          
          logManager.info(LogCategory.NETWORK, LogEventType.SYSTEM_INFO, '课堂服务重连成功');
          return true;
        } else {
          logManager.error(LogCategory.NETWORK, `重新获取课堂数据失败: ${sessionResponse.message}`);
          return false;
        }
      } else {
        logManager.error(LogCategory.NETWORK, `重连失败: ${response.message}`);
        return false;
      }
    } catch (error) {
      logManager.error(LogCategory.NETWORK, `重连出错: ${error}`);
      return false;
    }
  }
}

// 导出单例实例
export default ClassRoomService.getInstance(); 