<template>
  <main class="safety-platform-container__main">
    <el-form ref="formRef" :model="formData" :rules="isAddMode ? formRules : undefined" label-width="180px" class="check-record-form">
      <el-form-item label="被检查单位：" prop="inspectedUnit">
        <el-input v-model="formData.inspectedUnit" :disabled="!isAddMode" placeholder="请输入被检查单位" clearable />
      </el-form-item>
      <el-form-item label="检查人员：" prop="inspector">
        <el-input v-model="formData.inspector" :disabled="!isAddMode" placeholder="请输入检查人员" clearable />
      </el-form-item>
      <el-form-item label="检查时间：" prop="checkTime">
        <el-date-picker
          v-if="isAddMode"
          v-model="formData.checkTime"
          type="date"
          placeholder="选择检查日期"
          value-format="YYYY-MM-DD"
          format="YYYY-MM-DD"
          style="width: 100%"
        />
        <el-input v-else v-model="formData.checkTime" disabled />
      </el-form-item>
      <el-form-item label="检查地点：" prop="checkPlace">
        <el-input v-model="formData.checkPlace" :disabled="!isAddMode" placeholder="请输入检查地点" clearable />
      </el-form-item>
      <el-form-item label="整体检查情况描述：" prop="overallDesc">
        <el-input
          v-model="formData.overallDesc"
          type="textarea"
          :rows="5"
          maxlength="300"
          show-word-limit
          :disabled="!isAddMode"
          :placeholder="isAddMode ? '请输入整体检查情况描述（限300字）' : '整体检查情况描述（限300字）'"
        />
      </el-form-item>
      <el-form-item label="被检查人签字文件：" prop="signFile">
        <div v-if="!isAddMode" class="upload-files-disabled">
          <UploadFiles label="上传附件" :file-list="displayFileList" />
        </div>
        <UploadFiles
          v-else
          label="上传附件"
          :file-list="displayFileList"
          @uploadSuccess="handleUploadSuccess"
        />
      </el-form-item>
    </el-form>

    <div class="check-items-section">
      <div class="section-header">
        <span class="section-title">检查明细</span>
      </div>
      <el-table :data="checkItems" border class="check-items-table">
        <el-table-column type="index" label="编号" width="80" align="center" />
        <el-table-column prop="checkContent" label="检查内容" min-width="200" />
        <el-table-column prop="checkStandard" label="检查标准" min-width="200" />
        <el-table-column label="检查结果" width="160" align="center">
          <template #default="{ row }">
            <el-radio-group v-if="isAddMode" v-model="row.checkResult" size="small">
              <el-radio value="合格">合格</el-radio>
              <el-radio value="不合格">不合格</el-radio>
              <el-radio value="待检">待检</el-radio>
            </el-radio-group>
            <span v-else>{{ row.checkResult || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="检查发现问题" min-width="200">
          <template #default="{ row }">
            <el-input v-if="isAddMode" v-model="row.checkProblem" placeholder="请输入检查发现问题" clearable />
            <span v-else>{{ row.checkProblem || '-' }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <footer v-if="isAddMode" class="safety-platform-container__footer">
      <el-button @click="handleBack">返回</el-button>
      <el-button type="primary" @click="handleSubmit">提交</el-button>
    </footer>
  </main>
</template>

<script setup lang="ts">
  import { computed, onMounted, ref } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import UploadFiles from '@/components/UploadFiles/UploadFiles.vue';
  import type { FileItem } from '@/components/UploadFiles/types';
  import {
    queryAreaCheckRecordDept,
    queryAreaCheckRecordTemplateDept,
    saveAreaCheckPlanDetailDept,
    type AreaCheckRecordTemplateItem,
  } from '@/api/production-safety-system';

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

  const operate = computed(() => (route.query.operate as string) || '');
  const isAddMode = computed(() => operate.value === 'area-check-plan-record-add');
  const recordId = computed(() => Number(route.query.recordId));
  const planId = computed(() => Number(route.query.planId));

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

  const formRules = {
    inspectedUnit: [{ required: true, message: '请输入被检查单位', trigger: 'blur' }],
    inspector: [{ required: true, message: '请输入检查人员', trigger: 'blur' }],
    checkTime: [{ required: true, message: '请选择检查时间', trigger: 'change' }],
    checkPlace: [{ required: true, message: '请输入检查地点', trigger: 'blur' }],
  };

  interface CheckItem {
    checkContent: string;
    checkStandard: string;
    checkResult: string;
    checkProblem: string;
  }

  const checkItems = ref<CheckItem[]>([]);

  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 = ref<FileItem[]>([]);
  const displayFileList = computed(() => {
    if (isAddMode.value) return signFileList.value;
    return convertSignFileToFileItems(formData.value.signFile || '');
  });

  const handleUploadSuccess = (files: FileItem[]) => {
    signFileList.value = files;
    formData.value.signFile = files
      .map((f) => f.fileUrl || f.fileName)
      .filter(Boolean)
      .join(',');
  };

  const handleBack = () => {
    router.back();
  };

  const handleSubmit = async () => {
    if (!formRef.value) return;
    const valid = await formRef.value.validate().catch(() => false);
    if (!valid) return;
    if (!planId.value) {
      ElMessage.error('缺少关联的区域检查计划ID，无法提交');
      return;
    }
    try {
      await saveAreaCheckPlanDetailDept({
        areaPlanId: planId.value,
        checkedCompanyName: formData.value.inspectedUnit,
        checkTime: formData.value.checkTime,
        checkPersonName: formData.value.inspector,
        // 暂无人员 code 来源，前端先不传或由后端根据名称解析
        checkAddress: formData.value.checkPlace,
        overallCheckDesc: formData.value.overallDesc,
        checkedPersonSign: formData.value.signFile,
        areaCheckRecords: checkItems.value.map((item) => ({
          checkContent: item.checkContent || '',
          checkStandard: item.checkStandard || '',
          // 新增检查日志时，检查结果和问题直接使用接口返回的数据
          checkResult: item.checkResult || '',
          checkProblem: item.checkProblem || '',
        })),
      });
      ElMessage.success('提交成功');
      router.back();
    } catch (e) {
      console.error('新增检查日志提交失败:', e);
      ElMessage.error(e?.message || e?.data || '提交失败，请稍后重试');
    }
  };

  const loadRecordDetail = async () => {
    if (recordId.value) {
      try {
        const res = await queryAreaCheckRecordDept(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((item) => ({
          checkContent: (item.checkContent ?? '') as string,
          checkStandard: (item.checkStandard ?? '') as string,
          checkResult: (item.checkResult ?? '') as string,
          checkProblem: (item.checkProblem ?? '') as string,
        }));
      } catch (e) {
        console.error('获取检查记录详情失败:', e);
      }
    } else {
      // 无 recordId 的查看场景，只保留空表单和空检查明细（不依赖路由传递数据）
      formData.value = {
        inspectedUnit: '',
        inspector: '',
        checkTime: '',
        checkPlace: '',
        overallDesc: '',
        signFile: '',
      };
      checkItems.value = [];
    }
  };

  const loadTemplateCheckItems = async () => {
    // 使用部门模板接口获取“新增检查日志”的检查明细
    if (!planId.value) {
      // 没有计划ID时，不展示任何检查明细
      checkItems.value = [];
      return;
    }
    try {
      const res = await queryAreaCheckRecordTemplateDept(planId.value);
      const list = ((res as { data?: AreaCheckRecordTemplateItem[] })?.data ?? res) || [];
      if (Array.isArray(list) && list.length > 0) {
        checkItems.value = list
      } else {
        // 模板为空时，不展示任何检查明细
        checkItems.value = [];
      }
    } catch (e) {
      console.error('获取检查明细模板失败:', e);
      // 接口异常时不影响表单填写，但不展示任何假数据
      checkItems.value = [];
    }
  };

  const initFormData = async () => {
    if (isAddMode.value) {
      const { planName, checkVenue } = route.query;
      formData.value = {
        inspectedUnit: planName ? String(planName) : '',
        inspector: '',
        checkTime: '',
        checkPlace: checkVenue ? String(checkVenue) : '',
        overallDesc: '',
        signFile: '',
      };
      signFileList.value = [];
      await loadTemplateCheckItems();
    } else {
      await loadRecordDetail();
    }
  };

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

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

  .check-record-form {
    max-width: 900px;
    margin-bottom: 24px;
  }

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

    .section-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 12px;

      .section-title {
        font-weight: 600;
        font-size: 15px;
      }
    }
  }

  .check-items-table {
    :deep(.el-textarea__inner) {
      border: none;
      box-shadow: none;
      padding: 4px 0;
    }
  }

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