<template>
  <div class="exam-page">
    <!-- 考试中心标题 -->
    <div class="exam-center-header">
      <div class="container">
        <h1 class="center-title">考试中心</h1>
        <p class="center-subtitle">诚信考试规范，考试过程规范，严格监考规范</p>
      </div>
    </div>

    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <div class="container">
        <span class="breadcrumb-text">
          当前考试：{{ courseName }} > {{ examName }}
        </span>
        <div class="exam-status">
          <span class="status-item">总题数：{{ questions.length }}</span>
          <span class="status-item">已答：{{ answeredCount }}</span>
          <span class="status-item">未答：{{ unansweredCount }}</span>
          <span class="status-item">标记：{{ markedCount }}</span>
        </div>
      </div>
    </div>

    <!-- 考试说明页面 -->
    <div class="exam-instructions" v-if="!examStarted">
      <div class="container">
        <div class="instructions-card">
          <h3>考试说明</h3>
          <ul>
            <li>本次考试共{{ questions.length }}道题，总分{{ totalScore }}分</li>
            <li>考试时长{{ examDuration }}分钟，请合理安排答题时间</li>
            <li>考试开始后不能暂停，请确保网络连接稳定</li>
            <li>每道题只能选择一个答案，提交后不能修改</li>
            <li>考试结束后系统将自动提交答案</li>
          </ul>
          <div class="exam-actions">
            <button class="btn-start-exam" @click="startExam">开始考试</button>
            <button class="btn-back" @click="goBack">返回课程</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 考试主体内容 -->
    <div class="exam-main" v-if="examStarted && !examFinished">
      <div class="container">
        <div class="exam-layout">
          <!-- 左侧导航 -->
          <div class="exam-sidebar">
            <!-- 考试时间 -->
            <div class="exam-timer">
              <h4>剩余时间</h4>
              <div class="timer-display" :class="{ 'timer-warning': remainingTime <= 300 }">
                {{ formatTimeHMS(remainingTime) }}
              </div>
            </div>

            <!-- 答题卡 -->
            <div class="answer-sheet">
              <h4>答题卡</h4>
              <div class="question-grid">
                <!-- 单选题 -->
                <div class="question-section">
                  <div class="section-header">
                    <h5>单选题</h5>
                    <span class="section-count">({{ questionsByType['单选题'].length }})</span>
                  </div>
                  <div class="question-numbers">
                    <div
                      v-for="(question, index) in questionsByType['单选题']"
                      :key="question.id"
                      class="question-number"
                      :class="getQuestionStatus(question.id - 1)"
                      @click="goToQuestion(question.id - 1)"
                    >
                      {{ String(index + 1).padStart(2, '0') }}
                    </div>
                  </div>
                </div>

                <!-- 多选题 -->
                <div class="question-section">
                  <div class="section-header">
                    <h5>多选题</h5>
                    <span class="section-count">({{ questionsByType['多选题'].length }})</span>
                  </div>
                  <div class="question-numbers">
                    <div
                      v-for="(question, index) in questionsByType['多选题']"
                      :key="question.id"
                      class="question-number"
                      :class="getQuestionStatus(question.id - 1)"
                      @click="goToQuestion(question.id - 1)"
                    >
                      {{ String(index + 1).padStart(2, '0') }}
                    </div>
                  </div>
                </div>

                <!-- 判断题 -->
                <div class="question-section">
                  <div class="section-header">
                    <h5>判断题</h5>
                    <span class="section-count">({{ questionsByType['判断题'].length }})</span>
                  </div>
                  <div class="question-numbers">
                    <div
                      v-for="(question, index) in questionsByType['判断题']"
                      :key="question.id"
                      class="question-number"
                      :class="getQuestionStatus(question.id - 1)"
                      @click="goToQuestion(question.id - 1)"
                    >
                      {{ String(index + 1).padStart(2, '0') }}
                    </div>
                  </div>
                </div>

                <!-- 填空题 -->
                <div class="question-section">
                  <div class="section-header">
                    <h5>填空题</h5>
                    <span class="section-count">({{ questionsByType['填空题'].length }})</span>
                  </div>
                  <div class="question-numbers">
                    <div
                      v-for="(question, index) in questionsByType['填空题']"
                      :key="question.id"
                      class="question-number"
                      :class="getQuestionStatus(question.id - 1)"
                      @click="goToQuestion(question.id - 1)"
                    >
                      {{ String(index + 1).padStart(2, '0') }}
                    </div>
                  </div>
                </div>

                <!-- 简答题 -->
                <div class="question-section">
                  <div class="section-header">
                    <h5>简答题</h5>
                    <span class="section-count">({{ questionsByType['简答题'].length }})</span>
                  </div>
                  <div class="question-numbers">
                    <div
                      v-for="(question, index) in questionsByType['简答题']"
                      :key="question.id"
                      class="question-number"
                      :class="getQuestionStatus(question.id - 1)"
                      @click="goToQuestion(question.id - 1)"
                    >
                      {{ String(index + 1).padStart(2, '0') }}
                    </div>
                  </div>
                </div>
              </div>

              <!-- 答题状态统计 -->
              <div class="answer-status">
                <div class="status-row">
                  <div class="status-item">
                    <span class="status-label">已答</span>
                    <span class="status-count">{{ answeredCount }}</span>
                  </div>
                  <div class="status-item">
                    <span class="status-label">未答</span>
                    <span class="status-count">{{ unansweredCount }}</span>
                  </div>
                </div>
              </div>

              <!-- 交卷按钮 -->
              <div class="submit-section">
                <button class="btn-submit-exam" @click="submitExam">交卷</button>
              </div>
            </div>
          </div>

          <!-- 右侧题目内容 -->
          <div class="exam-content">
            <div class="question-card" v-if="currentQuestion">
              <div class="question-header">
                <span class="question-number">Q{{ currentQuestionIndex + 1 }}/{{ questions.length }}</span>
                <span class="question-type">【{{ currentQuestion.type }}】</span>
                <span class="question-score">{{ currentQuestion.score }}分</span>
              </div>

              <div class="question-content">
                <div class="question-title">
                  {{ currentQuestion.title }}
                </div>

                <!-- 选择题选项 -->
                <div v-if="currentQuestion.type === '单选题' || currentQuestion.type === '多选题' || currentQuestion.type === '判断题'" class="question-options">
                  <div
                    v-for="(option, index) in currentQuestion.options"
                    :key="index"
                    class="option-item"
                    :class="{ 'selected': isOptionSelected(index) }"
                    @click="selectOption(index)"
                  >
                    <div class="option-checkbox">
                      <input
                        :type="currentQuestion.type === '多选题' ? 'checkbox' : 'radio'"
                        :name="`question-${currentQuestionIndex}`"
                        :checked="isOptionSelected(index)"
                        @change="handleCheckboxClick(index, $event)"
                        @click="handleCheckboxClick(index, $event)"
                      >
                    </div>
                    <div class="option-content">
                      <span class="option-label">{{ String.fromCharCode(65 + index) }}.</span>
                      <span class="option-text">{{ option }}</span>
                    </div>
                  </div>
                </div>

                <!-- 填空题输入框 -->
                <div v-else-if="currentQuestion.type === '填空题'" class="fill-blank">
                  <input
                    type="text"
                    v-model="fillAnswers[currentQuestionIndex]"
                    placeholder="请输入答案"
                    class="fill-input"
                  />
                </div>

                <!-- 简答题文本域 -->
                <div v-else-if="currentQuestion.type === '简答题'" class="essay-answer">
                  <textarea
                    v-model="essayAnswers[currentQuestionIndex]"
                    placeholder="请输入答案"
                    class="essay-textarea"
                    rows="8"
                  ></textarea>
                </div>
              </div>

              <div class="question-navigation">
                <button
                  class="btn-nav btn-prev"
                  @click="previousQuestion"
                  :disabled="currentQuestionIndex === 0"
                >
                  上一题
                </button>
                <button
                  class="btn-nav btn-next"
                  @click="nextQuestion"
                >
                  下一题
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 考试结果 -->
    <div class="exam-result" v-if="examFinished">
      <div class="container">
        <div class="result-card">
          <div class="result-header">
            <h2>考试完成</h2>
            <div class="result-score">
              <span class="score-label">您的得分：</span>
              <span class="score-value">{{ finalScore }}</span>
              <span class="score-total">/ {{ totalScore }}</span>
            </div>
          </div>
          <div class="result-details">
            <div class="result-item">
              <span class="label">正确题数：</span>
              <span class="value">{{ correctCount }} / {{ questions.length }}</span>
            </div>
            <div class="result-item">
              <span class="label">正确率：</span>
              <span class="value">{{ Math.round(correctCount / questions.length * 100) }}%</span>
            </div>
            <div class="result-item">
              <span class="label">用时：</span>
              <span class="value">{{ formatTime(examDuration * 60 - remainingTime) }}</span>
            </div>
          </div>
          <div class="result-actions">
            <button class="btn-review" @click="reviewAnswers">查看答案</button>
            <button class="btn-back" @click="goBack">返回课程</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

