<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import { useMessage, useToast } from 'wot-design-uni'
import { examPaperDetail } from '@/api/exam'

import { addAnswerResult } from '@/api/exam/answer'
import { endExam } from '@/api/exam/participant'

import oipimg from '@/assets/OIP-C.jpg'

const toast = useToast()
const wotMessage = useMessage()

const route = useRoute()
const examId = route.query.id || 0
const participantId = Number(route.query.pid || 0)
const examInfo = ref({}) as any

// 当前显示题目的答案状态
const currentSingleChoiceAnswer = ref('') as any
const currentMultipleChoiceAnswers = ref([]) as any
const currentFillBlankAnswers = ref([]) as any
const currentEssayAnswer = ref('') as any
const list: any = ref([])
const contentItemsStatus = ref({ '0_0': true }) as any
const showItems = ref(false) as any

// 默认选中单选题第一题（索引为 0_0）
contentItemsStatus.value['0_0'] = true

// 存储键，用于标识当前考试的答题数据
const storageKey = `exam_answers_${examId}_${participantId}`

// 答案状态管理：每个题目索引对应一个答案状态
const answerStatus = ref({}) as any

// 标记题目状态管理：每个题目索引对应一个标记状态
const markedQuestions = ref({}) as any

// 历史答案状态，用于检测答案是否变化
const previousAnswerStatus = ref({}) as any

// 倒计时相关变量
const remainingTime = ref(0) // 剩余时间（秒）
const countdownTimer = ref(null as any) // 定时器引用

// 处理 v-html 内容中的 img 标签，设置宽度为 100%，高度为 auto
function processHtmlContent(content: string): string {
  if (!content)
    return content

  // 正则表达式处理 img 标签的宽高属性
  return content.replace(/<img([^>]*)>/gi, (match, attributes) => {
    // 移除已有的 width 和 height 属性
    const cleanedAttributes = attributes
      .replace(/\s*width="[^"]*"\s*/gi, ' ')
      .replace(/\s*height="[^"]*"\s*/gi, ' ')
      .trim()

    // 构建新的 img 标签，添加 width="100%" height="auto"
    const attributesStr = cleanedAttributes ? ` ${cleanedAttributes}` : ''

    return `<img${attributesStr} width="100%" height="auto">`
  })
}

// 保存答案到 storage
function saveAnswersToStorage() {
  try {
    const data = {
      answerStatus: answerStatus.value,
      markedQuestions: markedQuestions.value,
      timestamp: Date.now(),
    }
    localStorage.setItem(storageKey, JSON.stringify(data))
  }
  catch (error) {
    console.error('保存答案到 storage 失败:', error)
  }
}

// 从 storage 加载答案
function loadAnswersFromStorage() {
  try {
    const data = localStorage.getItem(storageKey)
    if (data) {
      const parsedData = JSON.parse(data)
      answerStatus.value = parsedData.answerStatus || {}
      markedQuestions.value = parsedData.markedQuestions || {}
      // 保存当前状态作为历史状态，用于后续检测变化
      previousAnswerStatus.value = structuredClone(answerStatus.value)
    }
  }
  catch (error) {
    console.error('从 storage 加载答案失败:', error)
  }
}

// 初始化倒计时
function initCountdown() {
  const startTime = examInfo.value.examStartTime

  const examDuration = examInfo.value.examDuration * 600_000

  if (startTime) {
    // 页面刷新或重新进入，根据开始时间计算剩余时间
    const now = Date.now()
    const startTimestamp = new Date(startTime).getTime()

    // 计算从开始到现在的经过时间
    const elapsed = Math.floor((now - startTimestamp) / 1000)

    // 计算剩余时间
    const actualRemaining = Math.max(0, examDuration - elapsed)

    if (actualRemaining > 0) {
      remainingTime.value = actualRemaining
    }
    else {
      // 时间已到，自动交卷
      remainingTime.value = 0
      toast.warning('时间到，自动交卷')
      handleTimeUp()
      return
    }
  }

  startCountdown()
}

// 开始倒计时
function startCountdown() {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value)
  }

  countdownTimer.value = setInterval(() => {
    if (remainingTime.value > 0) {
      remainingTime.value--

      if (remainingTime.value === 0) {
        // 时间到，自动交卷
        toast.warning('时间到，自动交卷')
        handleTimeUp()
      }
    }
  }, 1000)
}

// 停止倒计时
function stopCountdown() {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value)
    countdownTimer.value = null
  }
}

