<template>
  <div class="area-check-plan-record-detail">
    <main class="safety-platform-container__main">
      <el-form :model="formData" label-width="auto" class="check-record-form">
        <el-form-item label="被检查单位：">
          <el-input v-model="formData.inspectedUnit" disabled />
        </el-form-item>
        <el-form-item label="检查人员：">
          <el-input v-model="formData.inspector" disabled />
        </el-form-item>
        <el-form-item label="检查时间：">
          <el-input v-model="formData.checkTime" disabled />
        </el-form-item>
        <el-form-item label="检查地点：">
          <el-input v-model="formData.checkPlace" disabled />
        </el-form-item>
        <el-form-item label="整体检查情况描述：">
          <el-input
            v-model="formData.overallDesc"
            type="textarea"
            :rows="5"
            maxlength="300"
            show-word-limit
            disabled
            placeholder="整体检查情况描述（限300字）"
          />
        </el-form-item>
        <el-form-item label="被检查人签字文件：">
          <div class="upload-files-disabled">
            <UploadFiles
              label="上传附件"
              :file-list="signFileList"
            />
          </div>
        </el-form-item>
      </el-form>

      <div class="check-items-section">
        <div class="section-header">
          <span class="section-title">检查明细</span>
        </div>
        <div class="check-items-table">
          <el-table :data="checkItems" border>
            <el-table-column type="index" label="编号" width="80" align="center" />
            <el-table-column prop="checkContent" label="检查内容" min-width="180" />
            <el-table-column prop="checkStandard" label="检查标准" min-width="180" />
            <el-table-column prop="checkResult" label="检查结果" min-width="120" align="center" />
            <el-table-column prop="checkProblem" label="检查发现问题" min-width="200" />
          </el-table>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
  import { computed, onMounted, ref } from 'vue';
  import { useRoute } from 'vue-router';
  import UploadFiles from '@/components/UploadFiles/UploadFiles.vue';
  import type { FileItem } from '@/components/UploadFiles/types';
  import { queryAreaCheckRecord } from '@/api/production-safety-system';

  const route = useRoute();
  const recordId = computed(() => Number(route.query.recordId));

  const formData = ref({
    inspectedUnit: '',
    inspector: '',
    checkTime: '',
    checkPlace: '',
    overallDesc: '',
    signFile: '',
  });

  /** 将签字文件（逗号分隔URL或文件名）转换为 UploadFiles 使用的 FileItem 列表，复用新增安全考核上传附件文档字段样式 */
  function convertSignFileToFileItems(attachmentsStr: string): FileItem[] {
    if (!attachmentsStr || !String(attachmentsStr).trim()) return [];
    const urls = String(attachmentsStr)
      .split(',')
      .map((u) => u.trim())
      .filter(Boolean);
    return urls.map((url, index) => {
      const parts = url.split('/');
      const fileName = parts[parts.length - 1] || `附件${index + 1}`;
      const ext = fileName.split('.').pop()?.toLowerCase() || '';
      let fileType = 'pdf';
      if (['doc', 'docx'].includes(ext)) fileType = 'word';
      else if (['xls', 'xlsx'].includes(ext)) fileType = 'excel';
      else if (['ppt', 'pptx'].includes(ext)) fileType = 'ppt';
      return { fileId: index + 1, fileName, fileType, fileSize: '0', fileUrl: url };
    });
  }

  const signFileList = computed<FileItem[]>(() => convertSignFileToFileItems(formData.value.signFile || ''));

  const checkItems = ref<Array<{
    checkContent?: string;
    checkStandard?: string;
    checkResult?: string;
    checkProblem?: string;
  }>>([]);

  const loadRecordDetail = async () => {
    if (!recordId.value) {
      // 新增检查日志：全部为空数据
      formData.value = {
        inspectedUnit: '',
        inspector: '',
        checkTime: '',
        checkPlace: '',
        overallDesc: '',
        signFile: '',
      };
      checkItems.value = [];
      return;
    }
    try {
      const res = await queryAreaCheckRecord(recordId.value);
      const raw = (res as { data?: Record<string, unknown> })?.data ?? res;
      const r = raw as Record<string, unknown>;
      formData.value = {
        inspectedUnit: String(r?.checkedCompanyName ?? r?.checkedCompany ?? ''),
        inspector: String(r?.checkPersonName ?? r?.checkPerson ?? ''),
        checkTime: String(r?.checkTime ?? ''),
        checkPlace: String(r?.checkAddress ?? r?.checkPlace ?? ''),
        overallDesc: String(r?.overallCheckDesc ?? ''),
        signFile: String(r?.checkedPersonSign ?? ''),
      };
      const records = (r?.areaCheckRecords ?? []) as Array<Record<string, unknown>>;
      checkItems.value = records.map((r) => ({
        checkContent: r.checkContent as string,
        checkStandard: r.checkStandard as string,
        checkResult: r.checkResult as string,
        checkProblem: r.checkProblem as string,
      }));
    } catch (e) {
      console.error('获取检查记录详情失败:', e);
    }
  };

  onMounted(() => loadRecordDetail());
</script>

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

  .check-record-form {
    max-width: 800px;
  }

  .check-items-section {
    margin-top: 16px;

    .section-header {
      margin-bottom: 8px;
      .section-title {
        font-weight: 600;
      }
    }
  }

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

