<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-card>
          <!-- 搜索框 -->
          <el-form :model="searchQuery" label-width="100px" style="margin-bottom: 20px;">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="试卷名称">
                  <el-input v-model="searchQuery.name" placeholder="请输入试卷名称" suffix-icon="el-icon-search" @input="filterPapers" />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="提交人">
                  <el-input v-model="searchQuery.submitter" placeholder="请输入提交人" suffix-icon="el-icon-search" @input="filterPapers" />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="批改状态">
                  <el-select v-model="searchQuery.status" placeholder="选择批改状态" @change="filterPapers">
                    <el-option label="全部" value=""></el-option>
                    <el-option label="已批改" value="0"></el-option>
                    <el-option label="未批改" value="1"></el-option>
                    <el-option label="未作答" value="2"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>

          <!-- 表格 -->
          <el-table :data="filteredExamPapers" border stripe style="width: 100%">
            <el-table-column prop="testId" label="试卷ID" width="120" />
            <el-table-column prop="name" label="试卷名称" />
            <el-table-column prop="subject" label="学科" />
            <el-table-column prop="senderName" label="提交人" width="150" />
            <el-table-column prop="status" label="批改状态" width="120">
              <template #default="{ row }">
                <el-tag :type="row.status === 0 ? 'success' : (row.status === 1 ? 'warning' : 'info')">
                  {{ row.status === 0 ? '已批改' : (row.status === 1 ? '未批改' : '未作答') }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template #default="{ row }">
                <el-button
                    v-if="row.status === 0"
                    size="small"
                    type="primary"
                    @click="viewPaper(row)">
                  查看试卷
                </el-button>

                <!-- 如果状态是 1，显示“批改”按钮 -->
                <el-button
                    v-else-if="row.status === 1"
                    size="small"
                    type="primary"
                    @click="correctPaper(row)"
                    style="width: 78px;">
                  批改
                </el-button>

                <!-- 如果状态是 2，显示“提醒”按钮 -->
                <el-button
                    v-else
                    size="small"
                    type="primary"
                    @click="remind(row)"
                    style="width: 78px;">
                  提醒
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 弹窗 -->
        <el-dialog v-model="dialogVisible" title="试卷详情" width="60%">
          <div v-if="selectedPaper">
            <p><strong>试卷名称：</strong>{{ selectedPaper.title }}</p>
            <p><strong>提交人：</strong>{{ selectedPaper.submitter }}</p>
            <p><strong>答题内容：</strong></p>
            <el-input type="textarea" v-model="selectedPaper.answers" rows="10" readonly />
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">关闭</el-button>
            <el-button type="success" @click="submitCorrection">提交批改</el-button>
          </div>
        </el-dialog>
      </el-main>
    </el-container>
  </el-container>
</template>

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

export default {
  name: "CorrectPapers",
  components: { Aside, Header },
  data() {
    return {
      userId: "",
      collapseBtnClass: "el-icon-s-fold",
      isCollapse: false,
      sideWidth: 200,
      logoTextShow: true,
      examPapers: [], // 试卷列表
      filteredExamPapers: [], // 过滤后的试卷列表
      dialogVisible: false, // 控制弹窗显示
      selectedPaper: null, // 当前选中的试卷
      searchQuery: {
        name: "", // 试卷名称
        status: "", // 批改状态
        submitter: "", // 提交人
      },
    };
  },
  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 fetchExamPapers() {
      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/selectMarkedtestList', {
          headers: {
            Authorization: `Bearer ${token}`,
            'Content-Type': 'application/json',
          }
        });
        if (response.data.code == 200) {
          this.examPapers = response.data.data;
          this.filteredExamPapers = [...this.examPapers]; // Initially, show all exam papers
          console.log('examPapers', this.filteredExamPapers);
        } else {
          alert("数据加载失败");
        }
      } catch (error) {
        console.error('获取数据失败', error);
      }
    },
    filterPapers() {
      this.filteredExamPapers = this.examPapers.filter(paper => {
        const matchesName = paper.name.toLowerCase().includes(this.searchQuery.name.toLowerCase());
        const matchesSubmitter = paper.senderName.toLowerCase().includes(this.searchQuery.submitter.toLowerCase());
        const matchesStatus = this.searchQuery.status === "" || paper.status == this.searchQuery.status;
        return matchesName && matchesSubmitter && matchesStatus;
      });
    },
    viewPaper(paper) {
      console.log('paper', paper);
      this.$router.push({
        name: 'ViewExamPaper',
        query: { userId: this.userId,studentId: paper.sendId, testid: paper.testId ,name: paper.name} // 传递试卷 ID
      });
    },
    correctPaper(paper){
      console.log('paper', paper);
      this.$router.push({
        name: 'CorrectExamPaper',
        query: { userId: this.userId,studentId: paper.sendId, testid: paper.testId ,name: paper.name} // 传递试卷 ID
      });
    },
    async remind(paper){
      const name = paper.name;
      const token = this.$store.state.tokens[this.userId];
      if (!token) {
        alert("用户未登录，请重新登录！");
        this.$router.push("/login"); // 跳转到登录页
        return;
      }
      const res =await axios.post(`http://localhost:8080/teacher/answerSheet/addMessage`,
        {teacherId: this.userId,
              studentId: paper.sendId,
              tf: false,
              name: name,
        },{
          headers: {
          Authorization: `Bearer ${token}`,
          'Content-Type': 'application/json',
        }
      });
      console.log(res);
      if(res.data.code == 200){
        this.$message.success("提醒成功！");
      }else{
        this.$message.error("发送失败！");
      }
    },
    submitCorrection() {
      this.dialogVisible = false;
      this.$message.success("批改提交成功！");
      // 模拟更新批改状态
      this.selectedPaper.status = "已批改";
    },
  },
  mounted() {
    this.userId = this.$route.query.userId;
    this.fetchExamPapers();
  },
};
</script>

<style scoped>
.el-table {
  margin-top: 20px;
}
</style>