// 格式化时间显示
function formatTime(seconds: number) {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60

  return hours > 0
    ? `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
    : `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 时间到处理
async function handleTimeUp() {
  stopCountdown()
  // localStorage.removeItem('examStartTime');

  try {
    await submitCurrentQuestionAnswer()

    // 显示全局loading，提示试卷提交中
    // const loading = ElLoading.service({
    //   lock: true,
    //   text: '试卷提交中...',
    //   background: 'rgba(0, 0, 0, 0.7)',
    // })

    // 延时2秒再执行endExam
    await new Promise(resolve => setTimeout(resolve, 2000))

    await endExam(+participantId)

    // 提交成功，关闭loading
    // loading.close()

    // await closeCurrentTab()

    // 获取用户类型
    const userType = localStorage.getItem('exam:usertype') || ''
    if (userType === 'exam') {
      // Examcompleted
      uni.navigateTo({
        url: `/pages/knowledge/exam/submit?pid=${participantId}&id=${examId}`,
      })
      // router.replace({
      //   name: 'Examcomplet',
      //   params: {
      //     id: examId,
      //   },
      //   query: {
      //     pid: participantId,
      //   },
      // })
    }
    else {
      // router.replace({
      //   name: 'ExamCompleted',
      //   params: {
      //     id: examId,
      //   },
      //   query: {
      //     pid: participantId,
      //   },
      // })
      uni.navigateTo({
        url: `/pages/knowledge/exam/submit?pid=${participantId}&id=${examId}`,
      })
    }
  }
  catch (error) {
    console.error('交卷失败:', error)
    // 无论成功失败，都关闭loading
    // ElLoading.service().close()
  }
}

async function getExamPaperDetail() {
  const res: any = await examPaperDetail(+examId)
  examInfo.value = res.data

  // 构建list数组
  const buildList = () => {
    console.log(examInfo.value.paper.bigQuestionNames, 'examInfo.value.paper.bigQuestionNames')
    // 解析大题信息
    const bigQuestions = JSON.parse(
      examInfo.value.paper.bigQuestionNames || '[]',
    )
    const questions: any = examInfo.value.paper.questions || []

    // 预计算最大索引，避免数组动态扩展
    let maxIndex = -1
    for (const question of questions) {
      const index = question.bigQuestionIndex
      if (index > maxIndex)
        maxIndex = index
    }

    // 预分配数组大小
    const groupedQuestions = Array.from({ length: maxIndex + 1 })

    // 分组操作
    for (const question of questions) {
      const index = question.bigQuestionIndex

      // 使用按位或 0 进行整数转换并检查
      const group: any = groupedQuestions[index]
      if (group) {
        group.push(question)
      }
      else {
        groupedQuestions[index] = [question]
      }
    }

    // 构建list数组
    const newList = bigQuestions.map((bigQ: any, bigIndex: number) => {
      // 获取该大题下的所有题目
      const bigQQuestions: any = groupedQuestions[bigIndex] || []

      // 只显示大题名称，不区分题型（因为大题下的小题类型可能混合）
      const type = bigQ.name

      // 构建该大题下的小题数据
      const data = bigQQuestions.map((question: any) => {
        const info = question.info
        const options = info.options ? JSON.parse(info.options) : []

        // 保留原始选项，不添加前缀，在渲染时动态生成序号

        // 根据题目类型构建不同的数据结构
        if (question.questionType === 'fill_blank') {
          // 填空题：count是空白数量
          const blankCount = options.length
          return {
            type: question.questionType, // 存储题型信息
            title: info.questionContent,
            content: info.questionContent,
            blanks: blankCount,
            score: question.smallQuestionScore,
            paperQuestionId: question.id, // 保留试卷试题关联ID
          }
        }
        else if (question.questionType === 'essay') {
          // 简答题
          return {
            type: question.questionType, // 存储题型信息
            title: info.questionContent,
            content: '请作答',
            score: question.smallQuestionScore,
            paperQuestionId: question.id, // 保留试卷试题关联ID
          }
        }
        else {
          // 选择题（单选、判断、多选）
          return {
            type: question.questionType, // 存储题型信息
            title: info.questionContent,
            content: options, // 存储原始选项，不包含前缀
            score: question.smallQuestionScore,
            paperQuestionId: question.id, // 保留试卷试题关联ID
          }
        }
      })

      return {
        type,
        score: bigQ.score,
        data,
      }
    })

    return newList
  }

  // 更新list
  list.value = buildList()

  // 重置默认选中状态
  contentItemsStatus.value = {}
  contentItemsStatus.value['0_0'] = true

  // 更新当前答案显示
  updateCurrentAnswerDisplay()
}

// 组件挂载时初始化倒计时
onMounted(() => {
  getExamPaperDetail().then(() => {
    // 加载保存的答案
    loadAnswersFromStorage()
    // 加载答案后更新当前答案显示，确保第一题的答案能正确显示
    updateCurrentAnswerDisplay()
    initCountdown()
  })
})

// 组件卸载时清理定时器
onUnmounted(() => {
  stopCountdown()
})

// 获取当前选中的题目索引（使用计算属性优化性能）
const currentSelectedIndex = computed(() => {
  const keys = Object.keys(contentItemsStatus.value)
  if (keys.length === 0)
    return { index: 0, indexs: 0 }
  const selectedKey = keys.find(key => contentItemsStatus.value[key])
  if (!selectedKey)
    return { index: 0, indexs: 0 }
  const [index, indexs] = selectedKey.split('_').map(Number)
  return { index, indexs }
})

// 保持向后兼容的函数包装器
const getCurrentSelectedIndex = () => currentSelectedIndex.value

// 判断是否为单选题（包含单选和判断题）
function isSingleChoice() {
  const { index, indexs } = getCurrentSelectedIndex()
  const safeIndex = index ?? 0
  const safeIndexs = indexs ?? 0
  const question = list.value[safeIndex]?.data?.[safeIndexs]
  // 从题目数据中获取题型信息（存储在data中的type字段）
  return question?.type === 'single_choice' || question?.type === 'judgment'
}

// 判断是否为填空题
function isFillBlank() {
  const { index, indexs } = getCurrentSelectedIndex()
  const safeIndex = index ?? 0
  const safeIndexs = indexs ?? 0
  const question = list.value[safeIndex]?.data?.[safeIndexs]
  return question?.type === 'fill_blank'
}

// 判断是否为简答题
function isEssayQuestion() {
  const { index, indexs } = getCurrentSelectedIndex()
  const safeIndex = index ?? 0
  const safeIndexs = indexs ?? 0
  const question = list.value[safeIndex]?.data?.[safeIndexs]
  return question?.type === 'essay'
}

// 判断题目是否已答题
function isQuestionAnswered(index: number, indexs: number) {
  const key = `${index}_${indexs}`
  const answer = answerStatus.value[key]
  return (
    answer
    && ((answer.type === 'single' && answer.answer)
      || (answer.type === 'multiple'
        && answer.answers
        && answer.answers.length > 0)
      || (answer.type === 'fill_blank'
        && answer.answers
        && answer.answers.some((ans: any) => ans && ans.trim()))
      || (answer.type === 'essay' && answer.answer && answer.answer.trim()))
  )
}

// 获取当前题目标题
function getCurrentQuestionTitle() {
  const { index, indexs } = getCurrentSelectedIndex()
  console.log(index, indexs, 'getCurrentQuestionTitle')
  const question: any = list.value[index || 0]?.data[indexs || 0]
  const questionType = list.value[index || 0]?.type || '题目'
  return `${questionType} (本题分值${question?.score || 0}分)`
}

// 获取当前题目内容
function getCurrentQuestionContent() {
  const { index, indexs } = getCurrentSelectedIndex()
  const safeIndex = index ?? 0
  const safeIndexs = indexs ?? 0
  const question = list.value[safeIndex]?.data?.[safeIndexs]
  // const type = list.value[safeIndex]?.type || '';

  return {
    num: safeIndexs + 1,
    content: processHtmlContent(question?.title || ''),
  }
}

// 获取当前题目选项
function getCurrentQuestionOptions() {
  const { index, indexs } = getCurrentSelectedIndex()
  const safeIndex = index ?? 0
  const safeIndexs = indexs ?? 0
  const question = list.value[safeIndex]?.data?.[safeIndexs]
  const type = list.value[safeIndex]?.type || ''

  if (type.includes('填空')) {
    return question?.content || ''
  }

  return question?.content || ['A.答案1', 'B.答案2', 'C.答案3', 'D.答案4']
}

// 获取当前题目空白数量
function getCurrentBlankCount() {
  const { index, indexs } = getCurrentSelectedIndex()
  const safeIndex = index ?? 0
  const safeIndexs = indexs ?? 0
  const question = list.value[safeIndex]?.data?.[safeIndexs]
  return question?.blanks || 1
}

// 处理单选题答案变化
function handleSingleChoiceChange(value: any) {
  const { index, indexs } = getCurrentSelectedIndex()
  const key = `${index}_${indexs}`
  answerStatus.value[key] = {
    type: 'single',
    answer: value,
  }
  // 保存答案到 storage
  saveAnswersToStorage()
}

// 处理多选题答案变化
function handleMultipleChoiceChange(values: any) {
  const { index, indexs } = getCurrentSelectedIndex()
  const key = `${index}_${indexs}`
  answerStatus.value[key] = {
    type: 'multiple',
    answers: values || [],
  }
  // 保存答案到 storage
  saveAnswersToStorage()
}

// 处理填空题答案变化
function handleFillBlankChange() {
  const { index, indexs } = getCurrentSelectedIndex()
  const key = `${index}_${indexs}`
  answerStatus.value[key] = {
    type: 'fill_blank',
    answers: currentFillBlankAnswers.value,
  }
  // 保存答案到 storage
  saveAnswersToStorage()
}

// 处理简答题答案变化
function handleEssayChange() {
  const { index, indexs } = getCurrentSelectedIndex()
  const key = `${index}_${indexs}`
  answerStatus.value[key] = {
    type: 'essay',
    answer: currentEssayAnswer.value,
  }
  // 保存答案到 storage
  saveAnswersToStorage()
}

// TODO: 处理标记题目
// const toggleQuestionMark = () => {
//   const { index, indexs } = getCurrentSelectedIndex();
//   const key = `${index}_${indexs}`;

//   // 切换标记状态
//   if (markedQuestions.value[key]) {
//     delete markedQuestions.value[key];
//   } else {
//     markedQuestions.value[key] = true;
//   }

//   // 触发响应式更新
//   markedQuestions.value = { ...markedQuestions.value };
//   // 保存答案到 storage
//   saveAnswersToStorage();
// };

// 判断题目是否被标记
function isQuestionMarked(index: number, indexs: number) {
  const key = `${index}_${indexs}`
  return !!markedQuestions.value[key]
}

// 初始化填空题答案数组
function initializeFillBlankAnswers() {
  const blankCount = getCurrentBlankCount()
  const currentAnswers = currentFillBlankAnswers.value

  // 如果当前答案数组长度与空白数量不匹配，重新初始化
  if (currentAnswers.length !== blankCount) {
    currentFillBlankAnswers.value = Array.from({ length: blankCount }).fill('')
  }
}

// 更新当前题目的答案显示状态
function updateCurrentAnswerDisplay() {
  const { index, indexs } = getCurrentSelectedIndex()
  const key = `${index}_${indexs}`
  const answer = answerStatus.value[key]

  switch (answer?.type) {
    case 'essay': {
      currentEssayAnswer.value = answer.answer || ''
      currentSingleChoiceAnswer.value = ''
      currentMultipleChoiceAnswers.value = []
      currentFillBlankAnswers.value = []

      break
    }
    case 'fill_blank': {
      // 初始化填空题答案数组
      initializeFillBlankAnswers()
      currentFillBlankAnswers.value
        = answer.answers
          || Array.from({ length: getCurrentBlankCount() }).fill('')
      currentSingleChoiceAnswer.value = ''
      currentMultipleChoiceAnswers.value = []
      currentEssayAnswer.value = ''

      break
    }
    case 'multiple': {
      currentMultipleChoiceAnswers.value = answer.answers || []
      currentSingleChoiceAnswer.value = ''
      currentFillBlankAnswers.value = []
      currentEssayAnswer.value = ''

      break
    }
    case 'single': {
      currentSingleChoiceAnswer.value = answer.answer || ''
      currentMultipleChoiceAnswers.value = []
      currentFillBlankAnswers.value = []
      currentEssayAnswer.value = ''

      break
    }
    default: {
      // 清除当前显示状态
      currentSingleChoiceAnswer.value = ''
      currentMultipleChoiceAnswers.value = []
      currentFillBlankAnswers.value = isFillBlank()
        ? Array.from({ length: getCurrentBlankCount() }).fill('')
        : []
      currentEssayAnswer.value = isEssayQuestion() ? '' : ''
    }
  }
}

async function contentItemsClick(index: number, indexs: number) {
  // 先提交当前题目的答案
  await submitCurrentQuestionAnswer()

  const key = `${index}_${indexs}`
  // 单选模式：先清空所有选中状态，然后只设置当前题目为选中
  contentItemsStatus.value = {}
  contentItemsStatus.value[key] = true

  // 更新当前题目的答案显示状态
  updateCurrentAnswerDisplay()
}

// 获取所有题目的扁平化列表（用于导航）
function getAllQuestions() {
  const questions: any = []
  list.value.forEach((section: any, sectionIndex: number) => {
    section.data.forEach((question: any, questionIndex: number) => {
      questions.push({
        sectionIndex,
        questionIndex,
        key: `${sectionIndex}_${questionIndex}`,
        type: section.type,
        title: question.title || question.content,
      })
    })
  })
  return questions
}

// 获取当前题目在所有题目中的位置
function getCurrentQuestionPosition() {
  const { index, indexs } = getCurrentSelectedIndex()
  const allQuestions = getAllQuestions()
  const currentKey = `${index}_${indexs}`
  const position = allQuestions.findIndex((q: any) => q.key === currentKey)
  return Math.max(position, 0)
}

// 比较两个对象是否相等
function isEqual(obj1: any, obj2: any) {
  return JSON.stringify(obj1) === JSON.stringify(obj2)
}

// 跳转到指定位置的题目
function jumpToQuestion(position: number) {
  const allQuestions = getAllQuestions()
  if (position < 0 || position >= allQuestions.length)
    return

  const targetQuestion = allQuestions[position]
  const key = targetQuestion.key

  // 设置选中状态
  contentItemsStatus.value = {}
  contentItemsStatus.value[key] = true

  // 更新当前题目的答案显示状态
  updateCurrentAnswerDisplay()
}

// 上一题
async function goToPreviousQuestion() {
  // 先提交当前题目的答案
  await submitCurrentQuestionAnswer()

  const currentPosition = getCurrentQuestionPosition()
  if (currentPosition > 0) {
    jumpToQuestion(currentPosition - 1)
  }
}

// 提交当前题目答案
async function submitCurrentQuestionAnswer() {
  const { index, indexs } = getCurrentSelectedIndex()

  const question = list.value[index ?? 0]?.data[indexs ?? 0]
  const key = `${index}_${indexs}`
  const answer = answerStatus.value[key]

  // 检查题目是否已作答
  if (!isQuestionAnswered(index ?? 0, indexs ?? 0)) {
    return
  }

  // 检查答案是否变化
  const previousAnswer = previousAnswerStatus.value[key]
  if (isEqual(answer, previousAnswer)) {
    // 答案没有变化，直接返回，不调用接口
    return
  }

  // 准备提交参数
  const submitData = {
    examId: +examId,
    paperQuestionId: question?.paperQuestionId,
    userAnswer: '',
    participantId,
  }

  // 根据题目类型和答案类型格式化userAnswer
  switch (answer?.type) {
    case 'essay': {
      // 简答题：直接使用字符串
      submitData.userAnswer = answer.answer

      break
    }
    case 'fill_blank': {
      // 填空题：直接使用数组
      submitData.userAnswer = JSON.stringify(answer.answers)

      break
    }
    case 'multiple': {
      // 多选题：转换为索引数组，如 [0, 1]
      const optionIndexes = answer.answers.map(
        (value: string) => Number.parseInt(value) - 1,
      )
      submitData.userAnswer = JSON.stringify(optionIndexes)

      break
    }
    case 'single': {
      // 单选题：转换为索引数组，如 [0]
      // 注意：接口接收的是选项索引，而当前存储的是选项值（字符串形式的数字，如 "1"）
      const optionIndex = Number.parseInt(answer.answer) - 1
      submitData.userAnswer = JSON.stringify([optionIndex])

      break
    }
    // No default
  }

  // 调用接口提交答案
  try {
    await addAnswerResult(submitData)
    // 更新历史答案状态
    if (!previousAnswerStatus.value) {
      previousAnswerStatus.value = {}
    }
    // previousAnswerStatus.value[key] = JSON.parse(JSON.stringify(answer));
    previousAnswerStatus.value[key] = structuredClone(answer)
  }
  catch (error) {
    console.error('提交答案失败:', error)
    // 可以在这里添加错误处理逻辑，如提示用户
  }
}

// 下一题
async function goToNextQuestion() {
  // 先提交当前题目的答案
  await submitCurrentQuestionAnswer()

  // 然后切换到下一题
  const allQuestions = getAllQuestions()
  const currentPosition = getCurrentQuestionPosition()
  if (currentPosition < allQuestions.length - 1) {
    jumpToQuestion(currentPosition + 1)
  }
}

// 初始化当前题目显示状态
updateCurrentAnswerDisplay()
</script>

<template>
  <view class="examcontent_box">
    <view class="examcontent_remainingtime_submit">
      <view class="examcontent_remainingtime">
        剩余时间：<span>{{ formatTime(remainingTime) }}</span>
      </view>
      <view class="examcontent_submit" @tap="handleTimeUp">
        提交考试
      </view>
    </view>
    <view class="examcontent_title">
      {{ getCurrentQuestionTitle() }}
    </view>
    <view class="examcontent_question">
      <view class="examcontent_question_title">
        <span>{{ `${getCurrentQuestionContent().num}.` }}</span>
        <div
          class="question-content"
          v-html="getCurrentQuestionContent().content"
        />
      </view>
      <!-- <view
        v-if="currentTitle?.SubTitle?.isimgs"
        class="examcontent_question_imgs"
      >
        <image
          :src="currentTitle?.SubTitle?.isimgs"
          class="examcontent_question_imgs_img"
        />
      </view> -->
      <view class="examcontent_question_item">
        <view class="examcontent_question_items">
          <template v-if="isSingleChoice()">
            <wd-radio-group
              v-model="currentSingleChoiceAnswer"
              style="
                display: flex;
                flex-direction: column;
                gap: 80rpx;
                align-items: flex-start;
              "
              shape="dot"
              inline
            >
              <wd-radio
                v-for="(option, index) in getCurrentQuestionOptions()"
                :key="index"
                :value="String(+index + 1)"
              >
                <span class="option-prefix">
                  {{ String.fromCodePoint(65 + +index) }}.
                </span>
                <span v-html="option" />
              </wd-radio>
            </wd-radio-group>
          </template>
          <template v-else-if="!isSingleChoice() && !isFillBlank() && !isEssayQuestion()">
            <wd-checkbox
              v-for="(option, index) in getCurrentQuestionOptions()"
              :key="index"
              v-model="currentMultipleChoiceAnswers"
              shape="square"
              :value="String(+index + 1)"
            >
              <span class="option-prefix">
                {{ String.fromCodePoint(65 + +index) }}.
              </span>
              <span v-html="option" />
            </wd-checkbox>
          </template>
          <!-- <template v-else-if="currentTitle.MainTitle?.includes('判断题')">
            <wd-radio-group
              v-model="currentTitle.SubTitle.value"
              style="
                display: flex;
                flex-direction: column;
                gap: 80rpx;
                align-items: flex-start;
              "
              shape="dot"
              inline
            >
              <wd-radio
                v-for="value in currentTitle.SubTitle.options"
                :value="value.value"
              >
                {{ value.label }}
              </wd-radio>
            </wd-radio-group>
          </template> -->
          <template v-else-if="isFillBlank()">
            <view class="examcontent_question_blanks">
              <view
                v-for="(answer, index) in currentFillBlankAnswers"
                :key="index"
                class="examcontent_question_blank_item"
              >
                <text class="examcontent_question_blank_label">
                  {{
                    `填空${+index + 1}: `
                  }}
                </text>
                <wd-input
                  v-model="currentFillBlankAnswers[index]"
                  placeholder="请输入"
                  class="examcontent_question_blank_input"
                  @input="handleFillBlankChange"
                />
              </view>
            </view>
          </template>
          <template v-else-if="isEssayQuestion()">
            <view class="examcontent_question_answer">
              <text class="examcontent_question_answer_title">请作答：</text>
              <wd-textarea
                v-model="currentEssayAnswer"
                placeholder="请输入答案"
                rows="4"
                class="examcontent_question_answer_textarea"
                @input="handleEssayChange"
              />
            </view>
          </template>
        </view>
      </view>
    </view>
    <view class="bottom_button">
      <view class="bottom_button_item choose_item" @click="showItems = true">
        <view v-for="value in 3" :key="value" class="choose_item_line" />
      </view>
      <view
        class="bottom_button_item"
        style="flex: 1"
        :class="{ disabled: isFirstQuestion }"
        @click="goToPreviousQuestion"
      >
        上一题
      </view>
      <view
        class="bottom_button_item"
        style="flex: 1"
        :class="{ disabled: isLastQuestion }"
        @click="goToNextQuestion"
      >
        下一题
      </view>
    </view>
    <wd-popup
      v-model="showItems"
      position="bottom"
      custom-style="height: 600px;"
      closable
      @close="showItems = false"
    >
      <view class="popup-header">
        <text class="popup-title">题目总览</text>
        <!-- <view class="popup-close" @click="showItems = false">
          <view class="close-icon" />
        </view> -->
      </view>
      <view class="popup-content">
        <view
          v-for="(item, index) in list"
          :key="index"
          class="question-section"
        >
          <view class="question-section-header">
            <text class="question-section-title">{{ item.type }}</text>
            <text class="question-section-info">
              总 {{ item.data.length }} 题/共
              {{ item.score }}
              分
            </text>
          </view>
          <view class="question-numbers">
            <view
              v-for="(items, indexs) in item.data"
              :key="indexs"
              class="question-number"
              :class="{
                tapactive: contentItemsStatus[`${index}_${indexs}`],
                done: isQuestionAnswered(+index, +indexs),
              }"
              @tap="contentItemsClick(+index, +indexs)"
            >
              {{ +indexs + 1 }}
            </view>
          </view>
        </view>
        <!-- <view
          v-for="value in list.filter((item) => item.type.includes('多选题'))"
          :key="value.type"
          class="question-section"
        >
          <view class="question-section-header">
            <text class="question-section-title">{{ value.type }}</text>
            <text class="question-section-info">
              总 {{ value.titlelist.length }} 题/共
              {{ value.titlelist.reduce((pre, cur) => pre + cur.score, 0) }}
              分
            </text>
          </view>
          <view class="question-numbers">
            <view
              v-for="(item, index) in value.titlelist"
              :key="index"
              class="question-number"
              :class="{
                tapactive: activeIndex === `${value.type}-${index}`,
                done: isDone(item),
              }"
              @tap="handleActive(value, index)"
            >
              {{ index + 1 }}
            </view>
          </view>
        </view>
        <view
          v-for="value in list.filter((item) => item.type.includes('判断题'))"
          :key="value.type"
          class="question-section"
        >
          <view class="question-section-header">
            <text class="question-section-title">{{ value.type }}</text>
            <text class="question-section-info">
              总 {{ value.titlelist.length }} 题/共
              {{ value.titlelist.reduce((pre, cur) => pre + cur.score, 0) }}
              分
            </text>
          </view>
          <view class="question-numbers">
            <view
              v-for="(item, index) in value.titlelist"
              :key="index"
              class="question-number"
              :class="{
                tapactive: activeIndex === `${value.type}-${index}`,
                done: isDone(item),
              }"
              @tap="handleActive(value, index)"
            >
              {{ index + 1 }}
            </view>
          </view>
        </view>
        <view
          v-for="value in list.filter((item) => item.type.includes('填空题'))"
          :key="value.type"
          class="question-section"
        >
          <view class="question-section-header">
            <text class="question-section-title">{{ value.type }}</text>
            <text class="question-section-info">
              总 {{ value.titlelist.length }} 题/共
              {{ value.titlelist.reduce((pre, cur) => pre + cur.score, 0) }}
              分
            </text>
          </view>
          <view class="question-numbers">
            <view
              v-for="(item, index) in value.titlelist"
              :key="index"
              class="question-number"
              :class="{
                tapactive: activeIndex === `${value.type}-${index}`,
                done: isDone(item),
              }"
              @tap="handleActive(value, index)"
            >
              {{ index + 1 }}
            </view>
          </view>
        </view>
        <view
          v-for="value in list.filter((item) => item.type.includes('简答题'))"
          :key="value.type"
          class="question-section"
        >
          <view class="question-section-header">
            <text class="question-section-title">{{ value.type }}</text>
            <text class="question-section-info">
              总 {{ value.titlelist.length }} 题/共
              {{ value.titlelist.reduce((pre, cur) => pre + cur.score, 0) }}
              分
            </text>
          </view>
          <view class="question-numbers">
            <view
              v-for="(item, index) in value.titlelist"
              :key="index"
              class="question-number"
              :class="{
                tapactive: activeIndex === `${value.type}-${index}`,
                done: isDone(item),
              }"
              @tap="handleActive(value, index)"
            >
              {{ index + 1 }}
            </view>
          </view>
        </view> -->
      </view>
    </wd-popup>
    <wd-message-box />
  </view>