// 路由参数
const courseId = ref(Number(route.params.courseId))
const sectionId = ref(Number(route.params.sectionId))
const courseName = ref(route.query.courseName as string || '课程名称')
const examName = ref(route.query.examName as string || '考试')

// 考试状态
const examStarted = ref(false)
const examFinished = ref(false)
const examDuration = ref(120) // 考试时长（分钟）- 2小时
const remainingTime = ref(0) // 剩余时间（秒）
const timer = ref<NodeJS.Timeout | null>(null)

// 题目相关
const currentQuestionIndex = ref(0)
const selectedAnswers = ref<number[]>([])
const multipleAnswers = ref<number[][]>([]) // 多选题答案
const fillAnswers = ref<string[]>([]) // 填空题答案
const essayAnswers = ref<string[]>([]) // 简答题答案
const isMarked = ref<boolean[]>([])
const finalScore = ref(0)
const correctCount = ref(0)

// 模拟考试题目
const questions = ref([
  // 单选题 (1-10)
  {
    id: 1,
    type: '单选题',
    score: 2,
    title: '信息学奥赛中常用的编程语言是什么？',
    options: ['Java', 'Python', 'C++', 'JavaScript'],
    correctAnswer: 2
  },
  {
    id: 2,
    type: '单选题',
    score: 2,
    title: '以下哪个是正确的C++变量声明？',
    options: ['int 2num;', 'int num_2;', 'int num-2;', 'int num 2;'],
    correctAnswer: 1
  },
  {
    id: 3,
    type: '单选题',
    score: 2,
    title: '在C++中，以下哪个运算符用于取地址？',
    options: ['*', '&', '%', '^'],
    correctAnswer: 1
  },
  {
    id: 4,
    type: '单选题',
    score: 2,
    title: '以下哪个循环结构在执行前不检查条件？',
    options: ['for循环', 'while循环', 'do-while循环', '以上都不是'],
    correctAnswer: 2
  },
  {
    id: 5,
    type: '单选题',
    score: 2,
    title: '在C++中，数组下标从几开始？',
    options: ['1', '0', '-1', '任意数'],
    correctAnswer: 1
  },
  {
    id: 6,
    type: '单选题',
    score: 2,
    title: '以下哪个是C++的标准输入流？',
    options: ['cout', 'cin', 'printf', 'scanf'],
    correctAnswer: 1
  },
  {
    id: 7,
    type: '单选题',
    score: 2,
    title: '在C++中，以下哪个关键字用于定义常量？',
    options: ['var', 'let', 'const', 'final'],
    correctAnswer: 2
  },
  {
    id: 8,
    type: '单选题',
    score: 2,
    title: '以下哪个是正确的函数定义语法？',
    options: ['function int add()', 'int add()', 'def add()', 'add() int'],
    correctAnswer: 1
  },
  {
    id: 9,
    type: '单选题',
    score: 2,
    title: '在C++中，以下哪个符号用于单行注释？',
    options: ['//', '/* */', '#', '--'],
    correctAnswer: 0
  },
  {
    id: 10,
    type: '单选题',
    score: 2,
    title: '以下哪个是C++中的逻辑与运算符？',
    options: ['&', '&&', 'and', '|'],
    correctAnswer: 1
  },
  // 多选题 (11-20)
  {
    id: 11,
    type: '多选题',
    score: 3,
    title: '以下哪些是C++的基本数据类型？',
    options: ['int', 'float', 'string', 'char'],
    correctAnswer: [0, 1, 3]
  },
  {
    id: 12,
    type: '多选题',
    score: 3,
    title: '以下哪些是面向对象编程的特征？',
    options: ['封装', '继承', '多态', '抽象'],
    correctAnswer: [0, 1, 2, 3]
  },
  {
    id: 13,
    type: '多选题',
    score: 3,
    title: '以下哪些是C++中的循环语句？',
    options: ['for', 'while', 'do-while', 'foreach'],
    correctAnswer: [0, 1, 2]
  },
  {
    id: 14,
    type: '多选题',
    score: 3,
    title: '以下哪些是C++中的条件语句？',
    options: ['if', 'switch', 'case', 'else'],
    correctAnswer: [0, 1]
  },
  {
    id: 15,
    type: '多选题',
    score: 3,
    title: '以下哪些是C++中的运算符？',
    options: ['++', '--', '+=', '=='],
    correctAnswer: [0, 1, 2, 3]
  },
  {
    id: 16,
    type: '多选题',
    score: 3,
    title: '以下哪些是C++中的存储类？',
    options: ['auto', 'static', 'extern', 'register'],
    correctAnswer: [0, 1, 2, 3]
  },
  {
    id: 17,
    type: '多选题',
    score: 3,
    title: '以下哪些是C++中的访问修饰符？',
    options: ['public', 'private', 'protected', 'internal'],
    correctAnswer: [0, 1, 2]
  },
  {
    id: 18,
    type: '多选题',
    score: 3,
    title: '以下哪些是C++中的标准库？',
    options: ['iostream', 'vector', 'string', 'algorithm'],
    correctAnswer: [0, 1, 2, 3]
  },
  {
    id: 19,
    type: '多选题',
    score: 3,
    title: '以下哪些是C++中的容器？',
    options: ['vector', 'list', 'map', 'set'],
    correctAnswer: [0, 1, 2, 3]
  },
  {
    id: 20,
    type: '多选题',
    score: 3,
    title: '以下哪些是C++中的智能指针？',
    options: ['unique_ptr', 'shared_ptr', 'weak_ptr', 'auto_ptr'],
    correctAnswer: [0, 1, 2]
  },
  // 判断题 (21-30)
  {
    id: 21,
    type: '判断题',
    score: 1,
    title: 'C++是一种面向对象的编程语言。',
    options: ['正确', '错误'],
    correctAnswer: 0
  },
  {
    id: 22,
    type: '判断题',
    score: 1,
    title: 'C++中的数组下标从1开始。',
    options: ['正确', '错误'],
    correctAnswer: 1
  },
  {
    id: 23,
    type: '判断题',
    score: 1,
    title: 'C++中可以使用//进行单行注释。',
    options: ['正确', '错误'],
    correctAnswer: 0
  },
  {
    id: 24,
    type: '判断题',
    score: 1,
    title: 'C++中的变量必须先声明后使用。',
    options: ['正确', '错误'],
    correctAnswer: 0
  },
  {
    id: 25,
    type: '判断题',
    score: 1,
    title: 'C++中的函数可以重载。',
    options: ['正确', '错误'],
    correctAnswer: 0
  },
  {
    id: 26,
    type: '判断题',
    score: 1,
    title: 'C++中的类可以继承多个父类。',
    options: ['正确', '错误'],
    correctAnswer: 0
  },
  {
    id: 27,
    type: '判断题',
    score: 1,
    title: 'C++中的指针可以进行算术运算。',
    options: ['正确', '错误'],
    correctAnswer: 0
  },
  {
    id: 28,
    type: '判断题',
    score: 1,
    title: 'C++中的const关键字用于定义常量。',
    options: ['正确', '错误'],
    correctAnswer: 0
  },
  {
    id: 29,
    type: '判断题',
    score: 1,
    title: 'C++中的虚函数可以实现多态。',
    options: ['正确', '错误'],
    correctAnswer: 0
  },
  {
    id: 30,
    type: '判断题',
    score: 1,
    title: 'C++中的析构函数可以有参数。',
    options: ['正确', '错误'],
    correctAnswer: 1
  },
  // 填空题 (31-40)
  {
    id: 31,
    type: '填空题',
    score: 4,
    title: '在C++中，用于输出的流对象是______。',
    options: [],
    correctAnswer: 'cout'
  },
  {
    id: 32,
    type: '填空题',
    score: 4,
    title: 'C++中定义整型变量的关键字是______。',
    options: [],
    correctAnswer: 'int'
  },
  {
    id: 33,
    type: '填空题',
    score: 4,
    title: 'C++中用于包含头文件的预处理指令是______。',
    options: [],
    correctAnswer: '#include'
  },
  {
    id: 34,
    type: '填空题',
    score: 4,
    title: 'C++中主函数的名称是______。',
    options: [],
    correctAnswer: 'main'
  },
  {
    id: 35,
    type: '填空题',
    score: 4,
    title: 'C++中用于定义类的关键字是______。',
    options: [],
    correctAnswer: 'class'
  },
  {
    id: 36,
    type: '填空题',
    score: 4,
    title: 'C++中用于动态分配内存的运算符是______。',
    options: [],
    correctAnswer: 'new'
  },
  {
    id: 37,
    type: '填空题',
    score: 4,
    title: 'C++中用于释放动态分配内存的运算符是______。',
    options: [],
    correctAnswer: 'delete'
  },
  {
    id: 38,
    type: '填空题',
    score: 4,
    title: 'C++中用于定义命名空间的关键字是______。',
    options: [],
    correctAnswer: 'namespace'
  },
  {
    id: 39,
    type: '填空题',
    score: 4,
    title: 'C++中用于继承的符号是______。',
    options: [],
    correctAnswer: ':'
  },
  {
    id: 40,
    type: '填空题',
    score: 4,
    title: 'C++中用于访问类成员的运算符是______。',
    options: [],
    correctAnswer: '.'
  },
  // 简答题 (41-44)
  {
    id: 41,
    type: '简答题',
    score: 10,
    title: '请简述C++中面向对象编程的三大特征。',
    options: [],
    correctAnswer: '封装、继承、多态'
  },
  {
    id: 42,
    type: '简答题',
    score: 10,
    title: '请解释C++中指针和引用的区别。',
    options: [],
    correctAnswer: '指针是变量的地址，引用是变量的别名'
  },
  {
    id: 43,
    type: '简答题',
    score: 10,
    title: '请说明C++中构造函数和析构函数的作用。',
    options: [],
    correctAnswer: '构造函数用于初始化对象，析构函数用于清理对象'
  },
  {
    id: 44,
    type: '简答题',
    score: 10,
    title: '请解释C++中虚函数的概念和作用。',
    options: [],
    correctAnswer: '虚函数实现多态，允许在运行时确定调用哪个函数'
  }
])

