<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="file-list">
          <div class="file-item" v-for="file in ruleFormData.attachmentDocument" :key="file.fileId">
            <span class="file-item--name">{{ file.fileName }}</span>
            <div class="file-item--footer">
              <el-button link type="primary" @click="previewOnline(file.fileUrl, file.fileType)"
                >预览</el-button
              >
              <el-button link type="primary" @click.stop="downloadFile(file.fileUrl, file.fileName)"
                >下载</el-button
              >
            </div>
          </div>
        </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 prop="selfScore" min-width="180">
            <template #header>
              <span class="required-star">*</span>自评得分
            </template>
            <template #default="scope">
              <el-input
                :model-value="scope.row.selfScore"
                placeholder="请输入自评得分"
                maxlength="5"
                @update:model-value="(v) => handleSelfScoreInput(scope.row, v)"
                @blur="handleScoreBlur"
              />
            </template>
          </el-table-column>
          <el-table-column prop="materialDescription" min-width="400">
            <template #header>
              <span class="required-star">*</span>资料说明
            </template>
            <template #default="scope">
              <UploadFiles
                label="上传附件"
                :file-list="scope.row.attachmentFileList"
                @uploadSuccess="(list: FileItem[]) => handleRowUploadSuccess(scope.$index, list)"
              />
            </template>
          </el-table-column>
          <el-table-column v-if="reviewRejectReson" label="复核不通过原因" prop="reviewRejectReson" min-width="220"></el-table-column>
        </el-table>
      </div>
    </div>

    <PreviewOnline ref="previewOnlineRef" />

  </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';
  import PreviewOnline from '@/views/disaster/components/PreviewOnline.vue';
  import { downloadFile } from '@/views/disaster/utils';
  const props = defineProps<{
    id: number;
  }>();

  const router = useRouter();
  const route = useRoute();
  const previewOnlineRef = ref<InstanceType<typeof PreviewOnline>>();

  // 判断是否为 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.isAdd === 2 || item.scoreType === '加分项' || item.scoreType === '基础分';
      return isAdd ? sum + score : sum - score;
    }, 0);
  };

  // 自评得分输入：仅允许数字，范围 0-99999
  const handleSelfScoreInput = (row: { selfScore?: number | null }, v: string | number) => {
    const str = String(v ?? '').replace(/\D/g, '');
    if (str === '') {
      row.selfScore = undefined as unknown as number;
      return;
    }
    const num = Math.min(Number(str), 99999);
    row.selfScore = num;
  };

  // 自评得分失去焦点时触发（用于强制更新合计行）
  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);
      });
    });
  };

  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 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 handleRowUploadSuccess = async (rowIndex: number, list: FileItem[]) => {
    if (!evaluationItems.value[rowIndex]) return;
    evaluationItems.value[rowIndex].attachmentFileList = await formatAttachmentList(list);
  };

  // 将逗号分隔的 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 = JSON.parse(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, // 自评得分
          materialDescription: score.attachments || '', // 资料说明（使用附件字段，字符串）
          reviewRejectReson: score.reviewRejectReson || '', // 复核不通过原因
          attachmentFileList: JSON.parse(score.attachments || '[]'), // 对应的附件文件列表
        }));
        generateSpanArr(evaluationItems.value);
      } else {
        evaluationItems.value = [];
      }
    } catch (e) {
      console.error('获取部门考核详情失败:', e);
      ElMessage.error(e?.message || e?.data || '获取详情失败，请重试');
    }
  };

  const handleSubmit = async () => {
    const res = await handleValidate();
    if (!res) return;
    try {
      if (!detailData.value) {
        ElMessage.error('数据加载失败，请刷新后重试');
        return;
      }

      // 校验表格中“自评得分”和“资料说明”必填
      const hasEmptyScore = evaluationItems.value.some(
        (item, index) => item.selfScore === null || item.selfScore === undefined || item.selfScore === '',
      );
      if (hasEmptyScore) {
        ElMessage.error('请填写所有考核项的自评得分');
        return;
      }

      const hasEmptyAttachment = evaluationItems.value.some(
        (item) => !Array.isArray(item.attachmentFileList) || item.attachmentFileList.length === 0,
      );
      if (hasEmptyAttachment) {
        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 = JSON.stringify(item.attachmentFileList || '[]');
              // 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 || e?.data || '提交失败，请重试');
    }
  };

  const previewOnline = (url: string | undefined, type) => {
    if (url) {
      previewOnlineRef.value?.open(url, type);
    }
  };

  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%;
  }

  .required-star {
    color: #f56c6c;
    margin-right: 2px;
  }

  .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>
