class StudyRecord {
  constructor() {
    this.study_record = null;
    
    // 录音统计相关
    this.audioScores = {}; // 按key存储录音分数 {key: [score1, score2, ...]}
    
    // 视频时长统计
    this.totalVideoDuration = 0; // 总视频时长（秒）
    
    // 音频时长统计
    this.totalAudioDuration = 0; // 总音频时长（秒）
    
    // 做题对错统计
    this.totalQuestions = 0; // 总题数
    this.questionResults = {}; // 题目结果 {index: score} 默认-1表示未答
  }

  // ==================== 录音统计方法 ====================
  
  /**
   * 记录录音分数
   * @param {string} key - 录音标识
   * @param {number} score - 录音分数
   */
  recordAudioScore(key, score) {
    console.log('recordAudioScore: ', key, score);
    if (!this.audioScores[key]) {
      this.audioScores[key] = [];
    }
    this.audioScores[key].push(score);
  }

  /**
   * 获取指定key的平均分数
   * @param {string} key - 录音标识
   * @returns {number} 平均分数，如果没有记录返回0
   */
  getAverageAudioScore(key) {
    if (!this.audioScores[key] || this.audioScores[key].length === 0) {
      return 0;
    }
    const sum = this.audioScores[key].reduce((acc, score) => acc + score, 0);
    return sum / this.audioScores[key].length;
  }

  /**
   * 获取指定key的录音次数
   * @param {string} key - 录音标识
   * @returns {number} 录音次数
   */
  getAudioRecordCount(key) {
    return this.audioScores[key] ? this.audioScores[key].length : 0;
  }

  /**
   * 获取总录音次数
   * @returns {number} 总录音次数
   */
  getTotalAudioRecordCount() {
    let total = 0;
    for (const key in this.audioScores) {
      total += this.audioScores[key].length;
    }
    return total;
  }

  /**
   * 获取所有录音key
   * @returns {string[]} 所有录音key数组
   */
  getAllAudioKeys() {
    return Object.keys(this.audioScores);
  }

  /**
   * 计算多个key的总平均分
   * @param {string[]} keys - 要计算平均分的key数组，如果不传则计算所有key
   * @returns {number} 总平均分，如果没有记录返回0
   */
  getTotalAverageAudioScore(keys = null) {
    const targetKeys = keys || this.getAllAudioKeys();
    
    if (targetKeys.length === 0) {
      return 0;
    }
    
    let totalScore = 0;
    let totalCount = 0;
    
    for (const key of targetKeys) {
      if (this.audioScores[key] && this.audioScores[key].length > 0) {
        const keySum = this.audioScores[key].reduce((acc, score) => acc + score, 0);
        totalScore += keySum;
        totalCount += this.audioScores[key].length;
      }
    }
    
    return Math.round(totalCount > 0 ? totalScore / totalCount : 0);
  }

  /**
   * 获取所有key及其对应数据
   * @returns {Object} 包含所有key和对应数据的对象 {key: {score: averageScore, count: count}}
   */
  getAllAudioKeyData() {
    const result = {};
    
    for (const key in this.audioScores) {
      if (this.audioScores[key] && this.audioScores[key].length > 0) {
        result[key] = {
          'score': this.getAverageAudioScore(key),
          'count': this.getAudioRecordCount(key)
        };
      }
    }
    
    return result;
  }

  // ==================== 视频时长统计方法 ====================
  
  /**
   * 设置总视频时长
   * @param {number} duration - 视频时长（秒）
   */
  setTotalVideoDuration(duration) {
    this.totalVideoDuration = duration;
  }

  /**
   * 获取总视频时长
   * @returns {number} 总视频时长（秒）
   */
  getTotalVideoDuration() {
    return this.totalVideoDuration;
  }

  // ==================== 音频时长统计方法 ====================
  
  /**
   * 设置总音频时长
   * @param {number} duration - 音频时长（秒）
   */
  setTotalAudioDuration(duration) {
    this.totalAudioDuration = duration;
  }

  /**
   * 增加音频时长
   * @param {number} duration - 要增加的音频时长（秒）
   */
  addAudioDuration(duration) {
    this.totalAudioDuration += duration;
    console.log('totalAudioDuration: ', this.totalAudioDuration);
  }

  /**
   * 获取总音频时长
   * @returns {number} 总音频时长（秒）
   */
  getTotalAudioDuration() {
    return this.totalAudioDuration;
  }

  // ==================== 做题对错统计方法 ====================
  
  /**
   * 设置总题数
   * @param {number} total - 总题数
   */
  setTotalQuestions(total) {
    this.totalQuestions = total;
    // 初始化所有题目的默认分数为-1
    for (let i = 0; i < total; i++) {
      if (!(i in this.questionResults)) {
        this.questionResults[i] = -1;
      }
    }
  }

