<template>
  <main class="safety-platform-container__main">
    <!-- 复核不通过提示条：仅在 evaluationDepartment-feedback 且 reviewRejectReson 有值时显示 -->
    <el-alert
      v-if="isFeedbackOperate && reviewRejectReson"
      type="error"
      :title="`复核不通过原因：${reviewRejectReson}`"
      show-icon
      class="reject-alert"
    />
    <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">
          <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="180">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.selfScore"
                :min="0"
                :max="99999"
                :precision="0"
                :step="1"
                placeholder="请输入自评得分"
                @blur="handleScoreBlur"
              />
            </template>
          </el-table-column>
          <el-table-column label="资料说明" prop="materialDescription" min-width="400">
            <template #default="scope">
              <UploadFiles
                label="上传附件"
                :file-list="scope.row.attachmentFileList"
                @uploadSuccess="(files: FileItem[]) => handleRowUploadSuccess(scope.$index, files)"
              />
            </template>
          </el-table-column>
          <el-table-column label="复核不通过原因" prop="reviewRejectReson" min-width="220"></el-table-column>
        </el-table>
      </div>
    </div>
  </main>
  <footer class="safety-platform-container__footer">
    <el-button @click="router.back()">取消</el-button>
    <el-button type="primary" @click="handleSubmit">提交</el-button>
  </footer>
</template>

<script setup lang="ts">
  import { computed, onMounted, ref } 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 {
    querySecurityExamineIssueDeptDetail,
    updateSecurityExamineDeptSubmit,
    exportSecurityExamineIssueDeptDetail,
    importSecurityExamineIssueDeptDetail,
  } from '@/api/evaluationSystem';
  import type { FileItem } from '@/components/UploadFiles/types';
  import { formatAttachmentList } from '@/components/UploadFiles/utils';

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

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

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

  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);

  // 复核拒绝原因（用于顶部提示条，仅 evaluationDepartment-feedback 时展示）
  const reviewRejectReson = computed(() => {
    const val = detailData.value?.reviewRejectReson;
    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.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') {
        // 自评得分列显示总分，即使为0也显示
        const total = getTotalScore();
        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[]) => {
    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 || '导入失败，请重试');
    } 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 || '导出失败，请重试');
    }
  };

  // 行内上传附件成功
  const handleRowUploadSuccess = (rowIndex: number, files: FileItem[]) => {
    if (!evaluationItems.value[rowIndex]) return;
    evaluationItems.value[rowIndex].attachmentFileList = files;
  };

  // 将逗号分隔的 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 () => {
    try {
      const detail = await querySecurityExamineIssueDeptDetail(props.id);
      if (!detail) return;

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

      // 映射表单字段
      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-是）
          isAddName: score.isAdd === 1 ? '加分项' : '减分项', // 加减分项名称
          scoreType: score.isAdd === 1 ? '加分项' : '减分项', // 加减分项（用于显示，兼容旧字段）
          evaluationItem: score.exProgram || '', // 考核项目
          evaluationContent: score.exContent || '', // 考核内容
          scoringMethod: score.scoringWay || '', // 评分方式
          selfScore: score.selfScore || 0, // 自评得分
          materialDescription: score.attachments || '', // 资料说明（使用附件字段，字符串）
          reviewRejectReson: score.reviewRejectReson || '', // 复核不通过原因
          attachmentFileList: parseAttachmentsToFileList(score.attachments || ''), // 对应的附件文件列表
        }));
      } else {
        evaluationItems.value = [];
      }
    } catch (e) {
      console.error('获取部门考核详情失败:', e);
      ElMessage.error('获取详情失败，请重试');
    }
  };

  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,
              selfScore: item ? Number(item.selfScore) || 0 : score.selfScore || 0,
              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 updateSecurityExamineDeptSubmit(submitData);
      ElMessage.success('提交成功');
      router.back();
    } catch (e: any) {
      console.error('提交失败:', e);
      ElMessage.error(e?.message || '提交失败，请重试');
    }
  };

  onMounted(() => {
    getDetail();
  });
</script>

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

  .reject-alert {
    margin-bottom: 20px;
  }

  .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-disabled {
    pointer-events: none;
    opacity: 0.6;

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

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