// 计算属性
const currentQuestion = computed(() => questions.value[currentQuestionIndex.value])
const totalScore = computed(() => questions.value.reduce((sum, q) => sum + q.score, 0))

const answeredCount = computed(() => {
  let count = 0
  questions.value.forEach((question, index) => {
    if (question.type === '单选题' || question.type === '判断题') {
      if (selectedAnswers.value[index] !== -1) count++
    } else if (question.type === '多选题') {
      if (multipleAnswers.value[index] && multipleAnswers.value[index].length > 0) count++
    } else if (question.type === '填空题') {
      if (fillAnswers.value[index] && fillAnswers.value[index].trim() !== '') count++
    } else if (question.type === '简答题') {
      if (essayAnswers.value[index] && essayAnswers.value[index].trim() !== '') count++
    }
  })
  return count
})
const unansweredCount = computed(() => questions.value.length - answeredCount.value)
const markedCount = computed(() => isMarked.value.filter(marked => marked).length)

// 按题型分组统计
const questionsByType = computed(() => {
  const groups = {
    '单选题': questions.value.filter(q => q.type === '单选题'),
    '多选题': questions.value.filter(q => q.type === '多选题'),
    '判断题': questions.value.filter(q => q.type === '判断题'),
    '填空题': questions.value.filter(q => q.type === '填空题'),
    '简答题': questions.value.filter(q => q.type === '简答题')
  }
  return groups
})



