<template>
  <!-- 区域检查计划管理(部门)查看：与管理员查看样式一致 -->
  <main 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.safetyEmergencyExecutorGroupName || '-' }}</div>
          </div>
          <div class="col">
            <div class="label">安全应急部责任人：</div>
            <div class="value">{{ viewDetail.safetyEmergencyResponsiblePerson || '-' }}</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.hospitalLeaderExecutorGroupName || '-' }}</div>
          </div>
          <div class="col">
            <div class="label">院领导责任人：</div>
            <div class="value">{{ viewDetail.hospitalLeaderResponsiblePerson || '-' }}</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>
        <el-button type="primary" @click="onAddRecord">新增检查日志</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="primary" link size="small" @click="onViewRecord(scope.row)">检查记录查看</el-button>
        </template>
      </BasicTable>
    </section>
  </main>
  <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="handleSandToHiddenDangerDept(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="showSandConfirmDialogDept"
    title="检查记录入账隐患台账"
    width="900px"
    destroy-on-close
  >
    <BasicForm
      ref="sandHiddenDangerFormRefDept"
      :formData="sandHiddenDangerFormDataDept"
      :formRules="sandHiddenDangerFormRulesDept"
      :formConfig="sandHiddenDangerFormConfigDept"
    >
      <template #rectificationDepartmentIds>
        <el-form-item prop="rectificationDepartmentIds" style="width: 100%;">
          <el-cascader
            v-model="sandHiddenDangerFormDataDept.rectificationDepartmentIds"
            :options="issueDeptTree"
            :props="cascaderDeptProp"
            :show-all-levels="false"
            placeholder="请选择整改责任部门"
            filterable
            clearable
            @change="onIssueDeptChange"
          />
        </el-form-item>
      </template>
      <template #rectificationResponsibleIds>
        <el-form-item prop="rectificationResponsibleIds" style="width: 100%;">
          <el-select
            v-model="sandHiddenDangerFormDataDept.rectificationResponsibleIds"
            placeholder="选择整改负责人"
            filterable
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="user in issueUserList"
              :key="user.id"
              :label="user.realname ?? user.username"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
      </template>
      <template #reviewDepartmentId>
        <el-cascader
          v-model="sandHiddenDangerFormDataDept.reviewDepartmentId"
          :options="deptTree"
          :props="cascaderDeptProp"
          :show-all-levels="false"
          placeholder="请选择复查人员所属部门"
          filterable
          clearable
          style="width: 100%"
        />
      </template>
      <template #reviewPerson>
        <el-select
          v-model="sandHiddenDangerFormDataDept.reviewPersonId"
          placeholder="请选择复查人员"
          clearable
          filterable
          style="width: 100%"
        >
          <el-option
            v-for="u in reviewUserListDept"
            :key="u.id"
            :label="u.realname || u.username"
            :value="u.id"
          />
        </el-select>
      </template>
      <template #isDrawLessonsPush>
        <el-radio-group v-model="sandHiddenDangerFormDataDept.isDrawLessonsPush" @change="isDrawLessonsPushChange">
          <el-radio :value="0">否</el-radio>
          <el-radio :value="1">是</el-radio>
        </el-radio-group>
      </template>
      <template #drawLessonsDepartmentIds> 
        <el-select
          v-model="drawLessonsDeptIdsArrayDept"
          placeholder="请选择举一反三责任部门，可多选"
          clearable
          filterable
          multiple
          collapse-tags
          collapse-tags-tooltip
          style="width: 100%"
          @change="() => { sandHiddenDangerFormDataDept.drawLessonsDepartmentIds = drawLessonsDeptIdsArrayDept.join(','); }"
        >
          <el-option
            v-for="d in deptOptions"
            :key="d.id"
            :label="d.deptName"
            :value="d.id"
          />
        </el-select>
      </template>
      <template #drawLessonsDeadline>
        <el-form-item prop="drawLessonsDeadline" style="width: 100%;">
          <el-date-picker
            v-model="sandHiddenDangerFormDataDept.drawLessonsDeadline"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择举一反三截止日期（选填）"
          />
        </el-form-item>
      </template>
    </BasicForm>
    <template #footer>
      <el-button @click="showSandConfirmDialogDept = false">取消</el-button>
      <el-button type="primary" :loading="sandConfirmLoadingDept" @click="confirmSandToHiddenDangerDept">
        提交
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { computed, onMounted, ref } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import { Document } from '@element-plus/icons-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 useTableConfig from '@/hooks/useTableConfigHook';
  import type { TableColumnProps } from '@/types/basic-table';
  import { AREA_CHECK_PLAN_STATUS_LABEL } from '../../areaCheckPlanManagement/configs/status';
  import {
    queryAreaCheckPlanManageDeptDetail,
    queryAreaCheckPlanDetailDeptPage,
    mapAreaCheckPlanApiRecordToUi,
    queryUnqualifiedItemNumDeptPage,
    sandAreaCheckRecordToProductionHiddenDanger,
    exportAreaCheckInspectionRecord,
    type UnqualifiedItemNumRecord,
    type SandAreaCheckRecordToHiddenDangerReq,
  } from '@/api/production-safety-system';
  import BasicForm from '@/components/BasicForm.vue';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import { getAllDepartments } from '@/api/auth/dept';
  import type { DeptTree } from '@/types/dept/type';
  import {
    HIDDEN_DANGER_FORM_CONFIG,
    HIDDEN_DANGER_FORM_DATA,
    HIDDEN_DANGER_FORM_RULES,
  } from '@/views/production-safety/hiddenTroubleInvestigationAndGovernance/hiddenTroubleAccountManagement/configs/form';
  import { queryAvailableUserList } from '@/api/production-safety/responsibility-implementation';
  import { downloadByData } from '@/utils/file/download';

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

  const currentId = computed(() => Number(route.query.id));

  const viewDetailData = ref<Record<string, unknown>>({});
  const viewDetail = computed(() => {
    const d = viewDetailData.value;
    const status = d?.status as number | undefined;
    console.log(d,'d')
    return {
      ...d,
      statusName: status != null ? AREA_CHECK_PLAN_STATUS_LABEL[String(status)] ?? '-' : '-',
      planName: d?.planName ?? '-',
      venueCategoryName: d?.venueCategoryName ?? '-',
      checkVenue: d?.checkVenue ?? '-',
      mainDeptName: d?.mainDeptName ?? '-',
      primaryResponsibleDeptName: (d?.primaryResponsibleDeptName ?? d?.mainDeptName) ?? '-',
      selfCheckFrequency: d?.selfCheckFrequency ?? '-',
      mainDeptExecutorGroupName: d?.mainDeptExecutorGroupName ?? '-',
      mainDeptResponsiblePerson: d?.mainDeptResponsiblePerson ?? '-',
      safetyEmergencyDeptName: d?.safetyEmergencyDeptName ?? '-',
      safetyEmergencyCheckFrequency: d?.safetyEmergencyCheckFrequency ?? '-',
      safetyEmergencyExecutorGroupName: d?.safetyEmergencyExecutorGroupName ?? '-',
      safetyEmergencyResponsiblePerson: d?.safetyEmergencyResponsiblePerson ?? '-',
      hospitalLeaderDeptName: d?.hospitalLeaderDeptName ?? '-',
      hospitalLeaderCheckFrequency: d?.hospitalLeaderCheckFrequency ?? '-',
      hospitalLeaderExecutorGroupName: d?.hospitalLeaderExecutorGroupName ?? '-',
      hospitalLeaderResponsiblePerson: d?.hospitalLeaderResponsiblePerson ?? '-',
      checklistCategoryName: d?.checklistCategoryName ?? '-',
      categoryName: (d?.categoryName ?? d?.checklistCategoryName) ?? '-',
      checklistTemplateName: d?.checklistTemplateName ?? '-',
      needOverallDesc: d?.needOverallDesc,
      needSigneeSign: d?.needSigneeSign,
      planStartTime: d?.planStartTime ?? '-',
      planEndTime: d?.planEndTime ?? '-',
      createdPersonName: (d?.createdPersonName ?? '') || '-',
      createdAt: (d?.createdAt ?? '') || '-',
      businessWork: (d?.businessWork ?? '') || '-',
      primaryResponsibleDeptExecGroupName: d?.primaryResponsibleDeptExecGroupName ?? '-',
      primaryResponsibleDeptPersonName: d?.primaryResponsibleDeptPersonName ?? '-',
    };
  });

  const issueDeptTree = ref<DeptTree[]>([]);
  const issueUserList = ref<Array<{ id: number; realname?: string; username?: string }>>([]);

  const onIssueDialogOpen = async () => {
    try {
      const [deptRes, userRes] = await Promise.all([
        getAllDepartments(),
        queryAvailableUserList({ pageNumber: 1, pageSize: 9999, queryParam: {} }),
      ]);
      const fullTree = (deptRes as DeptTree[]) ?? [];
      issueDeptTree.value = Array.isArray(fullTree) && fullTree[0]?.children ? fullTree[0].children : [];
      issueUserList.value = (userRes as any)?.records ?? [];
    } catch (e) {
      console.error('获取部门/用户列表失败:', e);
      ElMessage.error(e?.message || e?.data || '加载部门或负责人列表失败');
      issueDeptTree.value = [];
      issueUserList.value = [];
    }
  };

  const inspectionContentList = computed(() => {
    const content = (viewDetailData.value?.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: '80px' },
    { 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 showSandConfirmDialogDept = ref(false);
  const sandConfirmLoadingDept = ref(false);
  const sandHiddenDangerFormRefDept = ref<InstanceType<typeof BasicForm>>();
  const {
    ruleFormData: sandHiddenDangerFormDataDept,
    formRules: sandHiddenDangerFormRulesDept,
    ruleFormConfig: sandHiddenDangerFormConfigDept,
  } = useFormConfigHook(
    HIDDEN_DANGER_FORM_CONFIG,
    HIDDEN_DANGER_FORM_DATA as Record<string, unknown>,
    HIDDEN_DANGER_FORM_RULES,
  );

  // 复用部门树与用户下拉，用于复查部门/人员 & 举一反三责任部门
  const deptTree = ref<DeptTree[]>([]);
  const cascaderDeptProp = {
    checkStrictly: true,
    expandTrigger: 'hover' as const,
    value: 'id',
    label: 'deptName',
    emitPath: false,
  };
  function flattenDeptTree(nodes: DeptTree[] | undefined): Array<{ id: number; deptName: string }> {
    if (!nodes?.length) return [];
    const list: Array<{ id: number; deptName: string }> = [];
    const walk = (items: DeptTree[]) => {
      items.forEach((n) => {
        if (n.id != null) list.push({ id: n.id, deptName: n.deptName });
        if (n.children?.length) walk(n.children);
      });
    };
    walk(nodes);
    return list;
  }
  const deptOptions = computed(() => flattenDeptTree(deptTree.value));
  const drawLessonsDeptIdsArrayDept = ref<number[]>([]);
  const reviewUserListDept = ref<Array<{ id: number; realname?: string; username?: string }>>([]);

  const loadDeptAndUserOptionsDept = async () => {
    try {
      const [deptRes, userRes] = await Promise.all([
        getAllDepartments(),
        queryAvailableUserList({ pageNumber: 1, pageSize: 9999, queryParam: {} }),
      ]);
      const fullTree = (deptRes as DeptTree[]) ?? [];
      deptTree.value = Array.isArray(fullTree) && fullTree[0]?.children ? fullTree[0].children : [];
      reviewUserListDept.value = (userRes as any)?.records ?? [];
    } catch (e) {
      console.error('获取部门/用户列表失败:', e);
      deptTree.value = [];
      reviewUserListDept.value = [];
    }
  };

  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 queryAreaCheckPlanDetailDeptPage(currentId.value, {
        pageNumber: recordPagination.pageNumber,
        pageSize: recordPagination.pageSize,
        queryParam: {
          searchKey: recordSearchKeyword.value || undefined,
          startDate: start || undefined,
          endDate: end || undefined,
          id: currentId.value,
        },
      });
      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 handleRecordSizeChange = (value: number) => {
    recordPagination.pageSize = value;
    recordPagination.pageNumber = 1;
    loadRecordList();
  };
  const handleRecordPageChange = (value: number) => {
    recordPagination.pageNumber = value;
    loadRecordList();
  };

  const onRecordSearch = () => {
    recordPagination.pageNumber = 1;
    loadRecordList();
  };
  const onRecordExport = async () => {
    try {
      const [start, end] = recordDateRange.value && recordDateRange.value.length === 2
        ? recordDateRange.value
        : ['', ''];
      const queryParam = {
          searchKey: recordSearchKeyword.value || undefined,
          startDate: start || undefined,
          endDate: end || undefined,
      };
      const response = await exportAreaCheckInspectionRecord(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 loadUnqualifiedList = async () => {
    if (!currentRecordIdForUnqualified.value) return;
    unqualifiedTableConfig.loading = true;
    try {
      const res = await queryUnqualifiedItemNumDeptPage({
        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 handleSandToHiddenDangerDept = (row: { id?: number } & Record<string, unknown>) => {
    if (!row.id) return;
    currentRecordIdForUnqualified.value = Number(row.id);
    // 部门端入账同样不带入检查记录旧数据，每次打开还原为隐患台账初始表单
    Object.assign(sandHiddenDangerFormDataDept, HIDDEN_DANGER_FORM_DATA);
    showSandConfirmDialogDept.value = true;
  };

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

  const confirmSandToHiddenDangerDept = async () => {
    if (!currentRecordIdForUnqualified.value) return;
    const valid = await validateSandHiddenDangerFormDept();
    if (!valid) return;
    sandConfirmLoadingDept.value = true;
    try {
      const d = sandHiddenDangerFormDataDept;
      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 || '',
        confirmSandToHiddenDangerDept: d.confirmSandToHiddenDangerDept ?? 0,
        rectificationResponsibleIds: d.rectificationResponsibleIds || '',
        drawLessonsContent: d.drawLessonsContent || '',
        drawLessonsDepartmentIds: d.drawLessonsDepartmentIds || '',
        drawLessonsDeadline: d.drawLessonsDeadline || '',
      };
      await sandAreaCheckRecordToProductionHiddenDanger(payload);
      ElMessage.success('入账成功');
      // 关闭入账表单弹窗和“不合格数据”弹窗
      showSandConfirmDialogDept.value = false;
      showUnqualifiedDialog.value = false;
      await loadRecordList();
    } catch (e) {
      console.error('部门端下入账失败:', e);
      ElMessage.error(e?.message || e?.data || '下入账失败，请稍后重试');
    } finally {
      sandConfirmLoadingDept.value = false;
    }
  };

  const onAddRecord = () => {
    const needOverallDesc = !viewDetail.value.needOverallDesc ? 0 : 1;
    const needSigneeSign = !viewDetail.value.needSigneeSign ? 0 : 1;
    router.push({
      name: 'areaCheckPlanManagementDeptItem',
      query: {
        operate: 'area-check-plan-record-add',
        planId: currentId.value,  
        needOverallDesc,
        needSigneeSign,
      },
    });
  };

  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 onViewRecord = (row: Record<string, unknown>) => {
    const needOverallDesc = !viewDetail.value.needOverallDesc ? 0 : 1;
    const needSigneeSign = !viewDetail.value.needSigneeSign ? 0 : 1;
    router.push({
      name: 'areaCheckPlanManagementDeptItem',
      query: {
        operate: 'area-check-plan-record-view',
        recordId: row.id,
        planId: currentId.value,
        needOverallDesc,
        needSigneeSign,
      },
    });
  };

  const getDetail = async () => {
    if (!currentId.value) return;
    try {
      const res = await queryAreaCheckPlanManageDeptDetail(currentId.value);
      const raw = (res as { data?: unknown })?.data ?? res;
      const detail = mapAreaCheckPlanApiRecordToUi(raw);
      viewDetailData.value = { ...detail };
      loadRecordList();
    } catch (e) {
      console.error('获取详情失败:', e);
    }
  };

  const isDrawLessonsPushChange = () => {
    console.log(sandHiddenDangerFormDataDept.isDrawLessonsPush)
    console.log('HIDDEN_DANGER_FORM_CONFIG', HIDDEN_DANGER_FORM_CONFIG)
    let data = [
        {
          prop: 'drawLessonsContent',
          label: '举一反三内容：',
          component: 'ElInput',
          componentProps: {
            placeholder: '如：上级检查、院内自查',
          },
        },
        {
          prop: 'drawLessonsDepartmentIds',
          label: '举一反三责任部门：',
          slot: 'drawLessonsDepartmentIds',
        },
        {
          prop: 'drawLessonsDeadline',
          label: '举一反三时限：',
          slot: 'drawLessonsDeadline',
        },
    ]
  };

  const onIssueDeptChange = () => {
    sandHiddenDangerFormDataDept.rectificationResponsibleIds = undefined;
  };

  onMounted(() => {
    loadDeptAndUserOptionsDept();
    getDetail();
    onIssueDialogOpen();
  });
  
</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;
      }
    }
  }

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