<template>
  <el-container style="min-height: 100vh">
    <el-aside
        :width="sideWidth + 'px'"
        style="background-color: rgb(238, 241, 246); box-shadow: 2px 0 6px rgb(0 21 41 / 35%)"
    >
      <Aside :isCollapse="isCollapse" :logoTextShow="logoTextShow" />
    </el-aside>
    <el-container>
      <el-header style="border-bottom: 1px solid #ccc;">
        <Header :collapseBtnClass="collapseBtnClass" :collapse="collapse" />
      </el-header>
      <el-main>
        <!-- 搜索框 -->
        <el-row :gutter="20" class="search-row" style="margin-bottom: 20px;">
          <el-col :span="6">
            <el-input
                v-model="searchKeyword"
                placeholder="按试卷名称查询"
                clearable
                @input="search"
            >
              <template #prepend>
                <i class="el-icon-search"></i>
              </template>
            </el-input>
          </el-col>
        </el-row>

        <!-- 分数表格 -->
        <el-table v-if="!loading" :data="filteredScores" border style="width: 100%">
          <el-table-column label="试卷名称" width="200">
            <template #default="{ row }">
              {{ getTestInfo(row.testid).name }}
            </template>
          </el-table-column>
          <el-table-column label="学科" width="100">
            <template #default="{ row }">
              {{ getTestInfo(row.testid).subject }}
            </template>
          </el-table-column>
          <el-table-column prop="score" label="分数" width="100" />
          <el-table-column prop="time" label="答题时间(分钟)" />

          <!-- 传递点击的 testid 进行后续操作 -->
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button @click="viewTestPaper(row.testid, getTestInfo(row.testid).name)" style="background-color: beige;color:black">查看试卷</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 加载中 -->
        <el-empty v-else description="加载中..." />
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import Header from "@/components/Student/Header.vue";
import Aside from "@/components/Student/Aside.vue";
import axios from "axios";

export default {
  name: "ScoreList",
  components: { Aside, Header },
  data() {
    return {
      isCollapse: false,
      sideWidth: 200,
      logoTextShow: true,
      collapseBtnClass: "el-icon-s-fold",
      searchKeyword: "", // 搜索关键字
      scores: [], // 分数数据列表
      filteredScores: [], // 筛选后的分数数据
      loading: false, // 加载状态
      testInfoMap: {}, // 存储试卷信息的映射
    };
  },
  methods: {
    collapse(){
      //点击收缩按钮触发
      this.isCollapse = !this.isCollapse
      if(this.isCollapse){
        this.sideWidth = 64
        this.collapseBtnClass = 'el-icon-s-unfold'
        this.logoTextShow = false
      }else{
        this.sideWidth = 200
        this.collapseBtnClass = 'el-icon-s-fold'
        this.logoTextShow = true
      }
    },
    async fetchScores() {
      this.loading = true;
      try {
        const token = this.$store.state.tokens[this.userId];
        console.log('token',token);
        if (!token) {
          alert("用户未登录，请重新登录！");
          this.$router.push("/login"); // 跳转到登录页
          return;
        }

        const response = await axios.get(
            "http://localhost:8080/student/homepage/task_score",
            {
              headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
            }
        );

        this.scores = response.data.data || [];
        this.filteredScores = [...this.scores]; // 初始化筛选数据

        // 获取所有需要的试卷信息
        await this.fetchTestInfoForScores();
      } catch (error) {
        console.error("加载失败:", error);
        this.$router.push('/login'); // 引导用户重新登录
      } finally {
        this.loading = false;
      }
    },

    // 获取每个试卷的信息
    async fetchTestInfoForScores() {
      const testIds = this.scores.map((score) => score.testid);
      // 去除重复的 testid
      const uniqueTestIds = [...new Set(testIds)];

      // 对所有 uniqueTestIds 发起请求
      for (let testid of uniqueTestIds) {
        if (!this.testInfoMap[testid]) {
          await this.fetchTestInfo(testid);
        }
      }
    },

    // 获取单个试卷信息
    async fetchTestInfo(testid) {
      try {
        const token = this.$store.state.tokens[this.userId];
        if (!token) {
          alert("用户未登录，请重新登录！");
          this.$router.push("/login"); // 跳转到登录页
          return;
        }
        // 第一步：获取试卷的基本信息
        const response = await axios.get(
            `http://localhost:8080/student/examPaper/examPaperById`,
            {
              params: {id: testid},
              headers: {
                Authorization: `Bearer ${token}`,
                'Content-Type': 'application/json',
              },
            }
        );

        const testInfo = response.data.data;
        if (testInfo) {
          // 将试卷的基本信息存储到 testInfoMap 中
          this.testInfoMap[testid] = testInfo;

        } else {
          console.error("未找到试卷信息", testid);
        }
      } catch (error) {
        console.error("加载失败:", error);
        this.$router.push('/login'); // 引导用户重新登录
      }
    },

    // 通过 testid 获取试卷信息
    getTestInfo(testid) {
      return this.testInfoMap[testid] || {name: '未知', subject: '未知'};
    },

    search() {
      this.filteredScores = this.scores.filter((item) =>
          item.name.toLowerCase().includes(this.searchKeyword.toLowerCase())
      );
    },

    viewTestPaper(testid,name) {
      // 使用 Vue Router 跳转到新页面
      this.$router.push({
        name: 'TestPaperDetail',
        query: { userId: this.userId,id: testid ,name: name} // 传递试卷 ID
      });
    },
  },

  created() {
    this.userId = this.$route.query.userId;
    this.fetchScores(); // 在组件创建时获取数据
  },
};
</script>

<style scoped lang="scss">
.search-row {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
</style>
