<template>
  <!-- 查看模式：由 顶部摘要、基本信息、检查内容与业务工作、检查记录 组成 -->
  <main v-if="isViewMode" class="safety-platform-container__main area-check-plan-view">
    <section class="view-section view-summary">
      <div class="view-summary__title">一级危险点：{{ viewDetail.checkVenue || '-' }}</div>
      <div class="view-summary__meta">
        <span>检查类别：{{ viewDetail.venueCategoryName || '-' }}</span>
        <span>创建人：{{ viewDetail. createdPersonName || '-' }}</span>
        <span>创建时间：{{ viewDetail.createdAt || '-' }}</span>
      </div>
    </section>

    <section class="view-section audit-content">
      <h4 class="section-title">
        <el-icon class="section-title__icon"><Document /></el-icon>
        <span>基本信息</span>
      </h4>
      <div class="detail-ct detail-ct--table">
        <div class="row">
          <div class="col">
            <div class="label">区域计划名称：</div>
            <div class="value">{{ viewDetail.planName || '-' }}</div>
          </div>
          <div class="col">
            <div class="label">状态：</div>
            <div class="value">{{ viewDetail.statusName || '进行中' }}</div>
          </div>
        </div>
        <div class="row">
          <div class="col">
            <div class="label">主责部门：</div>
            <div class="value">{{ viewDetail.primaryResponsibleDeptName || '-' }}</div>
          </div>
          <div class="col">
            <div class="label">自查频率：</div>
            <div class="value">{{ viewDetail.selfCheckFrequency || '-' }}</div>
          </div>
        </div>
        <div class="row">
          <div class="col">
            <div class="label">主责部门执行人所属分组名称：</div>
            <div class="value">{{ viewDetail.primaryResponsibleDeptExecGroupName || '-' }}</div>
          </div>
          <div class="col">
            <div class="label">主责部门责任人：</div>
            <div class="value">{{ viewDetail.primaryResponsibleDeptPersonName || '-' }}</div>
          </div>
        </div>
        <div class="row">
          <div class="col">
            <div class="label">安全应急部部门名称：</div>
            <div class="value">{{ viewDetail.safetyEmergencyDeptName || '-' }}</div>
          </div>
          <div class="col">
            <div class="label">安全应急部检查频次：</div>
            <div class="value">{{ viewDetail.safetyEmergencyCheckFrequency || '-' }}</div>
          </div>
        </div>
        <div class="row">
          <div class="col">
            <div class="label">安全应急部执行人所属分组名称：</div> 
            <div class="value">{{ viewDetail.safetyEmergencyExecGroupName || '-' }}</div>
          </div>
          <div class="col">
            <div class="label">安全应急部责任人：</div>
            <div class="value">{{ viewDetail.safetyEmergencyPersonName || '-' }}</div>
          </div>
        </div>
        <div class="row">
          <div class="col">
            <div class="label">院领导部门名称：</div>
            <div class="value">{{ viewDetail.hospitalLeaderDeptName || '-' }}</div>
          </div>
          <div class="col">
            <div class="label">院领导检查频次：</div>
            <div class="value">{{ viewDetail.hospitalLeaderCheckFrequency || '-' }}</div>
          </div>
        </div>
        <div class="row">
          <div class="col">
            <div class="label">院领导执行人所属分组名称：</div>
            <div class="value">{{ viewDetail.hospitalLeaderExecGroupName || '-' }}</div>
          </div>
          <div class="col">
            <div class="label">院领导责任人：</div>
            <div class="value">{{ viewDetail.hospitalLeaderPersonName || '-' }}</div>
          </div>
        </div>
        <div class="row">
          <div class="col">
            <div class="label">检查单所属类别名称：</div>
            <div class="value">{{ viewDetail.categoryName || '-' }}</div>
          </div>
          <div class="col">
            <div class="label">检查单模版名称：</div>
            <div class="value">{{ viewDetail.checklistTemplateName || '-' }}</div>
          </div>
        </div>
        <div class="row">
          <div class="col">
            <div class="label">是否需要整体检查情况描述：</div>
            <div class="value">{{ viewDetail.needOverallDesc === true ? '是' : viewDetail.needOverallDesc === false ? '否' : '-' }}</div>
          </div>
          <div class="col">
            <div class="label">是否需要被检查人签字：</div>
            <div class="value">{{ viewDetail.needSigneeSign === true ? '是' : viewDetail.needSigneeSign === false ? '否' : '-' }}</div>
          </div>
        </div>
        <div class="row">
          <div class="col">
            <div class="label">计划开始日期：</div>
            <div class="value">{{ viewDetail.planStartTime || '-' }}</div>
          </div>
          <div class="col">
            <div class="label">计划完成日期：</div>
            <div class="value">{{ viewDetail.planEndTime || '-' }}</div>
          </div>
        </div>
        <div class="row">
          <div class="col">
            <div class="label">检查内容：</div>
            <div class="value value--list">
              <ol class="inspection-content-list">
                <li v-for="(item, i) in inspectionContentList" :key="i">{{ item }}</li>
              </ol>
            </div>
          </div>
          <div class="col">
            <div class="label">业务工作：</div>
            <div class="value">{{ viewDetail.businessWork || '-' }}</div>
          </div>
        </div>
      </div>
    </section>

    <section class="view-section">
      <div class="view-section__title">
        <span class="view-section__icon" />
        检查记录
      </div>
      <div class="view-record-toolbar">
        <el-input
          v-model="recordSearchKeyword"
          placeholder="检查场所类别/检查场所/检查人员"
          clearable
          style="width: 280px; margin-right: 12px"
        />
        <el-date-picker
          v-model="recordDateRange"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          style="margin-right: 12px;max-width: 280px;"
        />
        <el-button type="primary" class="view-record-toolbar-btn" @click="onRecordSearch">查询</el-button>
        <el-button @click="onRecordExport">导出</el-button>
      </div>
      <BasicTable
        :tableData="paginatedRecordList"
        :tableConfig="recordTableConfig"
        class="view-record-table"
        @update:pageSize="handleRecordSizeChange"
        @update:pageNumber="handleRecordPageChange"
      >
        <template #unqualifiedItemNum="scope">
          <el-button
            type="primary"
            link
            size="small"
            @click="openUnqualifiedDialog(scope.row)"
          >
            {{ scope.row.unqualifiedItemNum ?? 0 }}
          </el-button>
        </template>
        <template #sign="scope">
          <template v-if="JSON.parse(scope.row.checkedPersonSign || '[]').length">
            <div
              class="file-container--div"
              v-for="item in JSON.parse(scope.row.checkedPersonSign || '[]')"
              :key="item.fileUrl || item.fileName"
            >
              <!-- <img
                class="file-container--div__icon"
                :src="FILE_TYPE_ICON[item.fileType as keyof typeof FILE_TYPE_ICON]"
                @click="previewOnline(item.fileUrl, item.fileType as keyof typeof FILE_TYPE_ICON)"
              /> -->
              <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>
          <span v-else>-</span>
        </template>
        <template #action="scope">
          <el-button type="danger" link size="small" @click="onDeleteRecord(scope.row)">删除</el-button>
          <el-button type="primary" link size="small" @click="onViewRecord(scope.row)">检查记录查看</el-button>
        </template>
      </BasicTable>
    </section>
  </main>

  <main v-else class="safety-platform-container__main">
    <BasicForm
      ref="basicFormRef"
      :formData="ruleFormData"
      :formRules="isViewMode ? undefined : formRules"
      :formConfig="computedFormConfig"
    >
      <template #primaryResponsibleDept>
        <el-cascader
          ref="primaryResponsibleDeptCascaderRef"
          v-model="ruleFormData.primaryResponsibleDeptId"
          :options="deptTree"
          :props="cascaderDeptProp"
          :show-all-levels="false"
          placeholder="请选择部门"
          filterable
          clearable
          :disabled="isViewMode"
          style="width: 100%"
          @change="onPrimaryResponsibleDeptChange"
        />
      </template>
      <template #safetyEmergencyDept>
        <el-cascader
          ref="safetyEmergencyDeptCascaderRef"
          v-model="ruleFormData.safetyEmergencyDeptId"
          :options="deptTree"
          :props="cascaderDeptProp"
          :show-all-levels="false"
          placeholder="请选择部门"
          filterable
          clearable
          :disabled="isViewMode"
          style="width: 100%"
          @change="onSafetyEmergencyDeptChange"
        />
      </template>
      <template #hospitalLeaderDept>
        <el-cascader
          ref="hospitalLeaderDeptCascaderRef"
          v-model="ruleFormData.hospitalLeaderDeptId"
          :options="deptTree"
          :props="cascaderDeptProp"
          :show-all-levels="false"
          placeholder="请选择部门"
          filterable
          clearable
          :disabled="isViewMode"
          style="width: 100%"
          @change="onHospitalLeaderDeptChange"
        />
      </template>
      <template #selfCheckFrequency>
        <el-radio-group v-model="ruleFormData.selfCheckFrequency" :disabled="isViewMode">
          <el-radio
            v-for="opt in CHECK_FREQUENCY_OPTIONS"
            :key="opt.value"
            :value="opt.value"
          >
            {{ opt.label }}
          </el-radio>
        </el-radio-group>
      </template>
      <template #safetyEmergencyCheckFrequency>
        <el-radio-group v-model="ruleFormData.safetyEmergencyCheckFrequency" :disabled="isViewMode">
          <el-radio
            v-for="opt in CHECK_FREQUENCY_OPTIONS"
            :key="opt.value"
            :value="opt.value"
          >
            {{ opt.label }}
          </el-radio>
        </el-radio-group>
      </template>
      <template #hospitalLeaderCheckFrequency>
        <el-radio-group v-model="ruleFormData.hospitalLeaderCheckFrequency" :disabled="isViewMode">
          <el-radio
            v-for="opt in CHECK_FREQUENCY_OPTIONS"
            :key="opt.value"
            :value="opt.value"
          >
            {{ opt.label }}
          </el-radio>
        </el-radio-group>
      </template>
      <template #venueCategoryName>
        <el-select
          v-model="ruleFormData.venueCategoryName"
          placeholder="请选择检查类别"
          filterable
          clearable
          :disabled="isViewMode"
          style="width: 100%"
        >
          <el-option
            v-for="item in venueCategoryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </template>
    </BasicForm>
  </main>
  <footer class="safety-platform-container__footer">
    <el-button @click="router.back()">返回</el-button>
    <el-button v-if="!isViewMode" type="primary" @click="handleSubmit">
      {{ isCreateMode ? '提交' : '保存' }}
    </el-button>
  </footer>
  <PreviewOnline ref="previewOnlineRef" />

  <!-- 检查不合格数据弹窗（管理员） -->
  <el-dialog
    v-model="showUnqualifiedDialog"
    title="检查不合格数据"
    width="800px"
    destroy-on-close
  >
    <BasicTable
      :tableData="unqualifiedList"
      :tableConfig="unqualifiedTableConfig"
      @update:pageSize="handleUnqualifiedSizeChange"
      @update:pageNumber="handleUnqualifiedPageChange"
    >
      <template #action="scope">
        <el-button
          v-if="Number(scope.row.IsSand) == 0"
          type="primary"
          link
          size="small"
          @click="handleSandToHiddenDanger(scope.row)"
        >
          入账
        </el-button>
        <span v-else-if="Number(scope.row.IsSand) == 1" style="color: #999999">已入账</span>
        <span v-else>-</span>
      </template>
    </BasicTable>
  </el-dialog>

  <!-- 检查记录入账隐患台账确认弹窗 -->
  <el-dialog
    v-model="showSandConfirmDialog"
    title="检查记录入账隐患台账"
    width="900px"
    destroy-on-close
  >
    <BasicForm
      ref="sandHiddenDangerFormRef"
      :formData="sandHiddenDangerFormData"
      :formRules="sandHiddenDangerFormRules"
      :formConfig="sandHiddenDangerFormConfig"
    >
      <template #reviewDepartmentId>
        <el-cascader
          v-model="sandHiddenDangerFormData.reviewDepartmentId"
          :options="deptTree"
          :props="cascaderDeptProp"
          :show-all-levels="false"
          placeholder="请选择复查人员所属部门"
          filterable
          clearable
          style="width: 100%"
        />
      </template>
      <template #reviewPerson>
        <el-select
          v-model="sandHiddenDangerFormData.reviewPersonId"
          placeholder="请选择复查人员"
          clearable
          filterable
          style="width: 100%"
        >
          <el-option
            v-for="u in reviewUserList"
            :key="u.id"
            :label="u.realname || u.username"
            :value="u.id"
          />
        </el-select>
      </template>
      <template #isDrawLessonsPush>
        <el-radio-group v-model="sandHiddenDangerFormData.isDrawLessonsPush">
          <el-radio :value="0">否</el-radio>
          <el-radio :value="1">是</el-radio>
        </el-radio-group>
      </template>
      <template #drawLessonsDepartmentIds>
        <el-select
          v-model="drawLessonsDeptIdsArray"
          placeholder="请选择举一反三责任部门，可多选"
          clearable
          filterable
          multiple
          collapse-tags
          collapse-tags-tooltip
          style="width: 100%"
          @change="() => { sandHiddenDangerFormData.drawLessonsDepartmentIds = drawLessonsDeptIdsArray.join(','); }"
        >
          <el-option
            v-for="d in deptOptions"
            :key="d.id"
            :label="d.deptName"
            :value="d.id"
          />
        </el-select>
      </template>
    </BasicForm>
    <template #footer>
      <el-button @click="showSandConfirmDialog = false">取消</el-button>
      <el-button type="primary" :loading="sandConfirmLoading" @click="confirmSandToHiddenDanger">
        提交
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { computed, onMounted, ref, watch } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import { Document } from '@element-plus/icons-vue';
  import BasicForm from '@/components/BasicForm.vue';
  import BasicTable from '@/components/BasicTable.vue';
  import { FILE_TYPE_ICON } from '@/components/UploadFiles/constants';
  import DownloadIcon from '@/views/disaster/disaster-control/src/svg/download.svg';
  import PreviewOnline from '@/views/disaster/components/PreviewOnline.vue';
  import { downloadFile } from '@/views/disaster/utils';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import type { TableColumnProps } from '@/types/basic-table';
  import {
    AREA_CHECK_PLAN_FORM_CONFIG as AREA_CHECK_PLAN_FORM_CONFIG_IMPORT,
    AREA_CHECK_PLAN_FORM_DATA as AREA_CHECK_PLAN_FORM_DATA_IMPORT,
    AREA_CHECK_PLAN_FORM_RULES as AREA_CHECK_PLAN_FORM_RULES_IMPORT,
    CHECK_FREQUENCY_OPTIONS as CHECK_FREQUENCY_OPTIONS_IMPORT,
  } from '../configs/form';
  import type { AreaCheckPlanRecord } from '../configs/types';
  import { AREA_CHECK_PLAN_STATUS_LABEL } from '../configs/status';
  import { getAllDepartments } from '@/api/auth/dept';
  import type { DeptTree } from '@/types/dept/type';
  import { cloneDeep } from 'lodash-es';
  import {
    queryAreaCheckPlanManageDetail,
    saveAreaCheckPlanManage,
    updateAreaCheckPlanManage,
    queryAreaCheckPlanDetailPage,
    deleteAreaCheckPlanDetail,
    queryAreaCheckRecord,
    mapAreaCheckPlanApiRecordToUi,
    queryCheckListTemplateNameList,
    queryUnqualifiedItemNumPage,
    sandAreaCheckRecordToProductionHiddenDanger,
    exportInspectionRecordTow,
    type ChecklistTemplate,
    type UnqualifiedItemNumRecord,
    type SandAreaCheckRecordToHiddenDangerReq,
  } from '@/api/production-safety-system';
  import { queryDictTypeDetail } from '@/api/dict';
  import {
    HIDDEN_DANGER_FORM_CONFIG,
    HIDDEN_DANGER_FORM_DATA,
    HIDDEN_DANGER_FORM_RULES,
  } from '@/views/production-safety/hiddenTroubleInvestigationAndGovernance/hiddenTroubleAccountManagement/configs/form';
  import { downloadByData } from '@/utils/file/download';
