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

// @ts-ignore
import { Page } from '@vben/common-ui';
// @ts-ignore
import { useTabs } from '@vben/hooks';

import { ElLoading, ElMessage } from 'element-plus';

// @ts-ignore
import { addAnswerResult } from '#/api/exam/exam/answer';
// @ts-ignore
import { examPaperDetail } from '#/api/exam/exam/exam';
// @ts-ignore
import { endExam } from '#/api/exam/exam/participant';

const { closeCurrentTab } = useTabs();
const router = useRouter();
const route = useRoute();
const examId = route.params.id || 0;
const participantId = Number(route.query.pid || 0);

// 存储键，用于标识当前考试的答题数据
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); // 定时器引用

// 保存答案到 storage
const 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 加载答案
const 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);
  }
};

// 初始化倒计时
const 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;
      ElMessage({
        message: '时间到，自动交卷',
        type: 'warning',
      });
      handleTimeUp();
      return;
    }
  }

  startCountdown();
};

// 开始倒计时
const startCountdown = () => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value);
  }

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

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

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

// 格式化时间显示
const 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')}`;
};

// 时间到处理
const handleTimeUp = async () => {
  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
      router.replace({
        name: 'Examcomplet',
        params: {
          id: examId,
        },
        query: {
          pid: participantId,
        },
      });
    } else {
      router.replace({
        name: 'ExamCompleted',
        params: {
          id: examId,
        },
        query: {
          pid: participantId,
        },
      });
    }

    // if (route.path === '/startexamin') {
    //   router.replace({
    //     name: 'ExamCompleted',
    //     params: {
    //       id: examId,
    //     },
    //     query: {
    //       pid: participantId,
    //     },
    //   });
    // } else {
    //   router.replace({
    //     name: 'ExamCompleted',
    //     params: {
    //       id: examId,
    //     },
    //     query: {
    //       pid: participantId,
    //     },
    //   });
    // }
  } catch (error) {
    console.error('交卷失败:', error);
    // 无论成功失败，都关闭loading
    ElLoading.service().close();
  }
};

const examInfo = ref({}) as any;

const getExamPaperDetail = async () => {
  const res = await examPaperDetail(+examId);
  examInfo.value = res;

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

    // @ts-ignore:按大题索引分组题目
    // 预计算最大索引，避免数组动态扩展
    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 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;

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

// 获取当前选中的题目索引（使用计算属性优化性能）
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;

// 判断是否为单选题（包含单选和判断题）
const 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';
};

// 判断是否为填空题
const 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';
};

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

// 判断题目是否已答题
const 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()))
  );
};

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

// 获取当前题目内容
const 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: question?.title || '',
  };

  // if (type.includes('填空')) {
  //   return `${safeIndexs + 1}. ${question?.content || '这是本题的题目，请填写'}`;
  // }

  // return `${safeIndexs + 1}. ${question?.title || '这是本题的题目，请选择'}`;
};

// 获取当前题目选项
const 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'];
};

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

// 获取简答题描述
// const getCurrentQuestionDescription = () => {
//   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 '';
// };

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

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

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

// 处理简答题答案变化
const 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();
// };

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

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

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

// 更新当前题目的答案显示状态
const 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() ? '' : '';
    }
  }
};

const contentitemsclick = async (index: number, indexs: number) => {
  // 先提交当前题目的答案
  await submitCurrentQuestionAnswer();

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

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

// 获取所有题目的扁平化列表（用于导航）
const 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;
};

// 获取当前题目在所有题目中的位置
const 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);
};

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

// 跳转到指定位置的题目
const 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();
};

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

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

// 提交当前题目答案
const submitCurrentQuestionAnswer = async () => {
  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);
    // 可以在这里添加错误处理逻辑，如提示用户
  }
};

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

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