// 开始考试
const startExam = () => {
  examStarted.value = true
  remainingTime.value = examDuration.value * 60
  selectedAnswers.value = new Array(questions.value.length).fill(-1)
  multipleAnswers.value = Array.from({ length: questions.value.length }, () => [])
  fillAnswers.value = new Array(questions.value.length).fill('')
  essayAnswers.value = new Array(questions.value.length).fill('')
  isMarked.value = new Array(questions.value.length).fill(false)
  startTimer()
}

// 开始计时器
const startTimer = () => {
  timer.value = setInterval(() => {
    remainingTime.value--
    if (remainingTime.value <= 0) {
      submitExam()
    }
  }, 1000)
}



// 选择选项（通用）
const selectOption = (optionIndex: number) => {
  const question = currentQuestion.value
  if (question.type === '多选题') {
    const currentAnswers = multipleAnswers.value[currentQuestionIndex.value] || []
    const answerIndex = currentAnswers.indexOf(optionIndex)
    if (answerIndex > -1) {
      // 取消选择
      currentAnswers.splice(answerIndex, 1)
    } else {
      // 添加选择
      currentAnswers.push(optionIndex)
    }
    multipleAnswers.value[currentQuestionIndex.value] = [...currentAnswers]
  } else {
    // 单选题、判断题
    selectedAnswers.value[currentQuestionIndex.value] = optionIndex
  }
}

