<template>
  <div>
    <div class="rating-component">
      <span>评分:&nbsp;&nbsp;</span>
      <input type="number" class="score-input" :min="1" :max="100" placeholder="暂无分数" title="请输入0~100间的数字"
        v-model="correction.score" :disabled="isStudent" />
    </div>

    <div class="textarea-container">
      <textarea v-model="correction.remark" placeholder="暂无评语" :readonly="isStudent"></textarea>
    </div>

    <div class="correction-actions">
      <div class="button-group">
        <div class="left-buttons">
          <el-button 
            color="#597D3B" 
            @click="handleCorrect" 
            v-if="!isStudent"
            :loading="submitting"
          >
            提交批改
          </el-button>
          
          <el-button
            color="#597D3B"
            @click="handleNext"
            v-if="!isStudent"
            :disabled="isAllCorrected" 
          >
            下一个
          </el-button>

          <!-- 批改进度显示 -->
          <span class="progress-text" v-if="!isStudent">
            已批改/未批改：{{ correctionStats.correctNumber }}/{{ uncorrectedNumber }}
          </span>
          
          <!-- 批改进度条显示 -->
          <div class="correction-progress" v-if="!isStudent">
            <el-progress 
              :percentage="progressPercentage" 
              :stroke-width="6"
              color="#597D3B"
              class="progress-bar"
            />
          </div>

        </div>

        <div class="right-buttons">
          <el-button color="#597D3B" @click="goBack">返回</el-button>
        </div>
      </div>
      
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, computed } from 'vue';
import useApis from "@/apis";
import { ElMessage } from "element-plus";
import router from '@/router';
import "./index.scss"
import { useStore } from "@/store";

const store = useStore()

export default defineComponent({
  props: {
    studentId: {
      type: Number,
      required: true
    },
    assignmentId: {
      type: Number,
      required: true
    }
  },
  setup(props) {
    const isStudent = computed(() => store.user.role === 'STUDENT');
    const submitting = ref(false);

    //定义一个correction接收后端传过来的批改信息（如果有） 
    const correction = ref({
      score: 0,
      remark: ''
    });

    // 批改进度统计
    const correctionStats = ref({
      engageNumber: 0,
      correctNumber: 0
    });

    // 计算批改进度百分比
    const progressPercentage = computed(() => {
      if (correctionStats.value.engageNumber === 0) return 0;
      return Math.round((correctionStats.value.correctNumber / correctionStats.value.engageNumber) * 100);
    });

    // 计算未批改数量
    const uncorrectedNumber = computed(() => {
      return correctionStats.value.engageNumber - correctionStats.value.correctNumber;
    });

    // 判断是否全部批改完成
    const isAllCorrected = computed(() => {
      return uncorrectedNumber.value === 0;
    });

    // 获取批改进度统计
    const fetchCorrectionStats = async () => {
      const apis = useApis();
      try {
        const res = await apis.getAssignmentCorrectionStats(props.assignmentId);
        if (res.data.code === 200) {
          correctionStats.value = res.data.data;
        }
      } catch (error) {
        console.error('获取批改进度失败:', error);
      }
    };

    //新增：获取后台批改数据
    const fetchCorrection = async () => {
      const apis = useApis();
      try {
        const res = await apis.getEngagement(props.studentId, props.assignmentId);
        if (res.data.code === 200) {
          //这有两个.data，老是漏掉
          correction.value.score = res.data.data.score;
          correction.value.remark = res.data.data.remark;
        } else {
          ElMessage.error("获取批改异常" + res.data.msg);
        }
      } catch (err) {
        console.log(err);
        ElMessage.error("请求失败，请重试");
      }
    };

    // 获取下一个学生作业ID
    const getNextStudentAssignment = async () => {
      const apis = useApis();
      try {
        console.log(props.assignmentId, props.studentId);
        const res = await apis.getNextStudentAssignment(props.assignmentId, props.studentId);
        if (res.data.code === 200) {
          return res.data.data;
        }
      } catch (error) {
        console.error('获取下一个学生失败:', error);
      }
      return null;
    };

    onMounted(() => {
      fetchCorrection();
      fetchCorrectionStats();
    });

    const handleCorrect = async () => {
      console.log(correction.value.score, correction.value.remark);
      if (!correction.value.score) {
        ElMessage.error("请先评分");
        return;
      }
      if (!correction.value.remark) {
        ElMessage.error("请先输入评语");
        return;
      }
      if (isStudent.value) {
        ElMessage.error("学生不能提交批改");
        return;
      } else {
        submitting.value = true;
        const apis = useApis();
        try {
          await apis.engagementCorrect(props.studentId, props.assignmentId, correction.value)
            .then(async (res) => {
              if (res.data.code === 200) {
                ElMessage.success("批改成功");
                await fetchCorrectionStats();
              } else {
                ElMessage.error("批改异常" + res.data.msg);
              }
            });
        } catch (err) {
          console.log(err);
          ElMessage.error("批改失败，请重试");
        } finally {
          submitting.value = false;
        }
      }
    };

    const handleNext = async () => {
      if (isStudent.value) {
        ElMessage.error("学生不能跳转到下一个学生");
        return;
      } else {
        const nextStudentId = await getNextStudentAssignment();
        if (nextStudentId) {
          router.push({
            name: 'correct',
            params: { assignmentId: props.assignmentId },
            query: { studentId: nextStudentId }
          }).then(() => {
            // 强制刷新页面以重新加载数据
            window.location.reload();
          });
          ElMessage.success("已自动跳转到下一个学生");
        } else {
          ElMessage.info("没有下一个学生");
        }
      }
    };

    const goBack = () => {
      router.push({
        name: 'myCorrectWithAssignmentId',
        params: { assignmentId: props.assignmentId }
      });
    };

    return {
      correction,
      handleCorrect,
      handleNext,
      isStudent,
      submitting,
      correctionStats,
      progressPercentage,
      uncorrectedNumber,
      isAllCorrected,
      goBack
    };
  }
});  
</script>

<style lang="scss" scoped>
.correction-actions {
  margin-top: 20px;
  
  .button-group {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
    width: 100%;

    .left-buttons {
      display: flex;
      gap: 10px;
    }

    .progress-text {
      color: #666;
      font-size: 16px;
      flex: 1;
      text-align: center;
    }

    .right-buttons {
      display: flex;
      gap: 10px;
    }
  }

  .correction-progress {
    margin-top: 10px;
  }
}
</style>