import { id } from 'element-plus/es/locale';

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

  const operate = computed(() => (route.query.operate as string) || 'area-check-plan-create');
  const currentId = computed(() => Number(route.query.id));
  const isCreateMode = computed(() => operate.value === 'area-check-plan-create');
  const isEditMode = computed(() => operate.value === 'area-check-plan-edit');
  const isViewMode = computed(() => operate.value === 'area-check-plan-view');
  const venueCategoryOptions = ref<Array<{ label: string; value: string }>>([]);
  const AREA_CHECK_PLAN_FORM_CONFIG = AREA_CHECK_PLAN_FORM_CONFIG_IMPORT ?? [];
  const AREA_CHECK_PLAN_FORM_DATA = AREA_CHECK_PLAN_FORM_DATA_IMPORT ?? {};
  const AREA_CHECK_PLAN_FORM_RULES = AREA_CHECK_PLAN_FORM_RULES_IMPORT ?? {};
  const CHECK_FREQUENCY_OPTIONS = CHECK_FREQUENCY_OPTIONS_IMPORT ?? [];

  const { ruleFormData, formRules, ruleFormConfig, cloneRuleFormData } = useFormConfigHook(
    AREA_CHECK_PLAN_FORM_CONFIG,
    AREA_CHECK_PLAN_FORM_DATA as Record<string, unknown>,
    AREA_CHECK_PLAN_FORM_RULES,
  );

  // 部门树，与新增物品领取记录页的部门下拉一致（getAllDepartments，取第一级 children）
  const primaryResponsibleDeptCascaderRef = ref();
  const safetyEmergencyDeptCascaderRef = ref();
  const hospitalLeaderDeptCascaderRef = ref();
  const deptTree = ref<DeptTree[]>([]);
  const cascaderDeptProp = {
    checkStrictly: true,
    expandTrigger: 'hover' as const,
    value: 'id',
    label: 'deptName',
    emitPath: false,
  };

  /** 部门树：主责部门、安全应急部门、院领导部门均使用 getAllDepartments 接口 */
  const getDeptTreeData = async () => {
    try {
      const res = await getAllDepartments();
      deptTree.value = res?.[0]?.children ?? [];
    } catch (e) {
      console.error('获取部门树失败:', e);
      deptTree.value = [];
    }
  };

  const findDeptIdByName = (nodes: DeptTree[] | undefined, name: string): number | undefined => {
    if (!nodes?.length) return undefined;
    for (const n of nodes) {
      if (n.deptName === name) return n.id ?? undefined;
      const found = findDeptIdByName(n.children, name);
      if (found != null) return found;
    }
    return undefined;
  };

  const setDeptNameFromCascader = (refVal: any, nameKey: 'primaryResponsibleDeptName' | 'safetyEmergencyDeptName' | 'hospitalLeaderDeptName') => {
    const nodes = refVal?.getCheckedNodes?.();
    const label = nodes?.[0]?.label ?? '';
    const value = nodes?.[0]?.value;
    ruleFormData[nameKey] = label;
    if (nameKey === 'primaryResponsibleDeptName') {
      ruleFormData.primaryResponsibleDeptCode = value != null ? String(value) : '';
    }
  };

  const onPrimaryResponsibleDeptChange = () => {
    setDeptNameFromCascader(primaryResponsibleDeptCascaderRef.value, 'primaryResponsibleDeptName');
  };
  const onSafetyEmergencyDeptChange = () => {
    setDeptNameFromCascader(safetyEmergencyDeptCascaderRef.value, 'safetyEmergencyDeptName');
  };
  const onHospitalLeaderDeptChange = () => {
    setDeptNameFromCascader(hospitalLeaderDeptCascaderRef.value, 'hospitalLeaderDeptName');
  };

  // 检查单模版类别：使用 admin/dict/queryDictTypeDetail 接口
  const checklistCategoryOptions = ref<Array<{ label: string; value: string }>>([]);
  const loadChecklistCategoryOptions = async () => {
    try {
      const res = await queryDictTypeDetail('checklist_template');
      const list = res?.sysDictDataList ?? [];
      checklistCategoryOptions.value = list.map((item) => ({
        label: item.itemValue,
        value: item.itemCode,
      }));
    } catch (e) {
      console.error('获取检查单模版类别字典失败:', e);
      checklistCategoryOptions.value = [];
    }
  };
  // 检查单模版名称：来自接口，可按类别筛选
  const checklistTemplateOptions = ref<Array<{ label: string; value: string }>>([]);
  const allChecklistTemplates = ref<ChecklistTemplate[]>([]);

  /** 根据类别名称（form 静态选项的 value）筛选模版下拉 */
  const updateChecklistTemplateOptionsByCategory = (categoryName?: string) => {
    const list = allChecklistTemplates.value || [];
    const filtered = categoryName
      ? list.filter((item) => (item.categoryName as string) === categoryName)
      : list;
    checklistTemplateOptions.value = filtered
      .filter((item) => !!item.templateName)
      .map((item) => ({
        label: item.templateName as string,
        value: item.templateName as string,
      }));
  };

  /** 加载检查单模版名称列表（仅模版名称下拉用，类别用 form 静态数据） */
  const loadChecklistTemplateOptions = async () => {
    try {
      const res = await queryCheckListTemplateNameList();
      const list = ((res as { data?: ChecklistTemplate[] })?.data ?? (res as ChecklistTemplate[] | undefined)) || [];
      allChecklistTemplates.value = list;
      const currentCategoryName = ruleFormData.categoryName as string | undefined;
      updateChecklistTemplateOptionsByCategory(currentCategoryName);
    } catch (e) {
      console.error('获取检查单模版名称列表失败:', e);
      checklistTemplateOptions.value = [];
    }
  };

  const viewFormConfig = ref(
    AREA_CHECK_PLAN_FORM_CONFIG.map((item) => ({
      ...item,
      componentProps: {
        ...item.componentProps,
        disabled: true,
      },
    })),
  );

  const computedFormConfig = computed(() => {
    const base = isViewMode.value ? viewFormConfig.value : cloneDeep(AREA_CHECK_PLAN_FORM_CONFIG);
    return base.map((item) => {
      if (item.prop === 'categoryCode') {
        const opts = checklistCategoryOptions.value;
        return {
          ...item,
          selectOptions: opts,
          componentProps: {
            ...(item.componentProps || {}),
            onChange: (val: string) => {
              const opt = opts.find((o) => o.value === val);
              ruleFormData.categoryName = opt?.label ?? '';
              (ruleFormData as Record<string, unknown>).categoryCode = val;
              ruleFormData.checklistTemplateName = '';
              updateChecklistTemplateOptionsByCategory(opt?.label);
            },
          },
        };
      }
      if (item.prop === 'checklistTemplateName') {
        return {
          ...item,
          selectOptions: checklistTemplateOptions.value,
          componentProps: {
            ...(item.componentProps || {}),
          },
        };
      }
      return item;
    });
  });

  const basicFormRef = ref<InstanceType<typeof BasicForm>>();

  // 查看页：详情数据
  const viewDetailData = ref<Record<string, unknown>>({});
  const viewDetail = computed(() => {
    const d = viewDetailData.value;
    const status = d?.status as number | undefined;
    return {
      ...d,
      statusName: status != null ? AREA_CHECK_PLAN_STATUS_LABEL[String(status)] ?? '-' : '-',
      planName: d?.planName ?? ruleFormData.planName ?? '-',
      venueCategoryName: d?.venueCategoryName ?? ruleFormData.venueCategoryName ?? '-',
      checkVenue: d?.checkVenue ?? ruleFormData.checkVenue ?? '-',
      primaryResponsibleDeptName: d?.primaryResponsibleDeptName ?? ruleFormData.primaryResponsibleDeptName ?? '-',
      selfCheckFrequency: d?.selfCheckFrequency ?? ruleFormData.selfCheckFrequency ?? '-',
      mainDeptExecutorGroupName: d?.mainDeptExecutorGroupName ?? '-',
      mainDeptResponsiblePerson: d?.mainDeptResponsiblePerson ?? '-',
      safetyEmergencyDeptName: d?.safetyEmergencyDeptName ?? ruleFormData.safetyEmergencyDeptName ?? '-',
      safetyEmergencyCheckFrequency: d?.safetyEmergencyCheckFrequency ?? ruleFormData.safetyEmergencyCheckFrequency ?? '-',
      safetyEmergencyExecutorGroupName: d?.safetyEmergencyExecutorGroupName ?? '-',
      safetyEmergencyResponsiblePerson: d?.safetyEmergencyResponsiblePerson ?? '-',
      hospitalLeaderDeptName: d?.hospitalLeaderDeptName ?? ruleFormData.hospitalLeaderDeptName ?? '-',
      hospitalLeaderCheckFrequency: d?.hospitalLeaderCheckFrequency ?? ruleFormData.hospitalLeaderCheckFrequency ?? '-',
      hospitalLeaderExecutorGroupName: d?.hospitalLeaderExecutorGroupName ?? '-',
      hospitalLeaderResponsiblePerson: d?.hospitalLeaderResponsiblePerson ?? '-',
      categoryName: d?.categoryName ?? ruleFormData.categoryName ?? '-',
      checklistTemplateName: d?.checklistTemplateName ?? ruleFormData.checklistTemplateName ?? '-',
      needOverallDesc: d?.needOverallDesc ?? ruleFormData.needOverallDesc,
      needSigneeSign: d?.needSigneeSign ?? ruleFormData.needSigneeSign,
      planStartTime: d?.planStartTime ?? ruleFormData.planStartTime ?? '-',
      planEndTime: d?.planEndTime ?? ruleFormData.planEndTime ?? '-',
       createdPersonName: d?. createdPersonName ?? '-',
      createdAt: d?.createdAt ?? '-',
      businessWork: d?.businessWork ?? '-',
      primaryResponsibleDeptExecGroupName: d?.primaryResponsibleDeptExecGroupName ?? '-',
      primaryResponsibleDeptPersonName: d?.primaryResponsibleDeptPersonName ?? '-',
      safetyEmergencyExecGroupName: d?.safetyEmergencyExecGroupName ?? '-',
      safetyEmergencyPersonName: d?.safetyEmergencyPersonName ?? '-',
      hospitalLeaderExecGroupName: d?.hospitalLeaderExecGroupName ?? '-',
      hospitalLeaderPersonName: d?.hospitalLeaderPersonName ?? '-',
    };
  });

  const inspectionContentList = computed(() => {
    const content = (viewDetailData.value?.checkKeyContent ?? ruleFormData.checkKeyContent) as string;
    if (!content || typeof content !== 'string') return [];
    return content.split(/[;；]/).map((s) => s.trim()).filter(Boolean);
  });

  const RECORD_TABLE_COLUMNS: TableColumnProps[] = [
    { label: '编号', type: 'index', align: 'center', width: '80px' },
    { label: '检查时间', prop: 'checkTime', minWidth: '160px' },
    { label: '检查人员', prop: 'checkPerson', minWidth: '100px' },
    { label: '检查场所类别', prop: 'checkPlaceCategory', minWidth: '120px' },
    { label: '检查场所', prop: 'checkPlace', minWidth: '120px' },
    { label: '检查项总数', prop: 'checkItemTotal', align: 'center', width: '100px' },
    { label: '合格项数', prop: 'qualifiedItemNum', align: 'center', width: '90px' },
    { label: '不合格项数', prop: 'unqualifiedItemNum', slot: 'unqualifiedItemNum', align: 'center', width: '100px' },
    { label: '整体检查情况描述', prop: 'overallCheckDesc', minWidth: '180px', showOverflowTooltip: true },
    { label: '被检查人签字', slot: 'sign', align: 'center', width: '140px' },
    { label: '操作', slot: 'action', align: 'center', width: '160px', fixed: 'right' },
  ];
  const RECORD_TABLE_OPTIONS = {
    emptyText: '暂无检查记录',
    loading: false,
    maxHeight: '400px',
    stripe: true,
  };
  const { tableConfig: recordTableConfig, pagination: recordPagination } = useTableConfig(
    RECORD_TABLE_COLUMNS,
    RECORD_TABLE_OPTIONS,
    true,
  );

  const recordSearchKeyword = ref('');
  const recordDateRange = ref<[string, string] | null>(null);
  const inspectionRecordList = ref<Array<Record<string, unknown>>>([]);

  const paginatedRecordList = computed(() => inspectionRecordList.value);

  // 检查不合格数据弹窗
  const showUnqualifiedDialog = ref(false);
  const currentRecordIdForUnqualified = ref<number | null>(null);
  const currentRowForUnqualified = ref<Record<string, unknown> | null>(null);
  const unqualifiedList = ref<UnqualifiedItemNumRecord[]>([]);
  const UNQUALIFIED_TABLE_COLUMNS: TableColumnProps[] = [
    { label: '编号', type: 'index', align: 'center', width: '60px' },
    { label: '检查场所', prop: 'checkPlace', minWidth: '200px' },
    { label: '发现问题', prop: 'checkProblem', minWidth: '220px' },
    { label: '检查时间', prop: 'checkTime', minWidth: '180px' },
    { label: '操作', slot: 'action', align: 'center', width: '100px' },
  ];
  const UNQUALIFIED_TABLE_OPTIONS = {
    emptyText: '暂无不合格数据',
    loading: false,
    maxHeight: '400px',
    stripe: true,
  };
  const { tableConfig: unqualifiedTableConfig, pagination: unqualifiedPagination } = useTableConfig(
    UNQUALIFIED_TABLE_COLUMNS,
    UNQUALIFIED_TABLE_OPTIONS,
    true,
  );

  // 入账确认弹窗数据（复用隐患台账新增表单字段与样式）
  const showSandConfirmDialog = ref(false);
  const sandConfirmLoading = ref(false);
  const sandHiddenDangerFormRef = ref<InstanceType<typeof BasicForm>>();
  const {
    ruleFormData: sandHiddenDangerFormData,
    formRules: sandHiddenDangerFormRules,
    ruleFormConfig: sandHiddenDangerFormConfig,
  } = useFormConfigHook(
    HIDDEN_DANGER_FORM_CONFIG,
    HIDDEN_DANGER_FORM_DATA as Record<string, unknown>,
    HIDDEN_DANGER_FORM_RULES,
  );

  const handleRecordSizeChange = (value: number) => {
    recordPagination.pageSize = value;
    recordPagination.pageNumber = 1;
    loadRecordList();
  };
  const handleRecordPageChange = (value: number) => {
    recordPagination.pageNumber = value;
    loadRecordList();
  };

  const loadUnqualifiedList = async () => {
    if (!currentRecordIdForUnqualified.value) return;
    unqualifiedTableConfig.loading = true;
    try {
      const res = await queryUnqualifiedItemNumPage({
        pageNumber: unqualifiedPagination.pageNumber,
        pageSize: unqualifiedPagination.pageSize,
        queryParam: {
          id: currentRecordIdForUnqualified.value,
          checkPlace: String(currentRowForUnqualified.value?.checkPlace ?? ''),
          checkProblem: String(currentRowForUnqualified.value?.checkProblem ?? ''),
          checkTime: String(currentRowForUnqualified.value?.checkTime ?? ''),
        },
      });
      const raw = (res as { data?: { records?: UnqualifiedItemNumRecord[]; totalRow?: number } })?.data ?? res;
      unqualifiedList.value = raw?.records ?? [];
      unqualifiedPagination.total = raw?.totalRow ?? 0;
    } catch (e) {
      console.error('查询不合格数据失败:', e);
      unqualifiedList.value = [];
      unqualifiedPagination.total = 0;
    } finally {
      unqualifiedTableConfig.loading = false;
    }
  };

  const handleUnqualifiedSizeChange = (value: number) => {
    unqualifiedPagination.pageSize = value;
    unqualifiedPagination.pageNumber = 1;
    loadUnqualifiedList();
  };

  const handleUnqualifiedPageChange = (value: number) => {
    unqualifiedPagination.pageNumber = value;
    loadUnqualifiedList();
  };

  const openUnqualifiedDialog = (row: { id?: number } & Record<string, unknown>) => {
    if (!row.id) return;
    currentRecordIdForUnqualified.value = Number(row.id);
    currentRowForUnqualified.value = row;
    unqualifiedPagination.pageNumber = 1;
    showUnqualifiedDialog.value = true;
    loadUnqualifiedList();
  };

  const loadRecordList = async () => {
    if (!currentId.value) return;
    recordTableConfig.loading = true;
    try {
      const [start, end] = recordDateRange.value && recordDateRange.value.length === 2
        ? recordDateRange.value
        : ['', ''];
      const res = await queryAreaCheckPlanDetailPage(currentId.value, {
        pageNumber: recordPagination.pageNumber,
        pageSize: recordPagination.pageSize,
        queryParam: {
          searchKey: recordSearchKeyword.value || undefined,
          startDate: start || undefined,
          endDate: end || undefined,
        },
      });
      const raw = (res as { data?: { records?: Array<Record<string, unknown>>; totalRow?: number } })?.data ?? res;
      const records = raw?.records ?? [];
      inspectionRecordList.value = records.map((r: Record<string, unknown>) => ({
        ...r,
        checkPerson: r.checkPerson ?? r.checkPersonName,
        checkedCompany: r.checkedCompany ?? r.checkedCompanyName,
      }));
      recordPagination.total = raw?.totalRow ?? 0;
    } catch (e) {
      console.error('查询检查记录失败:', e);
      inspectionRecordList.value = [];
      recordPagination.total = 0;
    } finally {
      recordTableConfig.loading = false;
    }
  };

  const onRecordSearch = () => {
    recordPagination.pageNumber = 1;
    loadRecordList();
  };
  const onRecordExport = async () => {
    try {
      const [start, end] = recordDateRange.value && recordDateRange.value.length === 2
        ? recordDateRange.value
        : ['', ''];
      const queryParam = {
          id: currentId.value,
          searchKey: recordSearchKeyword.value || undefined,
          startDate: start || undefined,
          endDate: end || undefined,
        };
      const response = await exportInspectionRecordTow(queryParam);
      if (response) {
        const fileName = `区域检查记录_${new Date().toISOString().split('T')[0]}.xlsx`;
        downloadByData(response, fileName);
        ElMessage.success('导出成功');
      }
    } catch (e) {
      console.error('导出区域检查记录失败:', e);
      ElMessage.error('导出失败，请重试');
    }
  };

  const handleSandToHiddenDanger = (row: { id?: number } & Record<string, unknown>) => {
    if (!row.id) return;
    currentRecordIdForUnqualified.value = Number(row.id);
    // 每次打开入账弹窗都使用一份全新的隐患台账初始数据，不带入检查记录旧数据
    Object.assign(sandHiddenDangerFormData, HIDDEN_DANGER_FORM_DATA);
    showSandConfirmDialog.value = true;
  };

  const validateSandHiddenDangerForm = async () => {
    if (!sandHiddenDangerFormRef.value) return false;
    return await sandHiddenDangerFormRef.value.validateForm();
  };

  const confirmSandToHiddenDanger = async () => {
    if (!currentRecordIdForUnqualified.value) return;
    const valid = await validateSandHiddenDangerForm();
    if (!valid) return;
    sandConfirmLoading.value = true;
    try {
      const d = sandHiddenDangerFormData;
      const payload: SandAreaCheckRecordToHiddenDangerReq = {
        areaCheckRecordId: currentRecordIdForUnqualified.value,
        sourceType: 4,
        sourceRefId: currentRecordIdForUnqualified.value,
        dangerProblem: d.dangerProblem || '',
        typeId: d.typeId,
        reasonId: d.reasonId,
        taskSource: d.taskSource || '',
        rectificationRequirement: d.rectificationRequirement || '',
        rectificationDeadline: d.rectificationDeadline || '',
        rectificationDepartmentIds: d.rectificationDepartmentIds || '',
        rectificationResponsiblePerson: d.rectificationResponsiblePerson || '',
        reviewDepartmentId: d.reviewDepartmentId,
        reviewPersonId: d.reviewPersonId,
        reviewPersonName: d.reviewPersonName || '',
        isDrawLessonsPush: d.isDrawLessonsPush ?? 0,
        drawLessonsContent: d.drawLessonsContent || '',
        drawLessonsDepartmentIds: d.drawLessonsDepartmentIds || '',
        drawLessonsDeadline: d.drawLessonsDeadline || '',
        attachments: d.attachments || '',
      };
      await sandAreaCheckRecordToProductionHiddenDanger(payload);
      ElMessage.success('下入账成功');
      // 关闭入账表单弹窗和“不合格数据”弹窗
      showSandConfirmDialog.value = false;
      showUnqualifiedDialog.value = false;
      // 重新加载检查记录列表，刷新 isSand 状态和数量
      await loadRecordList();
    } catch (e) {
      console.error('下入账失败:', e);
      ElMessage.error(e?.message || e?.data || '下入账失败，请稍后重试');
    } finally {
      sandConfirmLoading.value = false;
    }
  };

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

  const parseSignFiles = (signFile: string | undefined): Array<{ fileUrl: string; fileName: string; fileType: string }> => {
    if (!signFile || !String(signFile).trim()) return [];
    const parts = String(signFile)
      .split(',')
      .map((s) => s.trim())
      .filter(Boolean);
    return parts.map((part) => {
      const urlParts = part.split('/');
      const fileName = urlParts[urlParts.length - 1] || part || '未知文件';
      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: part, fileName, fileType };
    });
  };

  const onDeleteRecord = async (row: { id?: number }) => {
    if (!row.id) return;
    try {
      await deleteAreaCheckPlanDetail(row.id);
      ElMessage.success('删除成功');
      loadRecordList();
    } catch (e) {
      console.error('删除检查记录失败:', e);
    }
  };
  const onViewRecord = (row: Record<string, unknown>) => {
    router.push({
      name: 'areaCheckPlanManagementItem',
      query: {
        operate: 'area-check-plan-record-view',
        recordId: row.id,
        planId: currentId.value,
      },
    });
  };

  const handleValidate = async () => {
    if (!basicFormRef.value) return;
    return await basicFormRef.value.validateForm();
  };

  const getDetail = async () => {
    if (!currentId.value) return;
    try {
      const res = await queryAreaCheckPlanManageDetail(currentId.value);
      const raw = (res as { data?: unknown })?.data ?? res;
      const detail = mapAreaCheckPlanApiRecordToUi(raw);
      viewDetailData.value = { ...detail };
      ruleFormData.planName = detail.planName ?? '';
      ruleFormData.venueCategoryName = detail.venueCategoryName ?? '';
      ruleFormData.checkVenue = detail.checkVenue ?? '';
      ruleFormData.primaryResponsibleDeptName = detail.primaryResponsibleDeptName ?? '';
      ruleFormData.primaryResponsibleDeptCode = detail.primaryResponsibleDeptCode ?? '';
      ruleFormData.primaryResponsibleDeptId = findDeptIdByName(deptTree.value, ruleFormData.primaryResponsibleDeptName as string) ?? null;
      ruleFormData.selfCheckFrequency = detail.selfCheckFrequency ?? '';
      ruleFormData.safetyEmergencyDeptName = detail.safetyEmergencyDeptName ?? '';
      ruleFormData.safetyEmergencyDeptId = findDeptIdByName(deptTree.value, ruleFormData.safetyEmergencyDeptName as string) ?? null;
      ruleFormData.safetyEmergencyCheckFrequency = detail.safetyEmergencyCheckFrequency ?? '';
      ruleFormData.hospitalLeaderDeptName = detail.hospitalLeaderDeptName ?? '';
      ruleFormData.hospitalLeaderDeptId = findDeptIdByName(deptTree.value, ruleFormData.hospitalLeaderDeptName as string) ?? null;
      ruleFormData.hospitalLeaderCheckFrequency = detail.hospitalLeaderCheckFrequency ?? '';
      (ruleFormData as Record<string, unknown>).categoryCode = detail.categoryCode ?? '';
      ruleFormData.categoryName = detail.categoryName ?? '';
      ruleFormData.checklistTemplateName = detail.checklistTemplateName ?? '';
      ruleFormData.checkKeyContent = detail.checkKeyContent ?? '';
      ruleFormData.primaryResponsibleDeptExecGroupName = detail.primaryResponsibleDeptExecGroupName ?? '';
      ruleFormData.primaryResponsibleDeptPersonName = detail.primaryResponsibleDeptPersonName ?? '';
      ruleFormData.safetyEmergencyExecGroupName = detail.safetyEmergencyExecGroupName ?? '';
      ruleFormData.safetyEmergencyPersonName = detail.safetyEmergencyPersonName ?? '';
      ruleFormData.hospitalLeaderExecGroupName = detail.hospitalLeaderExecGroupName ?? '';
      ruleFormData.hospitalLeaderPersonName = detail.hospitalLeaderPersonName ?? '';
      updateChecklistTemplateOptionsByCategory(ruleFormData.categoryName as string | undefined);
      cloneRuleFormData();
      if (isViewMode.value) {
        loadRecordList();
      }
    } catch (e) {
      console.error('获取详情失败:', e);
    }
  };

  const handleSubmit = async () => {
    const valid = await handleValidate();
    if (!valid) return;
    try {
      if (isCreateMode.value) {
        await saveAreaCheckPlanManage(ruleFormData as AreaCheckPlanRecord);
        ElMessage.success('创建成功');
      } else if (isEditMode.value) {
        await updateAreaCheckPlanManage({ ...ruleFormData, id: currentId.value } as AreaCheckPlanRecord & { id: number });
        ElMessage.success('保存成功');
      }
      router.back();
    } catch (e) {
      console.error('提交失败:', e);
    }
  };

  onMounted(async () => {
    cloneRuleFormData();
    venueCategoryOptions.value = [
      { label: '各级风险点', value: '各级风险点' },
      { label: '关键业务活动', value: '关键业务活动' },
      { label: '日常安全', value: '日常安全' },
      { label: '各级危险点', value: '各级危险点' },
      { label: '试验室及试验过程', value: '试验室及试验过程' },
      { label: '办公区域（含地下车库、图书馆、档案库房、仓库等）', value: '办公区域（含地下车库、图书馆、档案库房、仓库等）' },
      { label: '老旧厂房', value: '老旧厂房' },
      { label: '施工现场', value: '施工现场' },
      { label: '职工食堂', value: '职工食堂' },
      { label: '职工宿舍', value: '职工宿舍' },
      { label: '体育活动场所', value: '体育活动场所' },
      { label: '托育园', value: '托育园' },
      { label: '租、出借房屋', value: '租、出借房屋' },
      { label: '院内经营服务场所', value: '院内经营服务场所' },
      { label: '垃圾房', value: '垃圾房' },
      { label: '院内交通', value: '院内交通' },
      { label: '消防设施设备', value: '消防设施设备' },
      { label: '特种设备', value: '特种设备' },
      { label: '防雷设施', value: '防雷设施' },
      { label: '供、配电设施设备（含弱电）', value: '供、配电设施设备（含弱电）' },
      { label: '公务车辆', value: '公务车辆' },
      { label: '燃气管道设施（含报警装置）', value: '燃气管道设施（含报警装置）' },
      { label: '建筑物外墙标识物、装饰物', value: '建筑物外墙标识物、装饰物' },
      { label: 'UPS电源', value: 'UPS电源' },
      { label: '危险化学品', value: '危险化学品' },
      { label: '设施设备应急操作流程', value: '设施设备应急操作流程' },
      { label: '堆场、物资库房', value: '堆场、物资库房' },
      { label: '室内外停车场', value: '室内外停车场' }
    ];
    await getDeptTreeData();
    await loadChecklistCategoryOptions();
    await loadChecklistTemplateOptions();
    if (isEditMode.value || isViewMode.value) {
      getDetail();
    }
  });