// 检查选项是否被选中
const isOptionSelected = (optionIndex: number) => {
  const question = currentQuestion.value
  if (question.type === '多选题') {
    const currentAnswers = multipleAnswers.value[currentQuestionIndex.value] || []
    return currentAnswers.includes(optionIndex)
  } else {
    return selectedAnswers.value[currentQuestionIndex.value] === optionIndex
  }
}

// 处理复选框点击
const handleCheckboxClick = (optionIndex: number, event: Event) => {
  event.stopPropagation()
  selectOption(optionIndex)
}

// 上一题
const previousQuestion = () => {
  if (currentQuestionIndex.value > 0) {
    currentQuestionIndex.value--
  }
}

// 下一题
const nextQuestion = () => {
  if (currentQuestionIndex.value < questions.value.length - 1) {
    currentQuestionIndex.value++
  }
}

// 跳转到指定题目
const goToQuestion = (index: number) => {
  currentQuestionIndex.value = index
}

// 获取题目状态
const getQuestionStatus = (index: number) => {
  const classes = []
  const question = questions.value[index]

  // 当前题目
  if (index === currentQuestionIndex.value) {
    classes.push('current')
  }

  // 已答题目
  let isAnswered = false
  if (question.type === '单选题' || question.type === '判断题') {
    isAnswered = selectedAnswers.value[index] !== -1
  } else if (question.type === '多选题') {
    isAnswered = multipleAnswers.value[index] && multipleAnswers.value[index].length > 0
  } else if (question.type === '填空题') {
    isAnswered = !!(fillAnswers.value[index] && fillAnswers.value[index].trim() !== '')
  } else if (question.type === '简答题') {
    isAnswered = !!(essayAnswers.value[index] && essayAnswers.value[index].trim() !== '')
  }

  if (isAnswered) {
    classes.push('answered')
  }

  // 标记题目
  if (isMarked.value[index]) {
    classes.push('marked')
  }

  return classes
}

