<template>
  <div class="exam-container">
    <!-- 左侧栏 -->
    <div class="sidebar">
      <h2>{{ examTitle }}</h2>
      <p>总分：{{ totalScore }} &nbsp; 时长：{{ duration }}</p>
      <p class="time-remaining">剩余时间<br /><span>{{ formattedTime }}</span></p>
      <button class="submit-button" @click="submitExam" :disabled="loading">提交试卷</button>
      <div class="question-navigation">
        <div
            v-for="(question, index) in questions"
            :key="question.id"
            class="question-box"
            :class="{ answered: answers[question.id]?.length > 0 }"
            @click="scrollToQuestion(index)"
        >
          {{ index + 1 }}
        </div>
      </div>
    </div>

    <!-- 主内容 -->
    <div class="main-content" v-if="!loading && questions.length > 0">
      <div class="question" v-for="(question, index) in questions" :key="question.id" :ref="'question-' + question.id">
        <p>{{ index + 1 }}. {{ question.text }}
          <span class="score" v-if="question.score">（{{ question.score }} 分）</span>
          <span class="type" v-if="question.type">（{{ question.type }}）</span>
        </p>
        <div class="options">
          <!-- 单选题 -->
          <template v-if="question.type === '单选题'">
            <label v-for="(option, optIndex) in question.options" :key="optIndex">
              <input
                  type="radio"
                  :name="'question-' + question.id"
                  :value="option.value"
                  v-model="answers[question.id]"
              />
              {{ option.label }}
            </label>
          </template>

          <!-- 多选题 -->
          <template v-else-if="question.type === '多选题'">
            <label v-for="(option, optIndex) in question.options" :key="optIndex">
              <input
                  type="checkbox"
                  :value="option.value"
                  v-model="answers[question.id]"
              />
              {{ option.label }}
            </label>
          </template>

          <!-- 判断题 -->
          <template v-else-if="question.type === '判断题'">
            <label>
              <input
                  type="radio"
                  :name="'question-' + question.id"
                  value="T"
                  v-model="answers[question.id]"
              />
              正确
            </label>
            <label>
              <input
                  type="radio"
                  :name="'question-' + question.id"
                  value="F"
                  v-model="answers[question.id]"
              />
              错误
            </label>
          </template>

          <!-- 解答题和填空题 -->
          <template v-else>
            <textarea
                v-model="answers[question.id]"
                placeholder="请填写答案"
                rows="3"
            ></textarea>
          </template>
        </div>
      </div>
    </div>

    <!-- 加载中提示 -->
    <div class="loading" v-if="loading">
      正在加载试题，请稍候...
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "ExamPaper",
  data() {
    return {
      examTitle: "考试中...",
      totalScore: 0,
      duration: "未知",
      remainingTime: 5 * 60,
      questions: [],
      answers: {},
      loading: true,
      examId: null,
      timer: null,
      refreshTimer: null,
      userId:"",
    };
  },
  computed: {
    formattedTime() {
      const minutes = Math.floor(this.remainingTime / 60);
      const seconds = this.remainingTime % 60;
      return `${minutes}分${seconds}秒`;
    },
  },
  watch: {
    questions(newVal) {
      if (newVal.length > 0) {
        this.startCountdown();
        if (this.refreshTimer) clearTimeout(this.refreshTimer);
      }
    },
  },
  methods: {
    async fetchQuestions() {
      try {
        const token = this.$store.state.tokens[this.userId];
        if (!token) {
          alert("用户未登录，请重新登录！");
          this.$router.push("/login");
          return;
        }

        const res = await axios.get('http://localhost:8080/student/examPaper/selectByUserId', {
          headers: { Authorization: `Bearer ${token}` },
        });

        if (res.data && res.data.data && res.data.data.grade) {
          const grade = res.data.data.grade;

          const examRes = await axios.get(`http://localhost:8080/student/homepage/task_paper`, {
            params: { name: this.name, subject: this.subject, grade },
            headers: { Authorization: `Bearer ${token}` },
          });

          if (examRes.data.code === 200) {
            const { name, list } = examRes.data.data;
            this.examTitle = name;
            this.totalScore = examRes.data.data.sumscore;
            this.duration = this.time;
            this.remainingTime = this.time * 60;
            this.questions = list.map((item) => ({
              id: item.id,
              text: item.content,
              options: item.chance
                  ? item.chance.map((opt) => ({ value: opt.label, label: opt.text }))
                  : [],
              score: item.score,
              type: item.type,
            }));

            // 初始化 answers
            this.questions.forEach((question) => {
              if (question.type === "多选题") {
                this.answers[question.id] = [];
              } else {
                this.answers[question.id] = "";
              }
            });
          } else {
            alert("加载试题失败：" + examRes.data.msg);
            this.$router.push('/login'); // 引导用户重新登录
          }
        } else {
          alert("返回数据缺少年级信息！");
          this.$router.push('/student/exam'); // 引导用户重新登录
        }
      } catch (error) {
        console.error("加载试题时发生错误：", error);
        alert("加载试题失败，请稍后再试！");
      } finally {
        this.loading = false;
        this.startRefreshTimer(); // 确保初始化完成后再调用
      }
    },

    scrollToQuestion(index) {
      const questionId = this.questions[index].id;
      const questionElement = Array.isArray(this.$refs[`question-${questionId}`])
          ? this.$refs[`question-${questionId}`][0]
          : this.$refs[`question-${questionId}`];

      if (questionElement && questionElement.scrollIntoView) {
        questionElement.scrollIntoView({ behavior: "smooth", block: "start" });
      } else {
        console.warn(`Element for question ${index + 1} not found or invalid.`);
      }
    },

    startCountdown() {
      this.timer = setInterval(() => {
        if (this.remainingTime <= 0) {
          clearInterval(this.timer);
          alert("时间到！");
          this.submitExam();
        } else {
          this.remainingTime--;
        }
      }, 1000);
    },

    async submitExam() {
      try {
        const token = this.$store.state.tokens[this.userId];
        if (!token) {
          alert("用户未登录，请重新登录！");
          this.$router.push("/login");
          return;
        }

        // 检查是否有未作答的题目
        const unanswered = this.questions.filter(
            (q) => !this.answers[q.id] || (typeof this.answers[q.id] === 'string' && this.answers[q.id].trim() === "")
        );

        if (unanswered.length > 0) {
          const confirmSubmit = confirm(`还有 ${unanswered.length} 道题未作答，是否仍然提交试卷？`);
          if (!confirmSubmit) {
            return; // 用户选择不提交，退出提交操作
          }
        }

        const answerList = Object.keys(this.answers).map((questionId) => ({
          id: Number(questionId),
          answer: Array.isArray(this.answers[questionId])
              ? this.answers[questionId].join("")
              : this.answers[questionId].trim(),
        }));

        const response = await axios.post(
            "http://localhost:8080/student/homepage/task_answer",
            {
              testid: this.examId,
              list: answerList,
              time: Math.round(Math.max(this.duration * 60 - this.remainingTime, 0) / 60),
            },
            { headers: { Authorization: `Bearer ${token}` } }
        );

        const res = await axios.get(
            `http://localhost:8080/student/homepage/task_answerDisplay`,{
              params:{id:this.examId},
              headers: { Authorization: `Bearer ${token}` }
            }
        );
        if(res.data.code === 200){
          console.log('客观题已批改');
        }else{
          alert("批改系统异常");
        }
        if (response.data.code === 200) {
          alert("考试提交成功！");
          this.$router.go(-1);
          // this.$router.push({
          //   path: '/student/exam',
          //   query: { userId: this.userId }
          // });
        } else {
          alert("提交失败：" + response.data.msg);
        }
      } catch (error) {
        console.error("提交考试时发生错误：", error);
        alert("提交试卷失败，请稍后再试！");
      }
    },
    startRefreshTimer() {
      this.refreshTimer = setTimeout(() => {
        if (!this.questions.length) {
          alert("加载超时，页面将刷新以重试...");
          location.reload(); // 刷新页面
        }
      }, 10000); // 10 秒超时
    },
  },
  created() {
    this.userId = this.$route.query.userId;
    this.subject = this.$route.query.subject;
    this.name = this.$route.query.name;
    this.examId = this.$route.query.id;
    this.time = this.$route.query.time;

    if (!this.subject || !this.name) {
      alert("未获取到试卷，请重新选择！");
      this.$router.push("/exam");
      return;
    }

    this.fetchQuestions();
    this.startRefreshTimer();
  },
  beforeDestroy() {
    if (this.timer) clearInterval(this.timer);
    if (this.refreshTimer) clearTimeout(this.refreshTimer);
  },
};
</script>

