<template>
  <div>
    <el-container style="min-height: 100vh; width: 100%">
      <!-- Left sidebar -->
      <el-aside :width="sideWidth + 'px'" style="background-color: #f4f7fc; box-shadow: 2px 0 6px rgba(0, 21, 41, 0.15)">
        <Aside :isCollapse="isCollapse" :logoTextShow="logoTextShow" />
      </el-aside>

      <!-- Main content -->
      <el-container style="width: calc(100% - 200px);">
        <el-header style="border-bottom: 1px solid #e1e4ea; padding: 10px 20px; background: #fff;">
          <Header :collapseBtnClass="collapseBtnClass" :collapse="collapse" />
        </el-header>

        <el-main style="padding: 20px;">
          <!-- Search bar -->
          <el-row gutter={20} style="margin-bottom: 20px;">
            <el-col :span="12">
              <el-input
                  v-model="searchQuery.name"
                  placeholder="请输入试卷名称"
                  clearable
                  @input="fetchScores"
                  style="width: 100%; border-radius: 5px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);"
              />
            </el-col>
            <el-col :span="12">
              <el-input
                  v-model="searchQuery.testID"
                  placeholder="请输入试卷ID"
                  clearable
                  @input="fetchScores"
                  style="width: 100%; border-radius: 5px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);"
              />
            </el-col>
          </el-row>

          <!-- Exam papers table -->
          <el-table :data="papers" style="width: 100%" border>
            <el-table-column prop="id" label="试卷ID" width="100" />
            <el-table-column prop="name" label="试卷名称" width="200" />
            <el-table-column prop="subject" label="学科" width="150" />
            <el-table-column prop="grade" label="年级" width="100" />
            <el-table-column prop="class1" label="班级" width="100" />

            <el-table-column label="完成人数" width="200">
              <template slot-scope="scope">
                <span>{{ scope.row.completedCount }} / {{ scope.row.totalCount }}</span>
              </template>
            </el-table-column>

            <el-table-column label="成绩分布" width="160">
              <template slot-scope="scope">
                <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" style="border-radius: 5px; font-size: 14px;">
                  {{ scope.row.status === 1 ? '已发布' : '未发布' }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column label="操作" width="320">
              <template slot-scope="scope">
                <div style="display: flex; width: 100%; gap: 10px;">
                  <el-button
                      type="primary"
                      size="small"
                      style="flex: 1; border-radius: 4px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);"
                      @click="openRankingDetail(scope.row.id, scope.row.grade, scope.row.class1)">
                    查看排名
                  </el-button>
                  <el-button
                      type="primary"
                      size="small"
                      style="flex: 1; border-radius: 4px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);"
                      @click="publishExam(scope.row.id,scope.row.grade, scope.row.class1)">
                    发布
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>

          <!-- Pagination -->
          <el-pagination
              :current-page="pageNum"
              :page-size="pageSize"
              :total="total"
              @current-change="handlePageChange"
              layout="total, prev, pager, next, jumper"
              style="text-align: right; margin-top: 20px; border-top: 1px solid #e1e4ea; padding-top: 10px;"
          />
        </el-main>
      </el-container>
    </el-container>

    <!-- Ranking detail dialog -->
    <el-dialog :visible.sync="rankingDialogVisible" title="排名详情" width="50%">
      <p>试卷ID: {{ selectedTestId }}</p>

      <el-table :data="rankingDetails" style="width: 100%" border>
        <el-table-column prop="ranking" label="排名" width="100" />
        <el-table-column prop="senderName" label="学生姓名" width="150" />
        <el-table-column prop="score" label="得分" width="150" />

        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <el-button
                type="primary"
                size="small"
                style="border-radius: 4px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);"
                @click="viewDetails(scope.row)"
            >
              详细
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- Footer buttons -->
      <span slot="footer" class="dialog-footer" style="display: flex; justify-content: flex-end;">
        <el-button @click="rankingDialogVisible = false" style="border-radius: 4px;">
          关闭
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

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

export default {
  name: "Score",
  components: { Aside, Header },
  data() {
    return {
      userId: "", // 用户ID
      collapseBtnClass: "el-icon-s-fold",
      isCollapse: false,
      sideWidth: 200,
      logoTextShow: true,
      searchQuery: {
        name: "",
        testID: "",
      }, // 搜索条件
      papers: [], // 存放试卷列表
      pageNum: 1, // 当前页码
      pageSize: 10, // 每页显示条数
      total: 0, // 总记录数
      rankingDialogVisible: false, // 是否显示排名详情弹窗
      selectedTestId: null, // 当前查看的试卷ID
      rankingDetails: [], // 排名详情数据
    };
  },
  created() {
    this.userId = this.$route.query.userId;
    this.fetchScores(); // 初始化加载试卷成绩
  },
  methods: {
    collapse() {
      this.isCollapse = !this.isCollapse;
      this.sideWidth = this.isCollapse ? 64 : 200;
      this.collapseBtnClass = this.isCollapse ? "el-icon-s-unfold" : "el-icon-s-fold";
      this.logoTextShow = !this.isCollapse;
    },

    // 查询试卷数据
    async fetchScores() {
      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/teacher/answerSheet/getExamPaperList", {
          params: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
          },
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });
        console.log("responser",response);
        if (response.data.code === 200) {
          // 获取所有试卷数据
          const allPapers = response.data.data.records || [];
          this.papers = this.filterPapers(allPapers); // 筛选后的试卷列表
          this.total = response.data.data.total || 0;
          this.pageNum = response.data.data.current || 1;
        } else {
          this.$message.error("查询异常！");
        }
      } catch (error) {
        console.error("获取试卷数据失败", error);
      }
    },

    // 筛选试卷数据
    filterPapers(papers) {
      return papers.filter(paper => {
        // 对试卷名称和试卷ID进行筛选
        const matchesName = this.searchQuery.name
            ? paper.name.includes(this.searchQuery.name)
            : true;
        const matchesTestID = this.searchQuery.testID
            ? paper.id.toString().includes(this.searchQuery.testID)
            : true;

        return matchesName && matchesTestID;
      });
    },

    // 打开排名详情弹窗
    openRankingDetail(testId,grade,class1) {
      this.selectedTestId = testId; // Set the selectedTestId to the row's testId
      this.fetchRankingDetails(testId,grade,class1); // Fetch ranking details for the selected test
      this.rankingDialogVisible = true; // Show the ranking details dialog
    },

    // 查询排名详情
    async fetchRankingDetails(testId,grade,class1) {
      try {
        const token = this.$store.state.tokens[this.userId];
        if (!token) {
          alert("用户未登录，请重新登录！");
          this.$router.push("/login");
          return;
        }

        console.log('grade',grade);

        // 使用 testId 从后台获取排名详情
        const response = await axios.get(`http://localhost:8080/teacher/answerSheet/selectScoreList`, {
          params: { testid: testId, grade: grade, Class1: class1}, // 将 testId 传递给后台
          headers: { Authorization: `Bearer ${token}` }, // 包含 token 进行身份验证
        });
        console.log("response",response);
        // 如果响应成功
        if (response.data.code === 200) {
          // 将排名详情设置到组件的状态中
          this.rankingDetails = response.data.data || [];
        } else {
          // 如果查询失败，显示错误信息
          this.$message.error("查询排名详情失败！");
        }
      } catch (error) {
        console.error("获取排名详情失败", error);
        this.$message.error("获取排名详情失败");
      }
    },

    // 发布试卷
    async publishExam(testId, grade, class1) {
      try {
        const token = this.$store.state.tokens[this.userId];
        if (!token) {
          alert("用户未登录，请重新登录！");
          this.$router.push("/login");
          return;
        }

        const response = await axios.put(`http://localhost:8080/teacher/answerSheet/fabu`, { testid: testId }, {
          params: { testid: testId, grade: grade, Class1: class1},
          headers: { Authorization: `Bearer ${token}` },
        });

        console.log("response",response);

        if (response.data.code === 200) {
          this.fetchScores(); // 重新加载试卷数据
          this.$message.success("发布成功！");
        } else {
          this.$message.error("发布失败！");
        }
      } catch (error) {
        console.error("发布试卷失败", error);
      }
    },

    // 分页处理
    handlePageChange(pageNum) {
      this.pageNum = pageNum;
      this.fetchScores();
    },
  },
};
</script>

<style scoped lang="scss">
.el-container {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
}

.el-main {
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.el-header {
  background-color: #fff;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.el-table th {
  background-color: #f5f7fa;
  color: #333;
  font-weight: 500;
}

.el-table-row:hover {
  background-color: #f2f8ff;
}

.el-button {
  transition: background-color 0.3s ease, box-shadow 0.3s ease;
}

.el-button:hover {
  background-color: #409eff;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.el-input {
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.el-pagination {
  margin-top: 10px;
}

.el-dialog {
  background-color: #fff;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.el-dialog .el-button {
  border-radius: 4px;
}

.el-tag {
  font-size: 14px;
}
</style>