// 提交考试
const submitExam = () => {
  if (timer.value) {
    clearInterval(timer.value)
  }
  
  // 计算得分
  correctCount.value = 0
  finalScore.value = 0

  questions.value.forEach((question, index) => {
    let isCorrect = false

    if (question.type === '单选题' || question.type === '判断题') {
      isCorrect = selectedAnswers.value[index] === question.correctAnswer
    } else if (question.type === '多选题') {
      const userAnswers = multipleAnswers.value[index] || []
      const correctAnswers = Array.isArray(question.correctAnswer) ? question.correctAnswer : [question.correctAnswer]
      isCorrect = userAnswers.length === correctAnswers.length &&
                  userAnswers.every(answer => correctAnswers.includes(answer))
    } else if (question.type === '填空题') {
      const userAnswer = fillAnswers.value[index] || ''
      const correctAnswer = String(question.correctAnswer)
      isCorrect = userAnswer.trim().toLowerCase() === correctAnswer.toLowerCase()
    } else if (question.type === '简答题') {
      // 简答题需要人工评分，这里暂时不计分
      const userAnswer = essayAnswers.value[index] || ''
      isCorrect = userAnswer.trim() !== '' // 只要有内容就算答题了
    }

    if (isCorrect) {
      correctCount.value++
      finalScore.value += question.score
    }
  })
  
  examFinished.value = true
  console.log('考试完成，得分:', finalScore.value)
}

// 查看答案
const reviewAnswers = () => {
  // 这里可以跳转到答案解析页面
  alert('答案解析功能开发中...')
}

// 返回课程
const goBack = () => {
  router.push(`/course/${courseId.value}`)
}

// 格式化时间
const formatTime = (seconds: number): string => {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
}

// 格式化时间显示为时分秒
const formatTimeHMS = (seconds: number): string => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const remainingSeconds = seconds % 60
  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
}

// 组件卸载时清理计时器
onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value)
  }
})

onMounted(() => {
  console.log('考试页面加载完成')
  console.log('课程ID:', courseId.value)
  console.log('章节ID:', sectionId.value)
  console.log('考试名称:', examName.value)

  // 检查是否从考前须知页面跳转过来，如果是则直接开始考试
  const fromNotice = route.query.fromNotice
  if (fromNotice === 'true') {
    startExam()
  }
})
</script>

<style scoped>
.exam-page {
  min-height: 100vh;
  background: #f5f7fa;
}