</script>

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

  .area-check-plan-view {
    padding: 16px 24px;
    display: flex;
    flex-direction: column;
    gap: 24px;
  }

  .view-section {
    .view-section__title {
      font-weight: 600;
      margin-bottom: 12px;
      display: flex;
      align-items: center;
      gap: 6px;
      &--small {
        font-size: 13px;
        margin-bottom: 8px;
      }
    }
    .view-section__icon {
      width: 4px;
      height: 14px;
      background: var(--el-color-primary);
      border-radius: 2px;
    }
  }

  .view-summary {
    .view-summary__title {
      font-weight: 600;
      font-size: 15px;
      margin-bottom: 4px;
    }
    .view-summary__venue {
      margin-bottom: 8px;
    }
  .view-summary__meta {
    font-size: 13px;
    color: var(--el-text-color-secondary);
    span + span {
      margin-left: 16px;
    }
  }
}

/* 基本信息：与 OneByOneAuditDetail 保持一致 */
.audit-content {
  .section-title {
    display: flex;
    align-items: center;
    gap: 8px;
    margin: 20px 0 12px 0;
    font-size: 16px;
    font-weight: 600;
    color: #333;

    .section-title__icon {
      font-size: 18px;
      color: #333;
    }
  }

  .section-title:first-child {
    margin-top: 0;
  }

  .detail-ct {
    font-size: 14px;
    margin-bottom: 20px;

    &--table {
      border: 1px solid #dcdfe6;
      .row {
        display: flex;
        border-bottom: 1px solid #dcdfe6;

        &:last-child {
          border-bottom: none;
        }
      }
      .col {
        display: flex;
        flex: 1;
        min-height: 40px;
        align-items: stretch;

        .label {
          display: flex;
          align-items: center;
          justify-content: flex-end;
          flex-shrink: 0;
          width: 260px;
          padding: 0 12px;
          background-color: #f5f5f5;
          border-right: 1px solid #dcdfe6;
          color: #333;
        }

        .value {
          flex: 1;
          display: flex;
          align-items: center;
          padding: 10px 20px;
          background-color: #fff;
          border-right: 1px solid #dcdfe6;
          color: #333;

          &--list {
            align-items: flex-start;
            .inspection-content-list {
              margin: 0;
              padding-left: 20px;
              line-height: 1.8;
              color: #333;
            }
          }
        }
      }

      .row .col:last-child .value {
        border-right: none;
      }

      .row .col:nth-child(2) .label {
        border-left: 1px solid #dcdfe6;
      }
    }
  }
}

  .view-record-toolbar {
    margin-bottom: 12px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 8px;
  }

  .view-record-table {
    margin-bottom: 16px;
  }

  .view-record-toolbar-btn{
    margin-left: auto;
  }

</style>
