<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" @input="validateScore" />
      <span v-if="scoreError" class="error-message">{{ scoreError }}</span>
    </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="showTemplateDialog" v-if="!isStudent">评语模板</el-button> 
          <el-button color="#597D3B" @click="goBack">返回</el-button>
        </div>
      </div>
      
    </div>

    <!-- 添加评语模板弹窗 -->
    <el-dialog
      v-model="templateDialogVisible"
      title="评语模板"
      width="50%"
      :close-on-click-modal="false"
      class="template-dialog"
    >
      <div class="template-list">
        <div 
          v-for="(template, index) in remarkTemplates" 
          :key="index"
          class="template-item"
          @click="selectTemplate(template)"
        >
          <el-tooltip
            v-if="isTruncatedList[index]"
            :content="template"
            placement="top"
            :show-after="500"
            effect="light"
          >
            <div class="template-content" :ref="el => setTemplateContentRef(el, index)">
              {{ index + 1 }}. {{ template }}
            </div>
          </el-tooltip>
          <div
            v-else
            class="template-content"
            :ref="el => setTemplateContentRef(el, index)"
          >
            {{ index + 1 }}. {{ template }}
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, computed, nextTick, watch } 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);
    const scoreError = ref('');

    //定义一个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 = () => {
      // 根据用户角色决定返回页面
      if (isStudent.value) {
        // 学生返回 myHomework 页面
        router.push({
          name: 'myHomework'
        });
      } else {
        // 老师保持原有逻辑，返回批改页面
        router.push({
          name: 'myCorrectWithAssignmentId',
          params: { assignmentId: props.assignmentId }
        });
      }
    };
    //新增：验证评分是否在1-100之间
    const validateScore = () => {
      const score = Number(correction.value.score);
      if (isNaN(score) || score < 1 || score > 100) {
        scoreError.value = '评分必须在1-100之间';
      } else {
        scoreError.value = '';
      }
    };

    //新增：评语模板
    const templateDialogVisible = ref(false);
    const remarkTemplates = [
      'Great job! Your writing is clear and well-organized.',
      'There are some grammar mistakes that affect clarity. Please revise. ',
      'Watch out for tense consistency throughout your writing.',
      'You used some good vocabulary, but try to expand your word choice.',
      'Your argument is clear, but could be strengthened with more supporting details.Use more precise words to convey your ideas more effectively.'
    ];

    const showTemplateDialog = () => {
      templateDialogVisible.value = true;
    };

    const selectTemplate = (template: string) => {
      correction.value.remark = template;
      templateDialogVisible.value = false;
    };

    // 新增：判断每个选项是否被截断
    const isTruncatedList = ref<boolean[]>([]);
    const templateContentRefs = ref<(HTMLElement|null)[]>([]);

    const setTemplateContentRef = (el: any, index: number) => {
      templateContentRefs.value[index] = el;
    };

    // 计算截断
    const checkTruncated = () => {
      isTruncatedList.value = remarkTemplates.map((_, idx) => {
        const el = templateContentRefs.value[idx];
        if (!el || !(el instanceof HTMLElement)) return false;
        return el.scrollWidth > el.clientWidth;
      });
    };

    // 弹窗打开后检查
    watch(templateDialogVisible, (val) => {
      if (val) {
        nextTick(() => {
          checkTruncated();
        });
      }
    });

    return {
      correction,
      handleCorrect,
      handleNext,
      isStudent,
      submitting,
      correctionStats,
      progressPercentage,
      uncorrectedNumber,
      isAllCorrected,
      goBack,//返回
      scoreError,//评分错误
      validateScore,//验证评分
      templateDialogVisible,//评语模板弹窗
      remarkTemplates,//评语模板
      showTemplateDialog,//显示评语模板弹窗
      selectTemplate,//选择评语模板
      isTruncatedList,
      setTemplateContentRef,
    };
  }
});  
</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;
  }
}
/* 新增：评分错误 css样式*/
.rating-component {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;

  .error-message {
    color: #ff4d4f;
    font-size: 14px;
    font-weight: 700;
  }
}
/* 新增：评语模板 css样式*/
.template-dialog {
  :deep(.el-dialog__body) {
    padding: 20px 0; // 上下20px，左右0
  }
}

.template-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
  padding: 0 24px; // 左右留白对称

  .template-item {
    box-sizing: border-box;
    padding: 0 16px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s ease;
    height: 50px;
    overflow: hidden;
    display: flex;
    align-items: center;
    margin: 0 auto;
    width: 100%;

    &:hover {
      background-color: #f5f7fa;
      border-color: #597D3B;
    }

    .template-content {
      width: 100%;
      text-align: left;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      font-size: 14px;
      line-height: 1.5;
      display: block;
    }
  }
}
</style>