/* 考试中心标题 */
.exam-center-header {
  background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
  padding: 40px 0;
  text-align: center;
  color: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.center-title {
  font-size: 36px;
  font-weight: 600;
  margin: 0 0 12px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.center-subtitle {
  font-size: 16px;
  margin: 0;
  opacity: 0.9;
}

/* 面包屑导航 */
.breadcrumb {
  background: white;
  padding: 16px 0;
  border-bottom: 1px solid #e8e8e8;
}

.container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 20px;
}

.breadcrumb-text {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
  display: block;
}

.exam-status {
  display: flex;
  gap: 20px;
  font-size: 12px;
}

.status-item {
  color: #999;
}

/* 考试主体布局 */
.exam-main {
  padding: 20px 0;
  min-height: calc(100vh - 200px);
}

.exam-layout {
  display: flex;
  gap: 20px;
  align-items: flex-start;
}

/* 左侧边栏 */
.exam-sidebar {
  width: 280px;
  flex-shrink: 0;
}

/* 考试时间 */
.exam-timer {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.exam-timer h4 {
  font-size: 16px;
  color: #333;
  margin: 0 0 16px 0;
  font-weight: 500;
}

.timer-display {
  font-size: 32px;
  font-weight: 600;
  color: #333;
  font-family: 'Courier New', monospace;
  letter-spacing: 2px;
  background: #e8f4fd;
  padding: 12px 20px;
  border-radius: 6px;
  border: 1px solid #c5e2f7;
}

.timer-warning {
  color: #ff4d4f !important;
  animation: pulse 1s infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.7; }
}

/* 答题卡 */
.answer-sheet {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.answer-sheet h4 {
  font-size: 16px;
  color: #333;
  margin: 0 0 16px 0;
  font-weight: 500;
}

.question-section {
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.section-header h5 {
  font-size: 14px;
  color: #333;
  margin: 0;
  font-weight: 500;
}

.section-count {
  font-size: 12px;
  color: #999;
}

.question-numbers {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 8px;
}

.question-number {
  width: 40px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s;
  background: white;
  color: #666;
}

.question-number:hover {
  border-color: #1890ff;
  color: #1890ff;
}

.question-number.current {
  background: #2a5298;
  color: white;
  border-color: #2a5298;
}

.question-number.answered {
  background: #2a5298;
  color: white;
  border-color: #2a5298;
}

.question-number.marked {
  background: #faad14;
  color: white;
  border-color: #faad14;
}

/* 答题状态统计 */
.answer-status {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e8e8e8;
}

.status-row {
  display: flex;
  justify-content: space-between;
}

.status-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.status-label {
  font-size: 12px;
  color: #666;
}

.status-count {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

/* 提交按钮区域 */
.submit-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e8e8e8;
}

.btn-submit-exam {
  width: 100%;
  background: #52c41a;
  color: white;
  border: none;
  padding: 12px;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-submit-exam:hover {
  background: #73d13d;
}

/* 右侧题目内容 */
.exam-content {
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  min-height: 600px;
}

.question-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.question-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e8e8e8;
}

.question-number {
  background: #f0f9ff;
  color: #1890ff;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 600;
}

.question-type {
  color: #666;
  font-size: 14px;
}

.question-score {
  color: #666;
  font-size: 14px;
  margin-left: auto;
}

.question-content {
  flex: 1;
  margin-bottom: 24px;
}

.question-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin: 0 0 24px 0;
  line-height: 1.8;
}

.question-options {
  margin-bottom: 24px;
}

.option-item {
  display: flex;
  align-items: flex-start;
  padding: 16px;
  border: 1px solid #d1e7f0;
  border-radius: 6px;
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.3s;
  background: #e8f4fd;
}

.option-item:hover {
  border-color: #2a5298;
  background: #ddeef8;
}

.option-item.selected {
  border-color: #2a5298;
  background: #ddeef8;
}

.option-radio {
  margin-right: 12px;
  margin-top: 2px;
}

.option-radio input[type="radio"] {
  width: 16px;
  height: 16px;
  accent-color: #2a5298;
}

.option-content {
  display: flex;
  align-items: flex-start;
  flex: 1;
}

.option-label {
  font-weight: 600;
  color: #333;
  margin-right: 12px;
  min-width: 24px;
}

.option-text {
  color: #333;
  line-height: 1.6;
  flex: 1;
}

.option-checkbox {
  margin-right: 12px;
  margin-top: 2px;
  cursor: pointer;
  padding: 2px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.option-checkbox input[type="checkbox"],
.option-checkbox input[type="radio"] {
  width: 16px;
  height: 16px;
  accent-color: #2a5298;
  cursor: pointer;
  margin: 0;
}

.option-checkbox input[type="checkbox"]:checked,
.option-checkbox input[type="radio"]:checked {
  background-color: #2a5298;
  border-color: #2a5298;
}

/* 填空题样式 */
.fill-blank {
  margin-bottom: 24px;
}

.fill-input {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  font-size: 16px;
  transition: border-color 0.3s;
}

.fill-input:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

/* 简答题样式 */
.essay-answer {
  margin-bottom: 24px;
}

.essay-textarea {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  font-size: 16px;
  font-family: inherit;
  resize: vertical;
  min-height: 120px;
  transition: border-color 0.3s;
}

.essay-textarea:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.question-navigation {
  display: flex;
  justify-content: center;
  gap: 16px;
  padding-top: 20px;
  border-top: 1px solid #e8e8e8;
}

.btn-nav {
  padding: 10px 24px;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  min-width: 100px;
}

.btn-prev {
  background: #f5f5f5;
  color: #666;
  border: 1px solid #d9d9d9;
}

.btn-next {
  background: #1890ff;
  color: white;
  border: 1px solid #1890ff;
}

.btn-prev:hover {
  background: #e6f7ff;
  border-color: #1890ff;
  color: #1890ff;
}

.btn-next:hover {
  background: #40a9ff;
  border-color: #40a9ff;
}

.btn-prev:disabled {
  background: #f5f5f5;
  color: #bfbfbf;
  border-color: #e8e8e8;
  cursor: not-allowed;
}

/* 考试结果 */
.exam-result {
  display: flex;
  justify-content: center;
}

.result-card {
  background: white;
  border-radius: 8px;
  padding: 32px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  text-align: center;
  max-width: 500px;
  width: 100%;
}

.result-header h2 {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0 0 20px 0;
}

.result-score {
  margin-bottom: 24px;
}

.score-label {
  font-size: 16px;
  color: #666;
}

.score-value {
  font-size: 36px;
  font-weight: 600;
  color: #52c41a;
  margin: 0 8px;
}

.score-total {
  font-size: 18px;
  color: #666;
}

.result-details {
  border-top: 1px solid #e8e8e8;
  border-bottom: 1px solid #e8e8e8;
  padding: 20px 0;
  margin-bottom: 24px;
}

.result-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
}

.result-item:last-child {
  margin-bottom: 0;
}

.result-item .label {
  color: #666;
}

.result-item .value {
  font-weight: 500;
  color: #333;
}

.result-actions {
  display: flex;
  gap: 16px;
  justify-content: center;
}

.btn-review {
  background: #1890ff;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-review:hover {
  background: #40a9ff;
}

/* 考试说明页面 */
.exam-instructions {
  padding: 40px 0;
  min-height: calc(100vh - 200px);
  display: flex;
  align-items: center;
  justify-content: center;
}

.instructions-card {
  background: white;
  border-radius: 12px;
  padding: 40px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  max-width: 600px;
  width: 100%;
}

.instructions-card h3 {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0 0 24px 0;
  text-align: center;
}

.instructions-card ul {
  margin: 0 0 32px 0;
  padding-left: 20px;
}

.instructions-card li {
  margin-bottom: 12px;
  color: #666;
  line-height: 1.8;
  font-size: 15px;
}

.exam-actions {
  display: flex;
  gap: 16px;
  justify-content: center;
}

.btn-start-exam {
  background: #1890ff;
  color: white;
  border: none;
  padding: 14px 32px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-start-exam:hover {
  background: #40a9ff;
}

.btn-back {
  background: #f5f5f5;
  color: #666;
  border: 1px solid #d9d9d9;
  padding: 14px 24px;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-back:hover {
  background: #e6f7ff;
  border-color: #1890ff;
  color: #1890ff;
}

/* 考试结果 */
.exam-result {
  padding: 40px 0;
  min-height: calc(100vh - 200px);
  display: flex;
  align-items: center;
  justify-content: center;
}

.result-card {
  background: white;
  border-radius: 12px;
  padding: 40px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  text-align: center;
  max-width: 500px;
  width: 100%;
}

.result-header h2 {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0 0 20px 0;
}

.result-score {
  margin-bottom: 24px;
}

.score-label {
  font-size: 16px;
  color: #666;
}

.score-value {
  font-size: 36px;
  font-weight: 600;
  color: #52c41a;
  margin: 0 8px;
}

.score-total {
  font-size: 18px;
  color: #666;
}

.result-details {
  border-top: 1px solid #e8e8e8;
  border-bottom: 1px solid #e8e8e8;
  padding: 20px 0;
  margin-bottom: 24px;
}

.result-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
}

.result-item:last-child {
  margin-bottom: 0;
}

.result-item .label {
  color: #666;
}

.result-item .value {
  font-weight: 500;
  color: #333;
}

.result-actions {
  display: flex;
  gap: 16px;
  justify-content: center;
}

.btn-review {
  background: #1890ff;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-review:hover {
  background: #40a9ff;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .exam-layout {
    flex-direction: column;
  }

  .exam-sidebar {
    width: 100%;
    order: 2;
  }

  .exam-content {
    order: 1;
    margin-bottom: 20px;
  }

  .question-numbers {
    grid-template-columns: repeat(10, 1fr);
  }
}

@media (max-width: 768px) {
  .center-title {
    font-size: 28px;
  }

  .center-subtitle {
    font-size: 14px;
  }

  .exam-status {
    flex-direction: column;
    gap: 8px;
  }

  .exam-actions {
    flex-direction: column;
  }

  .question-navigation {
    flex-direction: column;
  }

  .btn-nav {
    width: 100%;
  }

  .instructions-card {
    margin: 20px;
    padding: 24px;
  }
}
</style>