// 初始化当前题目显示状态
updateCurrentAnswerDisplay();
</script>
<template>
  <Page>
    <div class="startexamin_box">
      <div class="left">
        <div class="title">{{ getCurrentQuestionTitle() }}</div>
        <div class="examquestions">
          <div class="examquestions_item_title">
            <span>{{ `${getCurrentQuestionContent().num}.` }}</span>
            <div
              v-html="getCurrentQuestionContent().content"
              class="question-content"
            ></div>
            <!-- <div
              class="WindPowericon"
              @click="toggleQuestionMark"
              :class="{
                marked: isQuestionMarked(
                  getCurrentSelectedIndex().index || 0,
                  getCurrentSelectedIndex().indexs || 0,
                ),
              }"
            >
              <el-icon><CollectionTag /></el-icon>
            </div> -->
          </div>
          <el-radio-group
            v-if="isSingleChoice()"
            v-model="currentSingleChoiceAnswer"
            class="vertical-radio"
            @change="handleSingleChoiceChange"
          >
            <el-radio
              v-for="(option, index) in getCurrentQuestionOptions()"
              :key="index"
              :value="String(+index + 1)"
              size="large"
            >
              <!--动态生成序号前缀和选项内容-->
              <span class="option-prefix">
                {{ String.fromCodePoint(65 + +index) }}.
              </span>
              <span v-html="option"></span>
            </el-radio>
          </el-radio-group>

          <el-checkbox-group
            v-if="!isSingleChoice() && !isFillBlank() && !isEssayQuestion()"
            v-model="currentMultipleChoiceAnswers"
            class="vertical-checkbox"
            @change="handleMultipleChoiceChange"
          >
            <el-checkbox
              v-for="(option, index) in getCurrentQuestionOptions()"
              :key="index"
              :value="String(+index + 1)"
              size="large"
            >
              <!--动态生成序号前缀和选项内容-->
              <span class="option-prefix">
                {{ String.fromCodePoint(65 + +index) }}.
              </span>
              <span v-html="option"></span>
            </el-checkbox>
          </el-checkbox-group>

          <div v-if="isFillBlank()" class="fill-blank-inputs">
            <!-- <div class="fill-blank-question">
              {{ getCurrentQuestionContent() }}
            </div> -->
            <div class="fill-blank-inputs-container">
              <div
                v-for="(answer, index) in currentFillBlankAnswers"
                :key="index"
                class="fill-blank-item"
              >
                <label class="fill-blank-label"> 第{{ +index + 1 }}空： </label>
                <el-input
                  v-model="currentFillBlankAnswers[index]"
                  placeholder="请输入答案"
                  size="large"
                  @input="handleFillBlankChange"
                />
              </div>
            </div>
          </div>

          <div v-if="isEssayQuestion()" class="essay-question-input">
            <div class="essay-question-description">
              <!-- {{ `${getCurrentQuestionDescription()}：` }} -->
              请作答：
            </div>
            <el-input
              v-model="currentEssayAnswer"
              type="textarea"
              :rows="8"
              placeholder="请在此输入您的答案..."
              size="large"
              @input="handleEssayChange"
              class="essay-textarea px-4 py-1"
            />
          </div>
        </div>
      </div>
      <div class="rigth">
        <div class="rigth_top">
          <div class="rigth_top_title">{{ examInfo.examName }}</div>
          <div class="rigth_top_countdown">
            <span class="rigth_top_countdown_title">剩余时间</span>
            <span class="rigth_top_countdown_time">{{
              formatTime(remainingTime)
            }}</span>
            <el-button class="rigth_top_countdown_Submit" @click="handleTimeUp">
              提前交卷
            </el-button>
          </div>
          <div class="rigth_top_previous_next">
            <el-button
              class="rigth_top_previousbtn"
              @click="goToPreviousQuestion"
            >
              上一题
            </el-button>
            <el-button
              class="rigth_top_nextbtn"
              type="primary"
              @click="goToNextQuestion"
            >
              下一题
            </el-button>
          </div>
        </div>
        <div class="rigth_main">
          <div
            class="rigth_main_content"
            v-for="(item, index) in list"
            :key="index"
          >
            <div class="rigth_main_content_title">
              <text>{{ item.type }}</text>
              <text>总 {{ item.data.length }} 题/共 {{ item.score }} 分</text>
            </div>
            <div class="rigth_main_content_item">
              <div
                v-for="(items, indexs) in item.data"
                :key="indexs"
                class="rigth_main_content_items"
                :class="[
                  {
                    selectedactive: contentitemsstatus[`${index}_${indexs}`],
                    answered: isQuestionAnswered(+index, +indexs),
                    marked: isQuestionMarked(+index, +indexs),
                  },
                ]"
                @click="contentitemsclick(+index, +indexs)"
              >
                {{ +indexs + 1 }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </Page>
</template>
<style lang="scss" scoped>
.startexamin_box {
  width: 100%;
  height: 796px;
  display: flex;
  justify-content: space-between;
  gap: 36px;
  overflow: hidden;
  .left {
    flex: 1;
    // border: 1px solid red;
    height: 100%;
    background-color: #fff;
    .title {
      width: 100%;
      height: 80px;
      background-color: #f7f9fa;
      font-size: 18px;
      font-weight: 500;
      line-height: 80px;
      box-sizing: border-box;
      padding-left: 24px;
    }
    .examquestions {
      box-sizing: border-box;
      padding-top: 40px;
      padding-left: 24px;

      .examquestions_item_title {
        display: flex;
        align-items: flex-start;
        font-size: 20px;
        font-weight: 400;
        margin-bottom: 24px;
        box-sizing: border-box;
        padding-right: 24px;

        .question-content {
          flex: 1;
          margin-left: 8px;
        }

        .WindPowericon {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          background-color: #fff;
          border: 1px solid #d4d6d9;
          display: flex;
          justify-content: center;
          align-items: center;
          // color: #faad14;
          font-size: 20px;
        }

        .WindPowericon.marked {
          color: #faad14;
          border-color: #faad14;
        }
      }
      .vertical-radio,
      .vertical-checkbox {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
      }

      :deep(.el-radio__label),
      :deep(.el-checkbox__label) {
        margin-left: 8px;
        display: flex;
        align-items: flex-start;
      }

      .option-prefix {
        margin-right: 4px;
        font-weight: normal;
        white-space: nowrap;
        flex-shrink: 0;
      }

      /* 选项内容容器 */
      :deep(.el-radio__label) span:last-child,
      :deep(.el-checkbox__label) span:last-child {
        flex: 1;
      }

      /* 处理选项内容中的块级元素，确保它们与前缀在同一行开始 */
      :deep(.el-radio__label) span:last-child > :first-child,
      :deep(.el-checkbox__label) span:last-child > :first-child {
        display: inline;
      }

      /* 处理选项内容中的后续块级元素 */
      :deep(.el-radio__label) span:last-child > *,
      :deep(.el-checkbox__label) span:last-child > * {
        margin-top: 0;
        margin-bottom: 0;
      }
      .fill-blank-input {
        width: 100%;
        max-width: 400px;
      }
      .fill-blank-inputs {
        width: 100%;
      }
      .fill-blank-question {
        font-size: 18px;
        line-height: 1.6;
        margin-bottom: 24px;
        color: #333;
      }
      .fill-blank-inputs-container {
        display: flex;
        flex-direction: column;
        gap: 16px;
      }
      .fill-blank-item {
        display: flex;
        align-items: center;
        gap: 12px;
      }
      .fill-blank-label {
        min-width: 60px;
        font-size: 16px;
        color: #333;
      }
      .fill-blank-item .el-input {
        flex: 1;
        max-width: 300px;
      }
      .essay-question-input {
        width: 100%;
      }
      .essay-question-title {
        font-size: 18px;
        font-weight: 500;
        color: #333;
        margin-bottom: 16px;
        line-height: 1.6;
      }
      .essay-question-description {
        // font-size: 16px;
        // color: #666;
        // margin-bottom: 24px;
        // line-height: 1.5;
        // padding: 16px;
        padding-bottom: 16px;
        // background-color: #f8f9fa;
        // border-radius: 8px;
        // border-left: 4px solid #215ACD;
      }
      .essay-textarea {
        .el-textarea__inner {
          font-size: 16px;
          line-height: 1.6;
          resize: vertical;
        }
      }
    }
  }
  .rigth {
    width: 400px;
    display: flex;
    flex-direction: column;
    gap: 12px;
    .rigth_top {
      background-color: #ffffff;
      width: 100%;
      height: 370px;
      //   margin-bottom: 12px;
      .rigth_top_title {
        font-size: 18px;
        font-weight: 500;
        color: #31373d;
        padding: 31px 0 31px 24px;
      }
      .rigth_top_countdown {
        height: 210px;
        width: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        gap: 32px;
        box-sizing: border-box;
        padding-top: 27px;
        padding-bottom: 32px;
        .rigth_top_countdown_title {
          font-size: 18px;
          font-weight: 500;
          color: #31373d;
        }
        .rigth_top_countdown_time {
          font-size: 28px;
          font-weight: 600;
          color: #eb5e12;
        }
        .rigth_top_countdown_Submit {
          width: 160px;
          height: 40px;
          margin-right: 10px;
        }
        .rigth_top_countdown_Close {
          width: 120px;
          height: 40px;
        }
      }
      .rigth_top_previous_next {
        border-top: 1px solid #e6e8eb;
        // box-sizing: border-box;
        padding: 24px 20px;
        display: flex;
        justify-content: space-between;
        gap: 32px;
        .rigth_top_previousbtn,
        .rigth_top_nextbtn {
          flex: 1;
        }
      }
    }
    .rigth_main {
      flex: 1;
      background-color: #ffffff;
      box-sizing: border-box;
      padding: 16px 24px;
      display: flex;
      flex-direction: column;
      gap: 28px;
      height: 400px;
      //   border: 1px solid red;
      overflow-y: auto;
      .rigth_main_content {
        display: flex;
        flex-direction: column;
        gap: 12px;
        .rigth_main_content_title {
          //   height: 48px;
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-size: 16px;
          font-weight: 500;
        }
        .rigth_main_content_item {
          display: flex;
          flex-wrap: wrap;
          gap: 12px;
          .rigth_main_content_items {
            width: 40px;
            height: 40px;
            border-radius: 4px;
            background-color: #ffffff;
            display: flex;
            justify-content: center;
            align-items: center;
            color: #31373d;
            font-size: 14px;
            font-weight: 400;
            border: 1px solid #d4d6d9;
          }
          .selectedactive {
            background-color: #e2eaf6;
          }
          .answered {
            background-color: #215acd;
            color: white;
          }
          .selectedactive.answered {
            background-color: #215acd;
            color: white;
          }
          .marked {
            color: #fff;
            background-color: #faad14;
          }
          .answered.marked {
            background-color: #215acd;
            color: white;
            border-color: #faad14;
          }
          .selectedactive.answered.marked {
            background-color: #215acd;
            color: white;
            border-color: #faad14;
          }
        }
      }
    }
  }
}
</style>