<style scoped>
.exam-container {
  display: flex;
  height: 100vh;
  background-color: #f4f6f9;
  padding: 0;
  position: relative;
}

.sidebar {
  width: 20%;
  padding: 20px;
  background-color: #ffffff;
  box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
  text-align: center;
  position: sticky;
  top: 0;
  height: 100vh;
}

.sidebar h2 {
  font-size: 20px;
  margin-bottom: 20px;
}

.time-remaining span {
  color: red;
  font-size: 24px;
}

.submit-button {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.submit-button:hover {
  background-color: #0056b3;
}

.main-content {
  flex: 1;
  padding: 30px;
  background-color: #ffffff;
  overflow-y: auto;
  height: 100vh;
  box-sizing: border-box;
}

.question {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e0e0e0;
}

.options input[type="radio"] {
  margin-right: 10px;
}

textarea {
  width: 100%;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 10px;
  font-size: 1.2rem; /* 调整字体大小 */
  line-height: 1.5; /* 调整行高 */
}

.question p {
  font-size: 2.2rem; /* 调整题目字体大小 */
  line-height: 1.5;
  margin-bottom: 20px;
}

.options label {
  font-size: 1.4rem; /* 调整选项字体大小 */
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}


.loading {
  text-align: center;
  font-size: 18px;
  color: #666;
  margin-top: 50px;
}

.score {
  font-size: 1.4rem;
  color: #999;
  margin-left: 10px;
}

/* Sidebar question navigation */
.question-navigation {
  margin-top: 20px;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.question-box {
  width: 40px;
  height: 40px;
  margin: 5px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f0f0f0;
  border-radius: 5px;
  cursor: pointer;
  font-size: 1.2rem;
}

.question-box:hover {
  background-color: #007bff;
  color: white;
}

.question-box.answered {
  background-color: red; /* 已做题目的背景色 */
  color: white; /* 文字颜色 */
}
</style>
