// 答题数据本地存储工具
const EXAM_STORAGE_KEY = 'exam_answers_data'

const examStorage = {
  // 保存答题数据
  saveAnswer: function(examType, questionId, value) {
    try {
      let examData = uni.getStorageSync(EXAM_STORAGE_KEY) || {}
      
      // 确保examType存在
      if (!examData[examType]) {
        examData[examType] = {}
      }
      
      // 保存答案
      examData[examType][questionId] = {
        value: value,
        timestamp: Date.now()
      }
      
      uni.setStorageSync(EXAM_STORAGE_KEY, examData)
    } catch (error) {
      console.error('保存答题数据失败:', error)
    }
  },
  
  // 获取答题数据
  getAnswer: function(examType, questionId) {
    try {
      let examData = uni.getStorageSync(EXAM_STORAGE_KEY) || {}
      
      if (examData[examType] && examData[examType][questionId]) {
        return examData[examType][questionId].value
      }
      
      return null
    } catch (error) {
      console.error('获取答题数据失败:', error)
      return null
    }
  },
  
  // 获取某个考试类型的所有答题数据
  getAllAnswers: function(examType) {
    try {
      let examData = uni.getStorageSync(EXAM_STORAGE_KEY) || {}
      return examData[examType] || {}
    } catch (error) {
      console.error('获取所有答题数据失败:', error)
      return {}
    }
  },
  
  // 清除某个考试类型的答题数据
  clearExamAnswers: function(examType) {
    try {
      let examData = uni.getStorageSync(EXAM_STORAGE_KEY) || {}
      
      if (examData[examType]) {
        delete examData[examType]
        uni.setStorageSync(EXAM_STORAGE_KEY, examData)
      }
    } catch (error) {
      console.error('清除答题数据失败:', error)
    }
  },
  
  // 清除所有答题数据
  clearAllAnswers: function() {
    try {
      uni.removeStorageSync(EXAM_STORAGE_KEY)
    } catch (error) {
      console.error('清除所有答题数据失败:', error)
    }
  },
  
  // 检查答题数据是否过期（可选功能，比如24小时后过期）
  isAnswerExpired: function(examType, questionId, expireHours = 24) {
    try {
      let examData = uni.getStorageSync(EXAM_STORAGE_KEY) || {}
      
      if (examData[examType] && examData[examType][questionId]) {
        const timestamp = examData[examType][questionId].timestamp
        const now = Date.now()
        const expireTime = expireHours * 60 * 60 * 1000 // 转换为毫秒
        
        return (now - timestamp) > expireTime
      }
      
      return true // 没有数据视为过期
    } catch (error) {
      console.error('检查答题数据过期失败:', error)
      return true
    }
  }
}

export default examStorage