<template>
  <!-- 反馈审核不通过提示条：仅在 evaluationSystem-feedback 且 approveRejectReson 有值时显示 -->
  <el-alert
    v-if="isFeedbackOperate && approveRejectReson"
    type="error"
    :title="approveRejectReson"
    show-icon
    class="reject-alert"
  />
  <main class="safety-platform-container__main">
    <el-form ref="formRef" :model="ruleFormData" :rules="formRules" label-width="auto" class="evaluation-form">
      <el-form-item label="考核信息标题：" prop="evaluationTitle">
        <el-input v-model="ruleFormData.evaluationTitle" placeholder="请输入考核信息标题" disabled />
      </el-form-item>
      <el-form-item label="上传附件文档：" prop="attachmentDocument">
        <div class="upload-files-disabled">
          <UploadFiles
            label="上传附件"
            :file-list="ruleFormData.attachmentDocument"
            @uploadSuccess="handleUploadSuccess"
          />
        </div>
      </el-form-item>
      <el-form-item label="评分说明：" prop="scoringDescription">
        <el-input
          v-model="ruleFormData.scoringDescription"
          type="textarea"
          :rows="5"
          placeholder="请输入评分说明"
          disabled
        />
      </el-form-item>
    </el-form>

    <div class="evaluation-items-section">
      <div class="section-header">
        <el-button plain @click="handleDownloadTemplate" disabled>模板下载</el-button>
        <el-button plain @click="handleImport">导入</el-button>
        <el-button plain @click="handleExport">导出</el-button>
        <input
          ref="importFileInputRef"
          type="file"
          accept=".xlsx,.xls"
          style="display: none"
          @change="handleFileChange"
        />
      </div>
      <div class="evaluation-items-table">
        <el-table :data="evaluationItems" border show-summary :summary-method="getSummaries" :span-method="spanMethod">
          <el-table-column label="编号" type="index" width="80" align="center" />
          <el-table-column label="考核项目" prop="evaluationItem" min-width="150" />
          <el-table-column label="考核内容" prop="evaluationContent" min-width="200" />
          <el-table-column label="评分方式" prop="scoringMethod" min-width="150" />
          <el-table-column label="加减分项" prop="scoreType" min-width="120" />
          <el-table-column label="自评得分" prop="selfScore" min-width="120">
            <template #default="scope">
              {{ scope.row.selfScore }}
            </template>
          </el-table-column>
          <el-table-column label="资料说明" prop="materialDescription" min-width="200">
            <template #default="scope">
              <div
                class="file-container--div"
                v-for="item in parseAttachments(scope.row.materialDescription)"
                :key="item.fileUrl"
              >
                <img
                  class="file-container--div__icon"
                  @click="previewOnline(item.fileUrl, item.fileType as keyof typeof FILE_TYPE_ICON)"
                  :src="FILE_TYPE_ICON[item.fileType]"
                />
                <span
                  class="file-container--div__name"
                  @click="previewOnline(item.fileUrl, item.fileType as keyof typeof FILE_TYPE_ICON)"
                  >{{ item.fileName }}</span
                >
                <img
                  class="file-container--div__download"
                  :src="DownloadIcon"
                  @click="downloadFile(item.fileUrl, item.fileName)"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="复核人姓名" prop="reviewUserName" min-width="120" />
          <el-table-column label="复核得分" prop="reviewScore" min-width="200">
            <template #default="scope">
              <el-input-number
                v-if="!isAudit && scope.row.isReviewInput"
                v-model="scope.row.reviewScore"
                :min="0"
                :max="99999"
                :precision="0"
                :step="1"
                placeholder="请输入复核得分"
                @blur="handleScoreBlur"
              />
              <span v-else>{{ scope.row.reviewScore }}</span>
            </template>
          </el-table-column>
          <el-table-column label="复核不通过原因" prop="reviewRejectReson" min-width="220">
            <template #default="scope">
              <el-input
                v-if="!isAudit && isSelfApproveButton"
                v-model="scope.row.reviewRejectReson"
                type="textarea"
                :rows="2"
                placeholder="请输入复核不通过原因"
              />
              <span v-else>{{ scope.row.reviewRejectReson }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </main>
  <footer class="safety-platform-container__footer">
    <el-button @click="router.back()">取消</el-button>
    <el-button v-if="!isAudit && isSelfApproveButton" @click="openRejectDialog('review')">复核不通过</el-button>
    <el-button v-if="isAudit" @click="openRejectDialog('approve')">审核不通过</el-button>
    <el-button v-if="!isAudit && isSelfApproveButton" type="primary" @click="handleSubmitItem">保存</el-button>

    <el-button v-if="!isFromDeptView" type="primary" @click="handleSubmit">{{ getSubmitButtonText }}</el-button>
  </footer>

  <!-- 拒绝原因弹窗 -->
  <el-dialog v-model="rejectDialogVisible" :title="rejectDialogTitle" width="600px" :close-on-click-modal="false">
    <el-input
      v-model="rejectReason"
      type="textarea"
      :rows="6"
      :maxlength="300"
      :show-word-limit="true"
      :placeholder="rejectDialogPlaceholder"
    />
    <template #footer>
      <el-button @click="closeRejectDialog">取消</el-button>
      <el-button type="primary" @click="confirmReject">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { computed, ref, watch } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import type { FormInstance } from 'element-plus';
  import UploadFiles from '@/components/UploadFiles/UploadFiles.vue';
  import {
    querySecurityExamineIssueDetail,
    updateSecurityExamineIssueReviewSubmit,
    updateSecurityExamineIssueReviewAgree,
    updateSecurityExamineIssueReviewDisagree,
    updateSecurityExamineIssueApproveAgree,
    updateSecurityExamineIssueApproveDisagree,
    exportSecurityExamineIssueDeptDetail,
    importSecurityExamineIssueDeptDetail,
  } from '@/api/evaluationSystem';
  import type { FileItem } from '@/components/UploadFiles/types';
  import { formatAttachmentList } from '@/components/UploadFiles/utils';
  import DownloadIcon from '@/views/disaster/disaster-control/src/svg/download.svg';
  import { downloadFile } from '@/views/disaster/utils';
  import PreviewOnline from '@/views/disaster/components/PreviewOnline.vue';
  import { FILE_TYPE_ICON } from '@/components/UploadFiles/constants';

  const props = defineProps<{
    id: number;
  }>();

  const router = useRouter();
  const route = useRoute();

  // 判断是评分还是审核
  const isAudit = computed(() => route.query.operate === 'evaluationSystem-audit');

  // 判断是否为 evaluationSystem-feedback（反馈/评分）
  const isFeedbackOperate = computed(() => route.query.operate === 'evaluationSystem-feedback');

  // 判断是否从部门考核结果视图进入（如果是，则不显示提交按钮）
  const isFromDeptView = computed(() => route.query.fromDeptView === 'true');

  // 提交按钮文字
  const getSubmitButtonText = computed(() => {
    if (isAudit.value) {
      return '审核通过';
    }
    // 如果是评分模式，根据 isSelfApproveButton 决定按钮文字
    if (isSelfApproveButton.value) {
      return '提交';
    }
    return '保存';
  });

  // 拒绝原因弹窗相关
  const rejectDialogVisible = ref(false);
  const rejectReason = ref('');
  const rejectType = ref<'review' | 'approve'>('review'); // 当前拒绝类型

  const rejectDialogTitle = computed(() => {
    return rejectType.value === 'review'
      ? '复核评分不通过的记录,需要填写驳回原因'
      : '审核不通过的记录,需要填写驳回原因';
  });

  const rejectDialogPlaceholder = computed(() => {
    return rejectType.value === 'review' ? '请填写驳回审批原因' : '请填写驳回审批原因';
  });

  const openRejectDialog = (type: 'review' | 'approve') => {
    rejectType.value = type;
    rejectReason.value = '';
    rejectDialogVisible.value = true;
  };

  const closeRejectDialog = () => {
    rejectDialogVisible.value = false;
    rejectReason.value = '';
  };

  const formRef = ref<FormInstance>();
  const ruleFormData = ref({
    evaluationTitle: '',
    attachmentDocument: [] as FileItem[],
    scoringDescription: '',
  });

  const formRules = {
    evaluationTitle: [{ required: true, message: '请输入考核信息标题', trigger: 'blur' }],
    attachmentDocument: [{ required: true, message: '请上传附件文档', trigger: 'change' }],
    // scoringDescription: [{ required: true, message: '请输入评分说明', trigger: 'blur' }],
  };

  const evaluationItems = ref<any[]>([]);
  // 保存详情原始数据，用于提交
  const detailData = ref<any>(null);
  // 是否显示复核不通过按钮（从详情接口获取）
  const isSelfApproveButton = ref(false);

  // 审批拒绝原因（用于顶部提示条，仅 evaluationSystem-feedback 时展示）
  const approveRejectReson = computed(() => {
    const val = detailData.value?.approveRejectReson;
    return val && String(val).trim() ? String('审核不通过原因:' + val).trim() : '';
  });

  // 计算自评得分总计：根据加减分项计算，加分项和基础分加、减分项减（基础分按加分项计，与复核得分规则一致）
  const getTotalScore = () => {
    return evaluationItems.value.reduce((sum, item) => {
      const score = Number(item.selfScore) || 0;
      const isAdd = item.isAdd === 1 || item.isAdd === 2 || item.scoreType === '加分项' || item.scoreType === '基础分';
      return isAdd ? sum + score : sum - score;
    }, 0);
  };

  // 计算复核得分总计：根据加减分项计算，加分项和基础分加、减分项减（基础分按加分项计，与自评得分规则一致）
  const getTotalReviewScore = () => {
    return evaluationItems.value.reduce((sum, item) => {
      const score = Number(item.reviewScore) || 0;
      const isAdd = item.isAdd === 1 || item.isAdd === 2 || item.scoreType === '加分项' || item.scoreType === '基础分';
      return isAdd ? sum + score : sum - score;
    }, 0);
  };

  // 自评得分失去焦点时触发（用于强制更新合计行）
  const handleScoreBlur = () => {
    // 触发响应式更新，让合计行重新计算
    // 通过修改数组引用来触发更新
    evaluationItems.value = [...evaluationItems.value];
  };

  // 表格合计行方法
  const getSummaries = (param: any) => {
    const { columns } = param;
    const sums: string[] = [];
    columns.forEach((column: any, index: number) => {
      if (index === 0) {
        // 编号列
        sums[index] = '';
      } else if (column.property === 'scoreType') {
        // 加减分项列显示"总计："
        sums[index] = '总计：';
      } else if (column.property === 'selfScore') {
        // 自评得分列显示总分（按加减分项规则计算）
        const total = getTotalScore();
        sums[index] = `${total}分`;
      } else if (column.property === 'reviewScore') {
        // 复核得分列显示总分（按加减分项规则计算，与自评得分一致）
        const total = getTotalReviewScore();
        sums[index] = `${total}分`;
      } else {
        // 其他列显示空
        sums[index] = '';
      }
    });
    return sums;
  };

  const handleValidate = async () => {
    if (!formRef.value) return;
    return new Promise((resolve) => {
      formRef.value?.validate((valid: boolean) => {
        resolve(valid);
      });
    });
  };

  const handleUploadSuccess = (files: any[]) => {
    // 评分页顶部附件只读展示，这里仅保持与 UploadFiles 事件兼容
    ruleFormData.value.attachmentDocument = files;
  };

  const handleDownloadTemplate = () => {
    // TODO: 下载模板
    console.log('download template');
  };

  // 导入文件引用
  const importFileInputRef = ref<HTMLInputElement>();

  const handleImport = () => {
    // 触发文件选择
    importFileInputRef.value?.click();
  };

  const handleFileChange = async (event: Event) => {
    const target = event.target as HTMLInputElement;
    const file = target.files?.[0];
    if (!file) return;

    try {
      await importSecurityExamineIssueDeptDetail({
        id: props.id,
        file,
      });
      ElMessage.success('导入成功');
      // 重新加载详情数据
      await getDetail();
    } catch (e: any) {
      console.error('导入失败:', e);
      ElMessage.error(e?.message || e?.data || '导入失败，请重试');
    } finally {
      // 清空文件选择
      if (target) {
        target.value = '';
      }
    }
  };

  const handleExport = async () => {
    try {
      const blob = await exportSecurityExamineIssueDeptDetail(props.id);
      // 创建下载链接
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `部门考核详情_${new Date().getTime()}.xlsx`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      ElMessage.success('导出成功');
    } catch (e: any) {
      console.error('导出失败:', e);
      ElMessage.error(e?.message || e?.data || '导出失败，请重试');
    }
  };

  // 预览
  const previewOnlineRef = ref<InstanceType<typeof PreviewOnline>>();
  const previewOnline = (url: string | undefined, type: keyof typeof FILE_TYPE_ICON) => {
    if (url) {
      previewOnlineRef.value?.open(url, type);
    }
  };

  // 解析逗号分隔的URL字符串为文件列表（用于表格资料说明展示）
  const parseAttachments = (
    attachmentsStr: string | undefined,
  ): Array<{
    fileUrl: string;
    fileName: string;
    fileType: string;
  }> => {
    if (!attachmentsStr || !attachmentsStr.trim()) {
      return [];
    }

    const urls = attachmentsStr
      .split(',')
      .map((url) => url.trim())
      .filter((url) => url);

    return urls.map((url) => {
      const urlParts = url.split('/');
      const fileName = urlParts[urlParts.length - 1] || '未知文件';

      const extension = fileName.split('.').pop()?.toLowerCase() || '';
      let fileType = 'pdf';
      if (extension === 'doc' || extension === 'docx') {
        fileType = 'word';
      } else if (extension === 'xls' || extension === 'xlsx') {
        fileType = 'excel';
      } else if (extension === 'ppt' || extension === 'pptx') {
        fileType = 'ppt';
      }

      return {
        fileUrl: url,
        fileName,
        fileType,
      };
    });
  };

  // 将逗号分隔的 URL 字符串转换为 FileItem[] 格式
  const parseAttachmentsToFileList = (attachmentsStr: string | undefined): FileItem[] => {
    if (!attachmentsStr || !attachmentsStr.trim()) {
      return [];
    }

    // 按逗号分割URL
    const urls = attachmentsStr
      .split(',')
      .map((url) => url.trim())
      .filter((url) => url);

    return urls.map((url, index) => {
      // 从URL中提取文件名
      const urlParts = url.split('/');
      const fileName = urlParts[urlParts.length - 1] || `文件${index + 1}`;

      // 根据文件扩展名判断文件类型
      const extension = fileName.split('.').pop()?.toLowerCase() || '';
      let fileType = 'pdf';
      if (extension === 'doc' || extension === 'docx') {
        fileType = 'word';
      } else if (extension === 'xls' || extension === 'xlsx') {
        fileType = 'excel';
      } else if (extension === 'ppt' || extension === 'pptx') {
        fileType = 'ppt';
      }

      return {
        fileId: index + 1,
        fileName,
        fileType,
        fileSize: '0', // 接口未返回文件大小，使用默认值
        fileUrl: url,
      };
    });
  };

  const getDetail = async () => {
    if (!props.id || isNaN(props.id) || props.id <= 0) {
      console.error('无效的ID:', props.id);
      ElMessage.error('缺少有效的考核对象ID');
      return;
    }
    try {
      console.log('调用详情接口，ID:', props.id);
      const detail = await querySecurityExamineIssueDetail(props.id);
      if (!detail) {
        console.warn('详情接口返回空数据');
        return;
      }

      // 保存原始详情数据，用于提交
      detailData.value = detail;

      // 获取是否显示复核不通过按钮
      isSelfApproveButton.value = detail.isSelfApproveButton === true;

      // 映射表单字段
      ruleFormData.value.evaluationTitle = detail.exName || ''; // 考核表名称
      ruleFormData.value.attachmentDocument = parseAttachmentsToFileList(detail.attachments); // 附件文档
      ruleFormData.value.scoringDescription = detail.ratingDescribe; // 评分说明（接口暂无此字段，留空）

      // 映射考核项目列表（scores 数组）
      if (detail.scores && detail.scores.length > 0) {
        evaluationItems.value = detail.scores.map((score) => ({
          id: score.id, // 保留评分项ID，用于提交
          isAdd: score.isAdd !== undefined ? score.isAdd : score.selfScore >= 0 ? 1 : 0, // 加减分项（0-减分项，1-加分项，2-基础分）
          isAddName: score.isAdd === 2 ? '基础分' : score.isAdd === 1 ? '加分项' : '减分项', // 加减分项名称
          scoreType: score.isAdd === 2 ? '基础分' : score.isAdd === 1 ? '加分项' : '减分项', // 加减分项（用于显示，兼容旧字段）
          evaluationItem: score.exProgram || '', // 考核项目
          evaluationContent: score.exContent || '', // 考核内容
          scoringMethod: score.scoringWay || '', // 评分方式
          selfScore: score.selfScore, // 自评得分
          reviewUserName: score.reviewUserName || '-', // 复核人姓名（从详情顶层获取）
          reviewScore: score.reviewScore, // 复核得分
          reviewRejectReson: score.reviewRejectReson || '', // 复核不通过原因
          materialDescription: score.attachments || '', // 资料说明（使用附件字段，字符串）
          attachmentFileList: parseAttachmentsToFileList(score.attachments || ''), // 资料说明对应的附件文件列表
          isReviewInput: score.isReviewInput, // 是否显示复核得分输入框
          // reviewRejectResonShow: detail.isSelfApproveButton || '', // 复核不通过原因
        }));
        generateSpanArr(evaluationItems.value);
      } else {
        evaluationItems.value = [];
      }
    } catch (e) {
      console.error('获取考核对象详情失败:', e);
      ElMessage.error(e?.message || e?.data || '获取详情失败，请重试');
    }
  };
  let spanArr = ref<number[]>([]); // 存储每行的合并数，0表示被合并的行
  const generateSpanArr = (data) => {
    spanArr.value = [];
    let position = 0; // 记录当前考核项目的起始位置

    data.forEach((item, index) => {
      if (index === 0) {
        spanArr.value.push(1);
        position = 0;
      } else {
        // 当前考核项目与前一项相同时合并
        if (item.evaluationItem === data[index - 1].evaluationItem) {
          spanArr.value[position] += 1; // 起始行合并数+1
          spanArr.value.push(0); // 当前行标记为合并
        } else {
          spanArr.value.push(1); // 新考核项目组
          position = index; // 更新起始位置
        }
      }
    });
  };
  const spanMethod = ({ row, column, rowIndex, columnIndex }) => {
    // 仅对考核项目列（columnIndex=1）进行合并
    if (columnIndex === 1) {
      const _row = spanArr.value[rowIndex];
      const _col = _row > 0 ? 1 : 0;
      return [_row, _col];
    }
    return [1, 1]; // 其他列不合并
  };
  const handleSubmit = async () => {
    const res = await handleValidate();
    if (!res) return;
    try {
      if (!detailData.value) {
        ElMessage.error('数据加载失败，请刷新后重试');
        return;
      }

      // 使用详情原始数据，更新复核得分、加减分项及资料说明附件
      const updatedScores =
        (await Promise.all(
          (detailData.value.scores || []).map(async (score: any) => {
            const item = evaluationItems.value.find((row) => row.id === score.id);

            // 处理资料说明附件：将 UploadFiles 返回的文件列表转换为逗号分隔的 URL 字符串
            let attachments = score.attachments || '';
            if (item && Array.isArray(item.attachmentFileList)) {
              const existingFiles: string[] = [];
              const newFiles: any[] = [];

              item.attachmentFileList.forEach((file: any) => {
                if (file.fileUrl && !file.file) {
                  existingFiles.push(file.fileUrl);
                } else {
                  newFiles.push(file);
                }
              });

              let uploadedUrls: string[] = [];
              if (newFiles.length > 0) {
                const uploadedFiles = await formatAttachmentList(newFiles);
                uploadedUrls = uploadedFiles.map((f: any) => f.fileUrl || f.url || '').filter((url: string) => url);
              }

              attachments = [...existingFiles, ...uploadedUrls].filter((url) => url).join(',');
            }

            return {
              ...score,
              reviewScore: item ? Number(item.reviewScore) || 0 : score.reviewScore || 0,
              reviewRejectReson: item ? item.reviewRejectReson || '' : score.reviewRejectReson || '',
              isAdd: item
                ? item.isAdd !== undefined
                  ? item.isAdd
                  : item.selfScore >= 0
                  ? 1
                  : 0
                : score.isAdd !== undefined
                ? score.isAdd
                : score.selfScore >= 0
                ? 1
                : 0,
              attachments,
            };
          }),
        )) || [];

      const submitData = {
        ...detailData.value,
        scores: updatedScores,
      };

      if (isAudit.value) {
        // 审核通过
        await updateSecurityExamineIssueApproveAgree(props.id);
        ElMessage.success('审核通过操作成功');
      } else {
        // 评分模式
        if (isSelfApproveButton.value) {
          // isSelfApproveButton 为 true，调用复核同意接口
          await updateSecurityExamineIssueReviewAgree(submitData);
          ElMessage.success('提交操作成功');
        } else {
          // isSelfApproveButton 为 false，调用提交接口
          await updateSecurityExamineIssueReviewSubmit(submitData);
          ElMessage.success('保存成功');
        }
      }
      router.back();
    } catch (e: any) {
      console.error('提交失败:', e);
      ElMessage.error(e?.message || e?.data || '提交失败，请重试');
    }
  };
  const handleSubmitItem = async () => {
    const res = await handleValidate();
    if (!res) return;
    try {
      if (!detailData.value) {
        ElMessage.error('数据加载失败，请刷新后重试');
        return;
      }

      // 使用详情原始数据，更新复核得分、加减分项及资料说明附件
      const updatedScores =
        (await Promise.all(
          (detailData.value.scores || []).map(async (score: any) => {
            const item = evaluationItems.value.find((row) => row.id === score.id);

            // 处理资料说明附件：将 UploadFiles 返回的文件列表转换为逗号分隔的 URL 字符串
            let attachments = score.attachments || '';
            if (item && Array.isArray(item.attachmentFileList)) {
              const existingFiles: string[] = [];
              const newFiles: any[] = [];

              item.attachmentFileList.forEach((file: any) => {
                if (file.fileUrl && !file.file) {
                  existingFiles.push(file.fileUrl);
                } else {
                  newFiles.push(file);
                }
              });

              let uploadedUrls: string[] = [];
              if (newFiles.length > 0) {
                const uploadedFiles = await formatAttachmentList(newFiles);
                uploadedUrls = uploadedFiles.map((f: any) => f.fileUrl || f.url || '').filter((url: string) => url);
              }

              attachments = [...existingFiles, ...uploadedUrls].filter((url) => url).join(',');
            }

            return {
              ...score,
              reviewScore: item ? Number(item.reviewScore) || 0 : score.reviewScore || 0,
              reviewRejectReson: item ? item.reviewRejectReson || '' : score.reviewRejectReson || '',
              isAdd: item
                ? item.isAdd !== undefined
                  ? item.isAdd
                  : item.selfScore >= 0
                  ? 1
                  : 0
                : score.isAdd !== undefined
                ? score.isAdd
                : score.selfScore >= 0
                ? 1
                : 0,
              attachments,
            };
          }),
        )) || [];

      const submitData = {
        ...detailData.value,
        scores: updatedScores,
      };
      await updateSecurityExamineIssueReviewSubmit(submitData);
      ElMessage.success('保存成功');
      router.back();
    } catch (e: any) {
      console.error('提交失败:', e);
      ElMessage.error(e?.message || e?.data || '提交失败，请重试');
    }
  };

  const confirmReject = async () => {
    if (!rejectReason.value || !rejectReason.value.trim()) {
      ElMessage.warning('请填写驳回原因');
      return;
    }

    try {
      if (rejectType.value === 'review') {
        const submitData = {
          id: props.id,
          reviewRejectReson: rejectReason.value.trim(),
          scores: evaluationItems.value,
        };
        await updateSecurityExamineIssueReviewDisagree(submitData);
        ElMessage.success('复核不通过操作成功');
      } else {
        const submitData = {
          id: props.id,
          approveRejectReson: rejectReason.value.trim(),
          psemId: detailData.value.psemId,
        };
        await updateSecurityExamineIssueApproveDisagree(submitData);
        ElMessage.success('审核不通过操作成功');
      }
      closeRejectDialog();
      router.back();
    } catch (e: any) {
      console.error('操作失败:', e);
      ElMessage.error(e?.message || e?.data || '操作失败，请重试');
    }
  };

  // 监听 props.id 变化，重新加载数据
  watch(
    () => props.id,
    (newId) => {
      if (newId && !isNaN(newId) && newId > 0) {
        getDetail();
      }
    },
    { immediate: true },
  );
</script>

<style scoped lang="scss">
  @use '@/styles/page-details-layout.scss' as *;
  @use '@/styles/basic-table-file.scss' as *;

  .evaluation-form {
    display: flex;
    flex-direction: column;
    width: 600px;
    gap: 32px;

    :deep(.el-form-item) {
      margin-bottom: 0;
    }

    :deep(.el-form-item__label) {
      padding: 0;
    }
  }

  .evaluation-items-section {
    margin-top: 32px;
  }

  .section-header {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
  }

  .evaluation-items-table {
    width: 100%;
  }

  .upload-files-wrapper {
    width: 100%;
  }

  .upload-files-disabled {
    pointer-events: none;
    opacity: 0.6;

    :deep(.upload-button) {
      cursor: not-allowed;
      background-color: #f5f5f5;
      color: #aaa;
    }

    :deep(.delete-button) {
      display: none;
    }
  }
</style>