</template>

<style scoped lang="scss">
html,
body {
  overflow: hidden;
}
:deep() {
  .wd-message-box {
    .custom-shadow {
      border-radius: 8rpx;
      background-color: #215acd;
      color: #ffffff;
    }
    .cancel-button {
      border-radius: 8rpx;
      background-color: #ffffff;
      color: #31373d;
      border: 1px solid #d4d6d9;
    }
  }
}
.examcontent_box {
  height: calc(100vh - 88rpx);
  display: flex;
  flex-direction: column;
  padding: 32rpx 40rpx;
  box-sizing: border-box;
  .examcontent_remainingtime_submit {
    height: 64rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .examcontent_remainingtime {
      font-weight: 400;
      font-style: 55 Regular;
      font-size: 32rpx;
      color: #86909c;
    }
    .examcontent_submit {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100%;
      width: 188rpx;
      border: 1px solid #d4d6d9;
      border-radius: 8rpx;
      font-weight: 400;
      font-style: 55 Regular;
      font-size: 28rpx;
      letter-spacing: 4%;
      color: #31373d;
    }
  }
  .examcontent_title {
    margin-top: 48rpx;
    margin-bottom: 104rpx;
    font-weight: 500;
    font-style: 65 Medium;
    font-size: 36rpx;
    letter-spacing: 4%;
    color: #31373d;
  }
  .examcontent_question {
    // height: 72%;
    flex: 1;
    width: 100%;
    display: flex;
    flex-direction: column;
    gap: 98rpx;
    .examcontent_question_title {
      display: flex;
      align-items: flex-start;
      font-weight: 400;
      font-style: 55 Regular;
      font-size: 32rpx;
      leading-trim: NONE;
      color: #31373d;
      .question-content {
        flex: 1;
      }
    }
    .examcontent_question_imgs {
      width: 100%;
      height: 260rpx;
      // margin-bottom: 32rpx;
      .examcontent_question_imgs_img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
    .examcontent_question_item {
      width: 100%;

      .examcontent_question_items {
        display: flex;
        flex-direction: column;
        gap: 80rpx;
        .examcontent_question_items_text {
          font-weight: 400;
          font-style: 55 Regular;
          font-size: 28rpx;
          color: #1f1f1f;
        }
        .examcontent_question_blanks {
          display: flex;
          flex-direction: column;
          gap: 40rpx;
          .examcontent_question_blank_item {
            display: flex;
            align-items: center;
            gap: 20rpx;
            .examcontent_question_blank_label {
              font-size: 28rpx;
              color: #31373d;
              white-space: nowrap;
              margin-right: 20rpx;
            }
            .examcontent_question_blank_input {
              height: 64rpx;
              flex: 1;
              border: 1px solid #d4d6d9;
              border-radius: 8rpx;
              padding: 20rpx;
              font-size: 28rpx;
              box-sizing: border-box;
              display: flex;
              align-items: center;
            }
          }
        }
        .examcontent_question_answer {
          width: 100%;
          .examcontent_question_answer_title {
            font-weight: 400;
            font-style: 55 Regular;
            font-size: 28rpx;
            color: #1f1f1f;
          }
          .examcontent_question_answer_textarea {
            margin-top: 18rpx;
            width: 94%;
            border: 1px solid #d4d6d9;
            border-radius: 8rpx;
            padding: 20rpx;
            font-size: 28rpx;
            min-height: 200rpx;
            resize: vertical;
          }
        }
      }
    }
  }
  .bottom_button {
    // margin-top: auto;
    width: 100%;
    height: 80rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 32rpx;
    .choose_item {
      width: 80rpx;
      padding: 20rpx;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      gap: 12rpx;
      .choose_item_line {
        width: 100%;
        height: 4rpx;
        background-color: #353566;
      }
    }
    .bottom_button_item {
      height: 100%;
      border: 1px solid #d4d6d9;
      border-radius: 8rpx;
      font-weight: 400;
      font-size: 32rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #31373d;
      cursor: pointer;
      transition: all 0.3s ease;
      &.disabled {
        background-color: #f5f5f5;
        color: #9ca3af;
        border-color: #e5e7eb;
        cursor: not-allowed;
      }
    }
  }
  .popup-header {
    padding: 24rpx;
    // border-bottom: 1px solid #e5e7eb;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    .popup-title {
      font-weight: 500;
      font-style: 65 Medium;
      font-size: 32rpx;
      color: #31373d;
    }
    .popup-close {
      position: absolute;
      right: 24rpx;
      top: 50%;
      transform: translateY(-50%);
      width: 40rpx;
      height: 40rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      .close-icon {
        width: 36rpx;
        height: 36rpx;
        position: relative;
        &::before,
        &::after {
          content: '';
          position: absolute;
          width: 100%;
          height: 2rpx;
          background-color: #020917;
          top: 50%;
          left: 0;
        }
        &::before {
          transform: rotate(45deg);
        }
        &::after {
          transform: rotate(-45deg);
        }
      }
    }
  }
  .popup-content {
    padding: 24rpx;
    .question-section {
      margin-bottom: 64rpx;
      &:last-child {
        margin-bottom: 0;
      }
      .question-section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 56rpx;
        .question-section-title {
          font-weight: 500;
          font-size: 32rpx;
          color: #31373d;
        }
        .question-section-info {
          font-weight: 500;
          font-size: 32rpx;
          color: #31373d;
        }
      }
      .question-numbers {
        display: flex;
        flex-wrap: wrap;
        gap: 16rpx;
        margin-bottom: 16rpx;
        &:last-child {
          margin-bottom: 0;
        }
        .question-number {
          width: 96rpx;
          height: 96rpx;
          border: 1px solid #d4d6d9;
          border-radius: 9.6rpx;
          display: flex;
          justify-content: center;
          align-items: center;
          font-size: 33.6rpx;
          color: #000000;
          &.done {
            background-color: #215acd;
            color: #ffffff;
            border-color: #215acd;
          }
        }
        .tapactive {
          background-color: #ebf3ff;
          color: #31373d;
        }
      }
    }
  }
}
</style>