  /**
   * 设置某题的对错
   * @param {number} index - 题目索引
   * @param {number} score - 题目分数（1为正确，0为错误，-1为未答）
   */
  setQuestionResult(index, score) {
    if (index >= 0 && index < this.totalQuestions) {
      //只记录第一次的分数
      if (this.questionResults[index] === -1) {
        this.questionResults[index] = score;
      }
    }
  }

  /**
   * 获取某题的对错
   * @param {number} index - 题目索引
   * @returns {number} 题目分数
   */
  getQuestionResult(index) {
    return this.questionResults[index] !== undefined ? this.questionResults[index] : -1;
  }

  /**
   * 获取所有题的对错
   * @returns {Object} 所有题目结果 {index: score}
   */
  getAllQuestionResults() {
    return { ...this.questionResults };
  }

  /**
   * 获取已答题的题目数量
   * @returns {number} 已答题数量
   */
  getAnsweredQuestionCount() {
    let count = 0;
    for (const index in this.questionResults) {
      if (this.questionResults[index] !== -1) {
        count++;
      }
    }
    return count;
  }

  /**
   * 计算平均分
   * @returns {number} 平均分，如果没有答题返回0
   */
  getAverageScore() {
    const answeredCount = this.getAnsweredQuestionCount();
    if (answeredCount === 0) {
      return 0;
    }
    
    let totalScore = 0;
    for (const index in this.questionResults) {
      if (this.questionResults[index] !== -1) {
        totalScore += this.questionResults[index];
      }
    }
    // 四舍五入
    return Math.round(totalScore / answeredCount);
  }

  /**
   * 获取正确题目数量
   * @returns {number} 正确题目数量
   */
  getCorrectQuestionCount() {
    let count = 0;
    for (const index in this.questionResults) {
      if (this.questionResults[index] === 1) {
        count++;
      }
    }
    return count;
  }

  /**
   * 获取错误题目数量
   * @returns {number} 错误题目数量
   */
  getWrongQuestionCount() {
    let count = 0;
    for (const index in this.questionResults) {
      if (this.questionResults[index] === 0) {
        count++;
      }
    }
    return count;
  }

  /**
   * 获取未答题目数量
   * @returns {number} 未答题目数量
   */
  getUnansweredQuestionCount() {
    let count = 0;
    for (const index in this.questionResults) {
      if (this.questionResults[index] === -1) {
        count++;
      }
    }
    return count;
  }

  // ==================== 数据导出和导入方法 ====================
  
  /**
   * 导出所有统计数据
   * @returns {Object} 所有统计数据
   */
  exportData() {
    return {
      audioScores: this.audioScores,
      totalVideoDuration: this.totalVideoDuration,
      totalAudioDuration: this.totalAudioDuration,
      totalQuestions: this.totalQuestions,
      questionResults: this.questionResults
    };
  }

  /**
   * 导入统计数据
   * @param {Object} data - 统计数据
   */
  importData(data) {
    if (data.audioScores) this.audioScores = data.audioScores;
    if (data.totalVideoDuration !== undefined) this.totalVideoDuration = data.totalVideoDuration;
    if (data.totalAudioDuration !== undefined) this.totalAudioDuration = data.totalAudioDuration;
    if (data.totalQuestions !== undefined) this.totalQuestions = data.totalQuestions;
    if (data.questionResults) this.questionResults = data.questionResults;
  }

  /**
   * 重置所有统计数据
   */
  reset() {
    this.audioScores = {};
    this.totalVideoDuration = 0;
    this.totalAudioDuration = 0;
    this.totalQuestions = 0;
    this.questionResults = {};
  }

  // ==================== 数据上报方法 ====================
  reportData(studyRecordModel, score) {
    // 注意：这个方法需要在使用时传入正确的上下文
    // 因为 this.callNetworkApiPostNew 可能不存在于 StudyRecord 类中
    console.log('reportData called with:', studyRecordModel);
    
    // 如果需要网络请求，应该在调用方处理
    // 这里只处理数据准备
    const reportData = {
      audioScores: this.getAllAudioKeyData(),
      totalVideoDuration: this.getTotalVideoDuration(),
      totalAudioDuration: this.getTotalAudioDuration(),
      totalQuestions: this.totalQuestions,
      questionResults: this.getAllQuestionResults(),
      averageScore: this.getAverageScore(),
      totalScore: score
    };
    
    console.log('Prepared report data:', reportData);
    // return reportData;
    return {score: 100};
  }
}

export default StudyRecord;