<!-- 编辑弹窗 -->
<template>
  <a-drawer
    width="98%"
    :visible="visible"
    :maskClosable="false"
    :maxable="maxable"
    :title="data?.name"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
  >
    <a-descriptions
      :column="descriptionColumns"
      size="small"
      bordered
      class="credit-company-descriptions"
    >
      <a-descriptions-item label="企业名称">
        {{ formatValue(form.matchName) }}
      </a-descriptions-item>
      <a-descriptions-item label="法定代表人">
        {{ formatValue(form.legalPerson) }}
      </a-descriptions-item>
      <a-descriptions-item label="统一社会信用代码">
        {{ formatValue(form.code) }}
      </a-descriptions-item>
      <a-descriptions-item label="企业地址">
        {{ formatValue(form.address) }}
      </a-descriptions-item>
      <a-descriptions-item label="电话">
        {{ formatValue(form.tel) }}
      </a-descriptions-item>
      <a-descriptions-item label="更多电话">
        {{ formatValue(form.moreTel) }}
      </a-descriptions-item>
    </a-descriptions>
    <a-divider style="margin: 16px 0" />
    <a-tabs
      v-model:activeKey="activeTab"
      :tabBarGutter="9"
      class="credit-company-tabs"
    >
      <a-tab-pane v-for="tab in tabList" :key="tab.key">
        <template #tab>
          <span
            :class="{
              'credit-company-tab-has-data': tabHasData[tab.key]
            }"
          >
            {{ tab.label }}
          </span>
        </template>
        <a-space style="margin-bottom: 12px">
          <a-button
            type="primary"
            :disabled="!form.id"
            @click="openRelatedImport(tab.key)"
          >
            导入(多)
          </a-button>
          <a-button
            v-if="tab.key === '被执行人'"
            type="dashed"
            :disabled="!form.id"
            @click="openJudgmentDebtorHistoryImport"
          >
            <template #icon>
              <CloudUploadOutlined />
            </template>
            导入历史被执行人
          </a-button>
          <a-button
            v-if="tab.key === '限制高消费'"
            type="dashed"
            :disabled="!form.id"
            @click="openXgxfHistoryImport"
          >
            <template #icon>
              <CloudUploadOutlined />
            </template>
            导入历史限制高消费
          </a-button>
          <a-button
            v-if="tab.key === '终本案件'"
            type="dashed"
            :disabled="!form.id"
            @click="openFinalVersionHistoryImport"
          >
            <template #icon>
              <CloudUploadOutlined />
            </template>
            导入历史终本案件
          </a-button>
          <a-button
            v-if="tab.key === '开庭公告'"
            type="dashed"
            :disabled="!form.id"
            @click="openCourtSessionHistoryImport"
          >
            <template #icon>
              <CloudUploadOutlined />
            </template>
            导入历史开庭公告
          </a-button>
          <a-button
            v-if="tab.key === '法院公告'"
            type="dashed"
            :disabled="!form.id"
            @click="openCourtAnnouncementHistoryImport"
          >
            <template #icon>
              <CloudUploadOutlined />
            </template>
            导入历史法院公告
          </a-button>
          <a-button
            v-if="tab.key === '失信被执行人'"
            type="dashed"
            :disabled="!form.id"
            @click="openBreachOfTrustHistoryImport"
          >
            <template #icon>
              <CloudUploadOutlined />
            </template>
            导入历史失信被执行人
          </a-button>
          <a-button
            v-if="tab.key === '裁判文书'"
            type="dashed"
            :disabled="!form.id"
            @click="openJudicialDocumentHistoryImport"
          >
            <template #icon>
              <CloudUploadOutlined />
            </template>
            导入历史裁判文书
          </a-button>
          <a-button
            v-if="tab.key === '股权冻结'"
            type="dashed"
            :disabled="!form.id"
            @click="openGqdjHistoryImport"
          >
            <template #icon>
              <CloudUploadOutlined />
            </template>
            导入历史股权冻结
          </a-button>
          <a-button
            v-if="tab.key === '破产重整'"
            type="dashed"
            :disabled="!form.id"
            @click="openBankruptcyHistoryImport"
          >
            <template #icon>
              <CloudUploadOutlined />
            </template>
            导入历史破产重整
          </a-button>
          <a-button
            v-if="tab.key === '行政许可'"
            type="dashed"
            :disabled="!form.id"
            @click="openAdministrativeLicenseHistoryImport"
          >
            <template #icon>
              <CloudUploadOutlined />
            </template>
            导入历史行政许可
          </a-button>
          <a-button
            :loading="tabState[tab.key].loading"
            @click="reloadTab(tab.key)"
          >
            刷新
          </a-button>
        </a-space>
        <a-table
          v-if="tabState[tab.key].columns.length"
          size="small"
          :columns="tabState[tab.key].columns"
          :data-source="tabState[tab.key].data"
          :loading="tabState[tab.key].loading"
          :row-key="getRowKey"
          :scroll="{ x: 'max-content' }"
          :pagination="getTabPagination(tab.key)"
        />
        <a-empty
          v-else-if="!tabState[tab.key].loading"
          description="暂无数据"
        />
      </a-tab-pane>
    </a-tabs>

    <!-- 企业详情子表导入 -->
    <CreditCompanyRelatedImport
      v-model:visible="showRelatedImport"
      :title="relatedImportTitle"
      :templatePath="relatedImportTemplatePath"
      :companyId="form.id"
      :importFn="relatedImportFn"
      @done="handleRelatedImportDone"
    />

    <!-- 历史行政许可导入（企业详情-行政许可tab） -->
    <CreditAdministrativeLicenseHistoryImport
      v-model:visible="showAdministrativeLicenseHistoryImport"
      :companyId="form.id"
      @done="handleAdministrativeLicenseHistoryImportDone"
    />

    <!-- 历史破产重整导入（企业详情-破产重整tab） -->
    <CreditBankruptcyHistoryImport
      v-model:visible="showBankruptcyHistoryImport"
      :companyId="form.id"
      @done="handleBankruptcyHistoryImportDone"
    />

    <!-- 历史被执行人导入（企业详情-被执行人tab） -->
    <CreditJudgmentDebtorHistoryImport
      v-model:visible="showJudgmentDebtorHistoryImport"
      :companyId="form.id"
      @done="handleJudgmentDebtorHistoryImportDone"
    />

    <!-- 历史限制高消费导入（企业详情-限制高消费tab） -->
    <CreditXgxfHistoryImport
      v-model:visible="showXgxfHistoryImport"
      :companyId="form.id"
      @done="handleXgxfHistoryImportDone"
    />

    <!-- 历史终本案件导入（企业详情-终本案件tab） -->
    <CreditFinalVersionHistoryImport
      v-model:visible="showFinalVersionHistoryImport"
      :companyId="form.id"
      @done="handleFinalVersionHistoryImportDone"
    />

    <!-- 历史开庭公告导入（企业详情-开庭公告tab） -->
    <CreditCourtSessionHistoryImport
      v-model:visible="showCourtSessionHistoryImport"
      :companyId="form.id"
      @done="handleCourtSessionHistoryImportDone"
    />

    <!-- 历史法院公告导入（企业详情-法院公告tab） -->
    <CreditCourtAnnouncementHistoryImport
      v-model:visible="showCourtAnnouncementHistoryImport"
      :companyId="form.id"
      @done="handleCourtAnnouncementHistoryImportDone"
    />

    <!-- 历史失信被执行人导入（企业详情-失信被执行人tab） -->
    <CreditBreachOfTrustHistoryImport
      v-model:visible="showBreachOfTrustHistoryImport"
      :companyId="form.id"
      @done="handleBreachOfTrustHistoryImportDone"
    />

    <!-- 历史裁判文书导入（企业详情-裁判文书tab） -->
    <CreditJudicialDocumentHistoryImport
      v-model:visible="showJudicialDocumentHistoryImport"
      :companyId="form.id"
      @done="handleJudicialDocumentHistoryImportDone"
    />

    <!-- 历史股权冻结导入（企业详情-股权冻结tab） -->
    <CreditGqdjHistoryImport
      v-model:visible="showGqdjHistoryImport"
      :companyId="form.id"
      @done="handleGqdjHistoryImportDone"
    />
  </a-drawer>
</template>

<script lang="ts" setup>
  import { computed, h, reactive, ref, watch } from 'vue';
  import { message } from 'ant-design-vue';
  import { CloudUploadOutlined } from '@ant-design/icons-vue';
  import { assignObject } from 'ele-admin-pro';
  import { CreditCompany } from '@/api/credit/creditCompany/model';
  import { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';
  import CreditCompanyRelatedImport from './credit-company-related-import.vue';
  import CreditAdministrativeLicenseHistoryImport from '@/views/credit/creditAdministrativeLicense/components/credit-administrative-license-history-import.vue';
  import CreditBankruptcyHistoryImport from '@/views/credit/creditBankruptcy/components/credit-bankruptcy-history-import.vue';
  import CreditJudgmentDebtorHistoryImport from '@/views/credit/creditJudgmentDebtor/components/credit-judgment-debtor-history-import.vue';
  import CreditXgxfHistoryImport from '@/views/credit/creditXgxf/components/credit-xgxf-history-import.vue';
  import CreditFinalVersionHistoryImport from '@/views/credit/creditFinalVersion/components/credit-final-version-history-import.vue';
  import CreditCourtSessionHistoryImport from '@/views/credit/creditCourtSession/components/credit-court-session-history-import.vue';
  import CreditCourtAnnouncementHistoryImport from '@/views/credit/creditCourtAnnouncement/components/credit-court-announcement-history-import.vue';
  import CreditBreachOfTrustHistoryImport from '@/views/credit/creditBreachOfTrust/components/credit-breach-of-trust-history-import.vue';
  import CreditJudicialDocumentHistoryImport from '@/views/credit/creditJudicialDocument/components/credit-judicial-document-history-import.vue';
  import CreditGqdjHistoryImport from '@/views/credit/creditGqdj/components/credit-gqdj-history-import.vue';
  import {
    pageCreditAdministrativeLicense,
    importCreditAdministrativeLicense
  } from '@/api/credit/creditAdministrativeLicense';
  import {
    pageCreditBankruptcy,
    importCreditBankruptcy
  } from '@/api/credit/creditBankruptcy';
  import {
    pageCreditBranch,
    importCreditBranch
  } from '@/api/credit/creditBranch';
  import {
    pageCreditHistoricalLegalPerson,
    importCreditHistoricalLegalPerson
  } from '@/api/credit/creditHistoricalLegalPerson';
  import {
    pageCreditNearbyCompany,
    importCreditNearbyCompany
  } from '@/api/credit/creditNearbyCompany';
  import {
    pageCreditPatent,
    importCreditPatent
  } from '@/api/credit/creditPatent';
  import {
    pageCreditSuspectedRelationship,
    importCreditSuspectedRelationship
  } from '@/api/credit/creditSuspectedRelationship';
  import { pageCreditUser, importCreditUsers } from '@/api/credit/creditUser';
  import {
    pageCreditExternal,
    importCreditExternal
  } from '@/api/credit/creditExternal';
  import {
    pageCreditRiskRelation,
    importCreditRiskRelation
  } from '@/api/credit/creditRiskRelation';
  import {
    pageCreditCompetitor,
    importCreditCompetitor
  } from '@/api/credit/creditCompetitor';
  import {
    pageCreditSupplier,
    importCreditSupplier
  } from '@/api/credit/creditSupplier';
  import {
    pageCreditCustomer,
    importCreditCustomer
  } from '@/api/credit/creditCustomer';
  import {
    pageCreditCaseFiling,
    importCreditCaseFiling
  } from '@/api/credit/creditCaseFiling';
  import {
    pageCreditMediation,
    importCreditMediation
  } from '@/api/credit/creditMediation';
  import {
    pageCreditCourtSession,
    importCreditCourtSession
  } from '@/api/credit/creditCourtSession';
  import {
    pageCreditCourtAnnouncement,
    importCreditCourtAnnouncement
  } from '@/api/credit/creditCourtAnnouncement';
  import {
    pageCreditDeliveryNotice,
    importCreditDeliveryNotice
  } from '@/api/credit/creditDeliveryNotice';
  import {
    pageCreditJudicialDocument,
    importCreditJudicialDocument
  } from '@/api/credit/creditJudicialDocument';
  import {
    pageCreditJudgmentDebtor,
    importCreditJudgmentDebtor
  } from '@/api/credit/creditJudgmentDebtor';
  import {
    pageCreditBreachOfTrust,
    importCreditBreachOfTrust
  } from '@/api/credit/creditBreachOfTrust';
  import {
    pageCreditFinalVersion,
    importCreditFinalVersion
  } from '@/api/credit/creditFinalVersion';
  import { pageCreditXgxf, importCreditXgxf } from '@/api/credit/creditXgxf';
  import { pageCreditGqdj, importCreditGqdj } from '@/api/credit/creditGqdj';
  import {
    pageCreditJudiciary,
    importCreditJudiciaries
  } from '@/api/credit/creditJudiciary';

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: CreditCompany | null;
  }>();

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  // 是否显示最大化切换按钮
  const maxable = ref(true);

  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);
  const descriptionColumns = computed(() => (styleResponsive.value ? 3 : 2));

  const tabList = [
    { key: '招投标', label: '招投标' },
    { key: '对外投资', label: '对外投资' },
    { key: '风险关系', label: '风险关系' },
    { key: '竞争对手', label: '竞争对手' },
    { key: '供应商', label: '供应商' },
    { key: '客户', label: '客户' },
    { key: '司法案件', label: '司法案件' },
    { key: '被执行人', label: '被执行人' },
    { key: '限制高消费', label: '限制高消费' },
    { key: '终本案件', label: '终本案件' },
    { key: '开庭公告', label: '开庭公告' },
    { key: '法院公告', label: '法院公告' },
    { key: '失信被执行人', label: '失信被执行人' },
    { key: '裁判文书', label: '裁判文书' },
    { key: '立案信息', label: '立案信息' },
    { key: '诉前调解', label: '诉前调解' },
    { key: '送达公告', label: '送达公告' },
    { key: '股权冻结', label: '股权冻结' },
    { key: '附近企业', label: '附近企业' },
    { key: '分支机构', label: '分支机构' },
    { key: '破产重整', label: '破产重整' },
    { key: '行政许可', label: '行政许可' },
    { key: '疑似关系', label: '疑似关系' },
    { key: '专利', label: '专利' },
    { key: '历史法定代表人', label: '历史法定代表人' }
  ];

  /**
   * 企业详情接口会下发各子表“记录数”(见 CreditCompany 模型中 `// 记录数` 字段)。
   * 用这个来做 Tab 高亮，避免为了计算高亮去逐个请求所有子表接口。
   */
  const tabCountFieldMap: Record<string, keyof CreditCompany> = {
    招投标: 'creditUser',
    对外投资: 'creditExternal',
    风险关系: 'creditRiskRelation',
    竞争对手: 'creditCompetitor',
    供应商: 'creditSupplier',
    客户: 'creditCustomer',
    司法案件: 'creditJudiciary',
    被执行人: 'creditJudgmentDebtor',
    限制高消费: 'creditXgxf',
    终本案件: 'creditFinalVersion',
    开庭公告: 'creditCourtSession',
    法院公告: 'creditCourtAnnouncement',
    失信被执行人: 'creditBreachOfTrust',
    裁判文书: 'creditJudicialDocument',
    立案信息: 'creditCaseFiling',
    诉前调解: 'creditMediation',
    送达公告: 'creditDeliveryNotice',
    股权冻结: 'creditGqdj',
    附近企业: 'creditNearbyCompany',
    分支机构: 'creditBranch',
    破产重整: 'creditBankruptcy',
    行政许可: 'creditAdministrativeLicense',
    疑似关系: 'creditSuspectedRelationship',
    专利: 'creditPatent',
    历史法定代表人: 'creditHistoricalLegalPerson'
  };

  type TabApiConfig = {
    page: (
      params: any
    ) => Promise<{ list: Record<string, any>[]; count?: number } | undefined>;
    importFn: (file: File, companyId?: number) => Promise<string>;
    templatePath: string;
  };

  const tabApiMap: Record<string, TabApiConfig> = {
    招投标: {
      page: pageCreditUser as any,
      importFn: importCreditUsers as any,
      templatePath: '/credit/credit-user/import/template'
    },
    对外投资: {
      page: pageCreditExternal as any,
      importFn: importCreditExternal as any,
      templatePath: '/credit/credit-external/import/template'
    },
    风险关系: {
      page: pageCreditRiskRelation as any,
      importFn: importCreditRiskRelation as any,
      templatePath: '/credit/credit-risk-relation/import/template'
    },
    竞争对手: {
      page: pageCreditCompetitor as any,
      importFn: importCreditCompetitor as any,
      templatePath: '/credit/credit-competitor/import/template'
    },
    供应商: {
      page: pageCreditSupplier as any,
      importFn: importCreditSupplier as any,
      templatePath: '/credit/credit-supplier/import/template'
    },
    客户: {
      page: pageCreditCustomer as any,
      importFn: importCreditCustomer as any,
      templatePath: '/credit/credit-customer/import/template'
    },
    立案信息: {
      page: pageCreditCaseFiling as any,
      importFn: importCreditCaseFiling as any,
      templatePath: '/credit/credit-case-filing/import/template'
    },
    诉前调解: {
      page: pageCreditMediation as any,
      importFn: importCreditMediation as any,
      templatePath: '/credit/credit-mediation/import/template'
    },
    开庭公告: {
      page: pageCreditCourtSession as any,
      importFn: importCreditCourtSession as any,
      templatePath: '/credit/credit-court-session/import/template'
    },
    法院公告: {
      page: pageCreditCourtAnnouncement as any,
      importFn: importCreditCourtAnnouncement as any,
      templatePath: '/credit/credit-court-announcement/import/template'
    },
    送达公告: {
      page: pageCreditDeliveryNotice as any,
      importFn: importCreditDeliveryNotice as any,
      templatePath: '/credit/credit-delivery-notice/import/template'
    },
    裁判文书: {
      page: pageCreditJudicialDocument as any,
      importFn: importCreditJudicialDocument as any,
      templatePath: '/credit/credit-judicial-document/import/template'
    },
    被执行人: {
      page: pageCreditJudgmentDebtor as any,
      importFn: importCreditJudgmentDebtor as any,
      templatePath: '/credit/credit-judgment-debtor/import/template'
    },
    失信被执行人: {
      page: pageCreditBreachOfTrust as any,
      importFn: importCreditBreachOfTrust as any,
      templatePath: '/credit/credit-breach-of-trust/import/template'
    },
    终本案件: {
      page: pageCreditFinalVersion as any,
      importFn: importCreditFinalVersion as any,
      templatePath: '/credit/credit-final-version/import/template'
    },
    限制高消费: {
      page: pageCreditXgxf as any,
      importFn: importCreditXgxf as any,
      templatePath: '/credit/credit-xgxf/import/template'
    },
    股权冻结: {
      page: pageCreditGqdj as any,
      importFn: importCreditGqdj as any,
      templatePath: '/credit/credit-gqdj/import/template'
    },
    司法案件: {
      page: pageCreditJudiciary as any,
      importFn: importCreditJudiciaries as any,
      templatePath: '/credit/credit-judiciary/import/template'
    },
    附近企业: {
      page: pageCreditNearbyCompany as any,
      importFn: importCreditNearbyCompany as any,
      templatePath: '/credit/credit-nearby-company/import/template'
    },
    分支机构: {
      page: pageCreditBranch as any,
      importFn: importCreditBranch as any,
      templatePath: '/credit/credit-branch/import/template'
    },
    破产重整: {
      page: pageCreditBankruptcy as any,
      importFn: importCreditBankruptcy as any,
      templatePath: '/credit/credit-bankruptcy/import/template'
    },
    行政许可: {
      page: pageCreditAdministrativeLicense as any,
      importFn: importCreditAdministrativeLicense as any,
      templatePath: '/credit/credit-administrative-license/import/template'
    },
    疑似关系: {
      page: pageCreditSuspectedRelationship as any,
      importFn: importCreditSuspectedRelationship as any,
      templatePath: '/credit/credit-suspected-relationship/import/template'
    },
    专利: {
      page: pageCreditPatent as any,
      importFn: importCreditPatent as any,
      templatePath: '/credit/credit-patent/import/template'
    },
    历史法定代表人: {
      page: pageCreditHistoricalLegalPerson as any,
      importFn: importCreditHistoricalLegalPerson as any,
      templatePath: '/credit/credit-historical-legal-person/import/template'
    }
  };

  type TableColumn = {
    title: string;
    dataIndex: string;
    key: string;
    ellipsis?: boolean;
    customRender?: (opt: { text: any; record: Record<string, any> }) => any;
  };

  type TabColumnConfig = {
    /**
     * Explicit column list (supports duplicate dataIndex with different titles, e.g. plaintiffUser shown twice).
     * When provided, it takes precedence over `order`.
     */
    columns?: Array<{ dataIndex: string; title: string; key?: string }>;
    order?: string[];
    hidden?: string[];
    titleMap?: Record<string, string>;
  };

  const commonHiddenColumnKeys = new Set<string>([
    'deleted',
    'tenantId',
    'userId',
    'name1',
    'sortNumber',
    'recommend',
    'url',
    'comments',
    'companyId'
  ]);

  const commonTitleMap: Record<string, string> = {
    id: 'ID',
    name: '客户',
    name1: '被执行人',
    code: '税号',
    price: '销售金额(万元)',
    url: '链接地址',
    caseNumber: '案号',
    courtName: '法院',
    occurrenceTime: '发生时间',
    amount: '执行标的',
    status: '状态',
    publicDate: '公开日期',
    dataSource: '数据来源',
    statusTxt: '状态',
    dataStatus: '数据状态',
    comments: '备注',
    createTime: '创建时间',
    updateTime: '修改时间'
  };

  // 每个tab的“字段顺序/隐藏字段/中文表头”在这里配置
  const tabColumnConfigMap: Record<string, TabColumnConfig> = {
    '招投标': {
      order: [
        'id',
        'companyName',
        'name',
        'releaseDate',
        'role',
        'infoType',
        'address',
        'procurementName',
        'winningName',
        'realName',
        'winningPrice'
      ],
      titleMap: {
        id: 'ID',
        companyName: '主体企业',
        name: '项目名称',
        role: '企业角色',
        infoType: '信息类型',
        address: '省份地区',
        procurementName: '招采单位',
        winningName: '中标单位',
        winningPrice: '中标金额',
        releaseDate: '发布日期',
        realName: '操作人'
      }
    },
    '对外投资': {
      order: [
        'id',
        'companyName',
        'name',
        'statusTxt',
        'legalRepresentative',
        'registeredCapital',
        'establishmentDate',
        'shareholdingRatio',
        'subscribedInvestmentAmount',
        'investmentDate',
        'region',
        'industry',
        'investmentCount',
        'relatedProductsInstitutions',
        'realName',
        'createTime'
      ],
      titleMap: {
        id: 'ID',
        companyName: '主体企业',
        name: '被投资企业名称',
        statusTxt: '状态',
        legalRepresentative: '法定代表人',
        registeredCapital: '注册资本',
        establishmentDate: '成立日期',
        shareholdingRatio: '持股比例',
        subscribedInvestmentAmount: '认缴出资额',
        investmentDate: '投资日期',
        region: '所属地区',
        industry: '所属行业',
        investmentCount: '投资数量',
        relatedProductsInstitutions: '关联产品/机构',
        realName: '操作人',
        createTime: '创建时间'
      },
    },
    '风险关系': {
      order: [
        'id',
        'companyName',
        'mainBodyName',
        'registrationStatus',
        'registeredCapital',
        'provinceRegion',
        'associatedRelation',
        'riskRelation',
        'realName',
        'createTime'
      ],
      titleMap: {
        id: '序号',
        companyName: '主体企业',
        mainBodyName: '主体名称',
        registrationStatus: '登记状态',
        registeredCapital: '注册资本',
        provinceRegion: '省份地区',
        associatedRelation: '关联关系',
        riskRelation: '风险关系',
        realName: '操作人',
        createTime: '创建时间'
      }
    },
    '竞争对手': {
      order: [
        'id',
        'companyName',
        'name',
        'legalRepresentative',
        'registeredCapital',
        'establishmentDate',
        'industry',
        'province',
        'realName',
        'createTime'
      ],
      titleMap: {
        id: '序号',
        companyName: '主体企业',
        name: '企业名称',
        legalRepresentative: '法定代表人',
        registeredCapital: '注册资本',
        establishmentDate: '成立日期',
        industry: '所属行业',
        province: '所属省份',
        realName: '操作人',
        createTime: '创建时间'
      },
      hidden: ['mainCompanyName']
    },
    '供应商': {
      order: [
        'id',
        'companyName',
        'supplier',
        'statusTxt',
        'purchaseAmount',
        'publicDate',
        'dataSource',
        'realName',
        'createTime'
      ],
      titleMap: {
        id: 'ID',
        companyName: '主体企业',
        supplier: '供应商',
        statusTxt: '状态',
        purchaseAmount: '采购金额(万元)',
        publicDate: '公开日期',
        dataSource: '数据来源',
        realName: '操作人',
        createTime: '创建时间'
      }
    },
    '客户': {
      order: [
        'id',
        'companyName',
        'name',
        'statusTxt',
        'price',
        'publicDate',
        'dataSource',
        'realName',
        'createTime'
      ],
      titleMap: {
        id: 'ID',
        companyName: '主体企业',
        name: '客户',
        statusTxt: '状态',
        price: '销售金额(万元)',
        publicDate: '公开日期',
        dataSource: '数据来源',
        realName: '操作人',
        createTime: '创建时间'
      },
    },
    '司法案件': {
      order: [
        'id',
        'companyName',
        'code',
        'name',
        'infoType',
        'reason',
        'processDate',
        'caseProgress',
        'caseIdentity',
        'court',
        'caseAmount',
        'realName'
      ],
      titleMap: {
        id: 'ID',
        companyName: '主体企业',
        code: '案号',
        name: '案件名称',
        infoType: '案件类型',
        reason: '案由',
        processDate: '进程日期',
        caseProgress: '案件进程',
        caseIdentity: '案件身份',
        court: '法院',
        caseAmount: '案件金额（元）',
        realName: '操作人'
      },
      hidden: [
        'parentId',
        'type',
        'country',
        'province',
        'city',
        'region',
        'address',
        'expirationTime',
        'createTime'
      ]
    },
    '被执行人': {
      order: [
        'id',
        'companyName',
        'caseNumber',
        'name',
        'code',
        'occurrenceTime',
        'courtName',
        'amount',
        'dataStatus',
        'realName',
        'updateTime'
      ],
      titleMap: {
        id: 'ID',
        companyName: '主体企业',
        caseNumber: '案号',
        name: '被执行人名称',
        code: '证件号/组织机构代码',
        amount: '执行标的(元)',
        courtName: '法院',
        occurrenceTime: '立案日期',
        dataStatus: '数据状态',
        realName: '操作人',
        updateTime: '更新时间'
      },
      hidden: ['historyId', 'historyName', 'createTime']
    },
    '限制高消费': {
      columns: [
        { dataIndex: 'id', title: 'ID' },
        { dataIndex: 'companyName', title: '主体企业' },
        { dataIndex: 'plaintiffUser', title: '原告/上诉人', key: 'plaintiffUser_1' },
        { dataIndex: 'plaintiffUser', title: '被告/被上诉人', key: 'plaintiffUser_2' },
        { dataIndex: 'otherPartiesThirdParty', title: '其他当事人/第三人' },
        { dataIndex: 'occurrenceTime', title: '发生时间' },
        { dataIndex: 'caseNumber', title: '案号' },
        { dataIndex: 'involvedAmount', title: '涉案金额(元)' },
        { dataIndex: 'courtName', title: '执行法院' },
        { dataIndex: 'dataStatus', title: '数据状态' },
        { dataIndex: 'realName', title: '操作人' },
        { dataIndex: 'createTime', title: '创建时间' }
      ]
    },
    '终本案件': {
      columns: [
        { dataIndex: 'id', title: 'ID' },
        { dataIndex: 'companyName', title: '主体企业' },
        { dataIndex: 'dataType', title: '原告/上诉人', key: 'dataType_1' },
        { dataIndex: 'dataType', title: '被告/被上诉人', key: 'dataType_2' },
        { dataIndex: 'dataType', title: '其他当事人/第三人', key: 'dataType_3' },
        { dataIndex: 'occurrenceTime', title: '发生时间' },
        { dataIndex: 'caseNumber', title: '案号' },
        { dataIndex: 'involvedAmount', title: '涉案金额' },
        { dataIndex: 'courtName', title: '法院' },
        { dataIndex: 'dataStatus', title: '数据状态' },
        { dataIndex: 'realName', title: '操作人' },
        { dataIndex: 'createTime', title: '创建时间' }
      ]
    },
    '开庭公告': {
      columns: [
        { dataIndex: 'id', title: 'ID' },
        { dataIndex: 'companyName', title: '主体企业' },
        { dataIndex: 'plaintiffUser', title: '原告/上诉人', key: 'plaintiffUser_1' },
        { dataIndex: 'plaintiffUser', title: '被告/被上诉人', key: 'plaintiffUser_2' },
        { dataIndex: 'otherPartiesThirdParty', title: '其他当事人/第三人' },
        { dataIndex: 'occurrenceTime', title: '发生时间' },
        { dataIndex: 'caseNumber', title: '案号' },
        { dataIndex: 'causeOfAction', title: '案由' },
        { dataIndex: 'involvedAmount', title: '涉案金额' },
        { dataIndex: 'courtName', title: '法院' },
        { dataIndex: 'dataStatus', title: '数据状态' },
        { dataIndex: 'realName', title: '操作人' },
        { dataIndex: 'createTime', title: '创建时间' }
      ]
    },
    '法院公告': {
      columns: [
        { dataIndex: 'id', title: 'ID' },
        { dataIndex: 'companyName', title: '主体企业' },
        { dataIndex: 'plaintiffUser', title: '原告/上诉人', key: 'plaintiffUser_1' },
        { dataIndex: 'plaintiffUser', title: '被告/被上诉人', key: 'plaintiffUser_2' },
        { dataIndex: 'otherPartiesThirdParty', title: '其他当事人/第三人' },
        { dataIndex: 'occurrenceTime', title: '发生时间' },
        { dataIndex: 'caseNumber', title: '案号' },
        { dataIndex: 'causeOfAction', title: '案由' },
        { dataIndex: 'involvedAmount', title: '涉案金额' },
        { dataIndex: 'courtName', title: '法院' },
        { dataIndex: 'dataStatus', title: '数据状态' },
        { dataIndex: 'realName', title: '操作人' },
        { dataIndex: 'createTime', title: '创建时间' }
      ]
    },
    '失信被执行人': {
      columns: [
        { dataIndex: 'id', title: 'ID' },
        { dataIndex: 'companyName', title: '主体企业' },
        { dataIndex: 'plaintiffUser', title: '原告/上诉人', key: 'plaintiffUser_1' },
        { dataIndex: 'plaintiffUser', title: '被告/被上诉人', key: 'plaintiffUser_2' },
        { dataIndex: 'otherPartiesThirdParty', title: '其他当事人/第三人' },
        { dataIndex: 'occurrenceTime', title: '发生时间' },
        { dataIndex: 'caseNumber', title: '案号' },
        { dataIndex: 'involvedAmount', title: '涉案金额' },
        { dataIndex: 'courtName', title: '法院' },
        { dataIndex: 'dataStatus', title: '数据状态' },
        { dataIndex: 'realName', title: '操作人' },
        { dataIndex: 'createTime', title: '创建时间' }
      ]
    },
    '裁判文书': {
      order: [
        'id',
        'companyName',
        'title',
        'type',
        'otherPartiesThirdParty',
        'occurrenceTime',
        'caseNumber',
        'causeOfAction',
        'involvedAmount',
        'courtName',
        'dataStatus',
        'realName',
        'createTime'
      ],
      titleMap: {
        id: 'ID',
        companyName: '主体企业',
        title: '文书标题',
        otherPartiesThirdParty: '当事人',
        occurrenceTime: '裁判日期',
        caseNumber: '案号',
        causeOfAction: '案由',
        involvedAmount: '涉案金额',
        type: '文书类型',
        courtName: '法院',
        dataStatus: '数据状态',
        realName: '操作人',
        createTime: '创建时间'
      },
      hidden: []
    },
    '立案信息': {
      columns: [
        { dataIndex: 'id', title: 'ID' },
        { dataIndex: 'companyName', title: '主体企业' },
        { dataIndex: 'plaintiffUser', title: '原告/上诉人', key: 'plaintiffUser_1' },
        { dataIndex: 'plaintiffUser', title: '被告/被上诉人', key: 'plaintiffUser_2' },
        { dataIndex: 'otherPartiesThirdParty', title: '其他当事人/第三人' },
        { dataIndex: 'occurrenceTime', title: '发生时间' },
        { dataIndex: 'caseNumber', title: '案号' },
        { dataIndex: 'causeOfAction', title: '案由' },
        { dataIndex: 'involvedAmount', title: '涉案金额' },
        { dataIndex: 'courtName', title: '法院' },
        { dataIndex: 'dataStatus', title: '数据状态' },
        { dataIndex: 'realName', title: '操作人' },
        { dataIndex: 'createTime', title: '创建时间' }
      ]
    },
    '诉前调解': {
      columns: [
        { dataIndex: 'id', title: 'ID' },
        { dataIndex: 'companyName', title: '主体企业' },
        { dataIndex: 'plaintiffUser', title: '原告/上诉人', key: 'plaintiffUser_1' },
        { dataIndex: 'plaintiffUser', title: '被告/被上诉人', key: 'plaintiffUser_2' },
        { dataIndex: 'otherPartiesThirdParty', title: '其他当事人/第三人' },
        { dataIndex: 'occurrenceTime', title: '发生时间' },
        { dataIndex: 'caseNumber', title: '案号' },
        { dataIndex: 'causeOfAction', title: '案由' },
        { dataIndex: 'involvedAmount', title: '涉案金额' },
        { dataIndex: 'courtName', title: '法院' },
        { dataIndex: 'dataStatus', title: '数据状态' },
        { dataIndex: 'realName', title: '操作人' },
        { dataIndex: 'createTime', title: '创建时间' }
      ]
    },
    '送达公告': {
      columns: [
        { dataIndex: 'id', title: 'ID' },
        { dataIndex: 'companyName', title: '主体企业' },
        { dataIndex: 'plaintiffUser', title: '原告/上诉人', key: 'plaintiffUser_1' },
        { dataIndex: 'plaintiffUser', title: '被告/被上诉人', key: 'plaintiffUser_2' },
        { dataIndex: 'otherPartiesThirdParty', title: '其他当事人/第三人' },
        { dataIndex: 'occurrenceTime', title: '发生时间' },
        { dataIndex: 'caseNumber', title: '案号' },
        { dataIndex: 'causeOfAction', title: '案由' },
        { dataIndex: 'involvedAmount', title: '涉案金额' },
        { dataIndex: 'courtName', title: '法院' },
        { dataIndex: 'dataStatus', title: '数据状态' },
        { dataIndex: 'realName', title: '操作人' },
        { dataIndex: 'createTime', title: '创建时间' }
      ]
    },
    '股权冻结': {
      columns: [
        { dataIndex: 'id', title: 'ID' },
        { dataIndex: 'companyName', title: '主体企业' },
        { dataIndex: 'caseNumber', title: '案号' },
        { dataIndex: 'plaintiffUser', title: '冻结股权标的企业', key: 'plaintiffUser_1' },
        { dataIndex: 'plaintiffUser', title: '被执行人', key: 'plaintiffUser_2' },
        { dataIndex: 'courtName', title: '执行法院' },
        { dataIndex: 'involvedAmount', title: '被执行人持有股权、其他投资权益数额' },
        { dataIndex: 'publicDate', title: '公示日期' },
        { dataIndex: 'freezeDateStart', title: '冻结开始日期' },
        { dataIndex: 'freezeDateStart', title: '冻结结束日期', key: 'freezeDateStart_2' },
        { dataIndex: 'status', title: '状态' },
        { dataIndex: 'dataStatus', title: '数据状态' },
        { dataIndex: 'realName', title: '操作人' },
        { dataIndex: 'createTime', title: '创建时间' }
      ],
    },
    '附近企业': {
      order: [
        'id',
        'companyName',
        'name',
        'registrationStatus',
        'legalPerson',
        'registeredCapital',
        'establishDate',
        'code',
        'address',
        'postalCode',
        'phone',
        'moreTel',
        'email',
        'moreEmail',
        'country',
        'province',
        'city',
        'region',
        'taxpayerCode',
        'registrationNumber',
        'organizationalCode',
        'numberOfInsuredPersons',
        'annualReport',
        'institutionType',
        'companySize',
        'businessTerm',
        'nationalStandardIndustryCategories',
        'nationalStandardIndustryCategories2',
        'nationalStandardIndustryCategories3',
        'nationalStandardIndustryCategories4',
        'formerName',
        'englishName',
        'domain',
        'mailingAddress',
        'mailingEmail',
        'companyProfile',
        'natureOfBusiness',
        'tel',
        'nationalStandardIndustryCategories5',
        'nationalStandardIndustryCategories6',
        'nationalStandardIndustryCategories7',
        'nationalStandardIndustryCategories8',
        'type',
        'paidinCapital',
        'registrationAuthority',
        'taxpayerQualification',
        'latestAnnualReportYear',
        'latestAnnualReportOnOperatingRevenue',
        'enterpriseScoreCheck',
        'creditRating',
        'cechnologyScore',
        'cechnologyLevel',
        'smallEnterprise',
        'realName',
        'createTime'
      ],
      titleMap: {
        id: 'ID',
        companyName: '主体企业',
        name: '企业名称',
        registrationStatus: '登记状态',
        legalPerson: '法定代表人',
        registeredCapital: '注册资本',
        establishDate: '成立日期',
        code: '统一社会信用代码',
        address: '注册地址',
        postalCode: '注册地址邮编',
        phone: '有效手机号',
        moreTel: '更多电话',
        email: '邮箱',
        moreEmail: '邮箱',
        country: '所在国家',
        province: '所属省份',
        city: '所属城市',
        region: '所属区县',
        taxpayerCode: '纳税人识别号',
        registrationNumber: '注册号',
        organizationalCode: '组织机构代码',
        numberOfInsuredPersons: '参保人数',
        annualReport: '参保人数所属年报',
        institutionType: '企业(机构)类型',
        companySize: '企业规模',
        businessTerm: '营业期限',
        nationalStandardIndustryCategories: '国标行业门类',
        nationalStandardIndustryCategories2: '国标行业大类',
        nationalStandardIndustryCategories3: '国标行业中类',
        nationalStandardIndustryCategories4: '国标行业小类',
        formerName: '曾用名',
        englishName: '英文名',
        domain: '官网网址',
        mailingAddress: '通信地址',
        mailingEmail: '通信地址邮箱',
        companyProfile: '企业简介',
        natureOfBusiness: '经营范围',
        tel: '电话',
        nationalStandardIndustryCategories5: '企查查行业门类',
        nationalStandardIndustryCategories6: '企查查行业大类',
        nationalStandardIndustryCategories7: '企查查行业中类',
        nationalStandardIndustryCategories8: '企查查行业小类',
        type: '类型',
        paidinCapital: '实缴资本',
        registrationAuthority: '登记机关',
        taxpayerQualification: '纳税人资质',
        latestAnnualReportYear: '最新年报年份',
        latestAnnualReportOnOperatingRevenue: '最新年报营业收入',
        enterpriseScoreCheck: '企查分',
        creditRating: '信用等级',
        cechnologyScore: '科创分',
        cechnologyLevel: '科创等级',
        smallEnterprise: '是否小微企业',
        realName: '操作人',
        createTime: '创建时间'
      },
      hidden: ['parentId']
    },
    '分支机构': {
      order: [
        'id',
        'companyName',
        'name',
        'curator',
        'region',
        'establishDate',
        'statusText',
        'realName',
        'createTime'
      ],
      titleMap: {
        id: 'ID',
        companyName: '主体企业',
        name: '分支机构名称',
        curator: '负责人',
        region: '地区',
        establishDate: '成立日期',
        statusText: '状态',
        realName: '操作人',
        createTime: '创建时间'
      },
      hidden: []
    },
    '破产重整': {
      order: [
        'id',
        'companyName',
        'code',
        'type',
        'party',
        'court',
        'publicDate',
        'realName',
        'createTime'
      ],
      titleMap: {
        id: 'ID',
        companyName: '主体企业',
        code: '案号',
        type: '案件类型',
        party: '当事人',
        court: '经办法院',
        publicDate: '公开日期',
        realName: '操作人',
        createTime: '创建时间'
      },
      hidden: []
    },
    '行政许可': {
      order: [
        'id',
        'companyName',
        'code',
        'name',
        'statusText',
        'type',
        'validityStart',
        'validityEnd',
        'licensingAuthority',
        'licenseContent',
        'dataSourceUnit',
        'realName',
        'createTime'
      ],
      titleMap: {
        id: 'ID',
        companyName: '主体企业',
        code: '决定文书/许可编号',
        name: '决定文书/许可证名称',
        statusText: '许可状态',
        type: '许可类型',
        validityStart: '有效期自',
        validityEnd: '有效期至',
        licensingAuthority: '许可机关',
        licenseContent: '许可内容',
        dataSourceUnit: '数据来源单位',
        realName: '操作人',
        createTime: '创建时间'
      },
      hidden: []
    },
    '疑似关系': {
      order: [
        'id',
        'companyName',
        'name',
        'statusText',
        'legalPerson',
        'registeredCapital',
        'createDate',
        'relatedParty',
        'type',
        'detail',
        'realName',
        'createTime'
      ],
      titleMap: {
        id: 'ID',
        companyName: '主体企业',
        name: '企业名称',
        statusText: '状态',
        legalPerson: '法定代表人',
        registeredCapital: '注册资本',
        createDate: '成立日期',
        relatedParty: '关联方',
        type: '疑似关系类型',
        detail: '疑似关系详情',
        realName: '操作人',
        createTime: '创建时间'
      },
      hidden: []
    },
    '专利': {
      order: [
        'id',
        'companyName',
        'name',
        'type',
        'statusText',
        'registerNo',
        'registerDate',
        'publicNo',
        'publicDate',
        'inventor',
        'patentApplicant',
        'realName',
        'createTime'
      ],
      titleMap: {
        id: 'ID',
        companyName: '主体企业',
        name: '发明名称',
        type: '专利类型',
        statusText: '法律状态',
        registerNo: '申请号',
        registerDate: '申请日',
        publicNo: '公开(公告)号',
        publicDate: '公开(公告)日期',
        inventor: '发明人',
        patentApplicant: '申请(专利权)人',
        realName: '操作人',
        createTime: '创建时间'
      },
      hidden: []
    },
    '历史法定代表人': {
      order: [
        'id',
        'companyName',
        'name',
        'registerDate',
        'publicDate',
        'realName',
        'createTime'
      ],
      titleMap: {
        id: 'ID',
        companyName: '主体企业',
        name: '名称',
        registerDate: '任职日期',
        publicDate: '卸任日期',
        realName: '操作人',
        createTime: '创建时间'
      },
      hidden: []
    }
  };

  type TabState = {
    loading: boolean;
    data: Record<string, any>[];
    columns: TableColumn[];
    pagination: {
      current: number;
      pageSize: number;
      total: number;
    };
    loadedSignature?: string;
  };

  const tabState = reactive<Record<string, TabState>>({});
  const tabHasData = reactive<Record<string, boolean>>({});
  tabList.forEach((tab) => {
    tabState[tab.key] = {
      loading: false,
      data: [],
      columns: [],
      pagination: {
        current: 1,
        pageSize: 20,
        total: 0
      },
      loadedSignature: undefined
    };
    tabHasData[tab.key] = false;
  });
  const activeTab = ref(tabList[0].key);

  const resetTabPagination = (key: string) => {
    tabState[key].pagination.current = 1;
    tabState[key].pagination.pageSize = 20;
    tabState[key].pagination.total = 0;
  };

  const setTabPagination = (
    key: string,
    next: Partial<TabState['pagination']>
  ) => {
    Object.assign(tabState[key].pagination, next);
  };

  const handleTabPageChange = (key: string, page: number, pageSize: number) => {
    const prevPageSize = tabState[key].pagination.pageSize;
    setTabPagination(key, {
      current: pageSize !== prevPageSize ? 1 : page,
      pageSize
    });
    loadTabData(key);
  };

  const getTabPagination = (key: string) => {
    const state = tabState[key];
    return {
      current: state.pagination.current,
      pageSize: state.pagination.pageSize,
      total: state.pagination.total,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100', '200'],
      showTotal: (total: number) => `共 ${total} 条`,
      onChange: (page: number, pageSize: number) =>
        handleTabPageChange(key, page, pageSize),
      onShowSizeChange: (page: number, pageSize: number) =>
        handleTabPageChange(key, page, pageSize)
    };
  };

  // 子表导入弹窗
  const showRelatedImport = ref(false);
  const relatedImportTabKey = ref(tabList[0].key);
  const relatedImportConfig = computed(
    () => tabApiMap[relatedImportTabKey.value]
  );
  const relatedImportTitle = computed(() => {
    const tab = tabList.find((t) => t.key === relatedImportTabKey.value);
    return `${tab?.label ?? relatedImportTabKey.value}批量导入`;
  });
  const relatedImportTemplatePath = computed(
    () => relatedImportConfig.value?.templatePath ?? ''
  );
  const relatedImportFn = (file: File, companyId?: number) => {
    const fn = relatedImportConfig.value?.importFn;
    if (!fn) {
      return Promise.reject(new Error('未配置导入接口'));
    }
    return fn(file, companyId);
  };

  const openRelatedImport = (key: string) => {
    if (!form.id) {
      message.error('缺少企业ID，无法导入');
      return;
    }
    if (!tabApiMap[key]) {
      message.error('未配置该Tab的导入功能');
      return;
    }
    relatedImportTabKey.value = key;
    showRelatedImport.value = true;
  };

  const handleRelatedImportDone = () => {
    resetTabPagination(activeTab.value);
    reloadTab(activeTab.value);
  };

  // 历史行政许可导入弹窗（企业详情-行政许可tab）
  const showAdministrativeLicenseHistoryImport = ref(false);

  const openAdministrativeLicenseHistoryImport = () => {
    if (!form.id) {
      message.error('缺少企业ID，无法导入');
      return;
    }
    showAdministrativeLicenseHistoryImport.value = true;
  };

  const handleAdministrativeLicenseHistoryImportDone = () => {
    resetTabPagination('行政许可');
    reloadTab('行政许可');
  };

  // 历史破产重整导入弹窗（企业详情-破产重整tab）
  const showBankruptcyHistoryImport = ref(false);

  const openBankruptcyHistoryImport = () => {
    if (!form.id) {
      message.error('缺少企业ID，无法导入');
      return;
    }
    showBankruptcyHistoryImport.value = true;
  };

  const handleBankruptcyHistoryImportDone = () => {
    resetTabPagination('破产重整');
    reloadTab('破产重整');
  };

  // 历史被执行人导入弹窗（企业详情-被执行人tab）
  const showJudgmentDebtorHistoryImport = ref(false);

  const openJudgmentDebtorHistoryImport = () => {
    if (!form.id) {
      message.error('缺少企业ID，无法导入');
      return;
    }
    showJudgmentDebtorHistoryImport.value = true;
  };

  const handleJudgmentDebtorHistoryImportDone = () => {
    resetTabPagination('被执行人');
    reloadTab('被执行人');
  };

  // 历史限制高消费导入弹窗（企业详情-限制高消费tab）
  const showXgxfHistoryImport = ref(false);

  const openXgxfHistoryImport = () => {
    if (!form.id) {
      message.error('缺少企业ID，无法导入');
      return;
    }
    showXgxfHistoryImport.value = true;
  };

  const handleXgxfHistoryImportDone = () => {
    resetTabPagination('限制高消费');
    reloadTab('限制高消费');
  };

  // 历史终本案件导入弹窗（企业详情-终本案件tab）
  const showFinalVersionHistoryImport = ref(false);

  const openFinalVersionHistoryImport = () => {
    if (!form.id) {
      message.error('缺少企业ID，无法导入');
      return;
    }
    showFinalVersionHistoryImport.value = true;
  };

  const handleFinalVersionHistoryImportDone = () => {
    resetTabPagination('终本案件');
    reloadTab('终本案件');
  };

  // 历史开庭公告导入弹窗（企业详情-开庭公告tab）
  const showCourtSessionHistoryImport = ref(false);

  const openCourtSessionHistoryImport = () => {
    if (!form.id) {
      message.error('缺少企业ID，无法导入');
      return;
    }
    showCourtSessionHistoryImport.value = true;
  };

  const handleCourtSessionHistoryImportDone = () => {
    resetTabPagination('开庭公告');
    reloadTab('开庭公告');
  };

  // 历史法院公告导入弹窗（企业详情-法院公告tab）
  const showCourtAnnouncementHistoryImport = ref(false);

  const openCourtAnnouncementHistoryImport = () => {
    if (!form.id) {
      message.error('缺少企业ID，无法导入');
      return;
    }
    showCourtAnnouncementHistoryImport.value = true;
  };

  const handleCourtAnnouncementHistoryImportDone = () => {
    resetTabPagination('法院公告');
    reloadTab('法院公告');
  };

  // 历史失信被执行人导入弹窗（企业详情-失信被执行人tab）
  const showBreachOfTrustHistoryImport = ref(false);

  const openBreachOfTrustHistoryImport = () => {
    if (!form.id) {
      message.error('缺少企业ID，无法导入');
      return;
    }
    showBreachOfTrustHistoryImport.value = true;
  };

  const handleBreachOfTrustHistoryImportDone = () => {
    resetTabPagination('失信被执行人');
    reloadTab('失信被执行人');
  };

  // 历史裁判文书导入弹窗（企业详情-裁判文书tab）
  const showJudicialDocumentHistoryImport = ref(false);

  const openJudicialDocumentHistoryImport = () => {
    if (!form.id) {
      message.error('缺少企业ID，无法导入');
      return;
    }
    showJudicialDocumentHistoryImport.value = true;
  };

  const handleJudicialDocumentHistoryImportDone = () => {
    resetTabPagination('裁判文书');
    reloadTab('裁判文书');
  };

  // 历史股权冻结导入弹窗（企业详情-股权冻结tab）
  const showGqdjHistoryImport = ref(false);

  const openGqdjHistoryImport = () => {
    if (!form.id) {
      message.error('缺少企业ID，无法导入');
      return;
    }
    showGqdjHistoryImport.value = true;
  };

  const handleGqdjHistoryImportDone = () => {
    resetTabPagination('股权冻结');
    reloadTab('股权冻结');
  };

  const defaultForm: CreditCompany = {
    id: undefined,
    name: undefined,
    matchName: undefined,
    code: undefined,
    type: undefined,
    parentId: undefined,
    registrationStatus: undefined,
    legalPerson: undefined,
    registeredCapital: undefined,
    paidinCapital: undefined,
    establishDate: undefined,
    address: undefined,
    tel: undefined,
    moreTel: undefined,
    email: undefined,
    moreEmail: undefined,
    country: undefined,
    province: undefined,
    city: undefined,
    region: undefined,
    institutionType: undefined,
    taxpayerCode: undefined,
    registrationNumber: undefined,
    organizationalCode: undefined,
    numberOfInsuredPersons: undefined,
    annualReport: undefined,
    businessTerm: undefined,
    nationalStandardIndustryCategories: undefined,
    nationalStandardIndustryCategories2: undefined,
    nationalStandardIndustryCategories3: undefined,
    nationalStandardIndustryCategories4: undefined,
    nationalStandardIndustryCategories5: undefined,
    nationalStandardIndustryCategories6: undefined,
    nationalStandardIndustryCategories7: undefined,
    nationalStandardIndustryCategories8: undefined,
    companySize: undefined,
    formerName: undefined,
    englishName: undefined,
    domain: undefined,
    mailingAddress: undefined,
    companyProfile: undefined,
    natureOfBusiness: undefined,
    registrationAuthority: undefined,
    taxpayerQualification: undefined,
    latestAnnualReportYear: undefined,
    latestAnnualReportOnOperatingRevenue: undefined,
    enterpriseScoreCheck: undefined,
    creditRating: undefined,
    cechnologyScore: undefined,
    cechnologyLevel: undefined,
    smallEnterprise: undefined,
    recommend: undefined,
    deleted: undefined,
    userId: undefined,
    tenantId: undefined,
    createTime: undefined,
    updateTime: undefined,
    status: 0,
    comments: ''
  };

  // 用户信息
  const form = reactive<CreditCompany>({ ...defaultForm });

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  const formatValue = (value: unknown) => {
    if (value === undefined || value === null || value === '') {
      return '-';
    }
    return value;
  };

  // const formatStatus = (status?: number) => {
  //   if (status === 0) {
  //     return '显示';
  //   }
  //   if (status === 1) {
  //     return '隐藏';
  //   }
  //   return '-';
  // };

  const getRowKey = (record: Record<string, any>, index: number) => {
    return record.id ?? record.code ?? record.key ?? index;
  };

  const buildColumns = (
    tabKey: string,
    rows: Record<string, any>[]
  ): TableColumn[] => {
    if (!rows.length) {
      return [];
    }
    const config = tabColumnConfigMap[tabKey];
    const hidden = new Set<string>([
      ...commonHiddenColumnKeys,
      ...(config?.hidden ?? [])
    ]);
    const titleMap = { ...commonTitleMap, ...(config?.titleMap ?? {}) };

    const linkTextDataIndex = new Set([
      'name',
      'code',
      'caseNumber',
      'registerNo'
    ]);

    // Prefer explicit columns to match the corresponding credit module headers exactly.
    const explicitColumns = config?.columns;
    if (explicitColumns?.length) {
      return explicitColumns
        .filter((col) => !hidden.has(col.dataIndex))
        .map((col, idx) => {
          const dataIndex = col.dataIndex;
          const key = col.key ?? `${dataIndex}_${idx}`;
          const column: TableColumn = {
            title: col.title ?? titleMap[dataIndex] ?? dataIndex,
            dataIndex,
            key,
            ellipsis: true
          };
          if (linkTextDataIndex.has(dataIndex)) {
            column.customRender = ({ text, record }) => {
              if (record?.url && text) {
                return h('a', { href: record.url, target: '_blank' }, text);
              }
              return text;
            };
          }
          return column;
        });
    }

    const keysFromData = Object.keys(rows[0]);
    const keysSet = new Set(keysFromData);
    const keys = config?.order?.length ? config.order : keysFromData;
    const finalKeys = keys.filter((k) => {
      if (hidden.has(k)) {
        return false;
      }
      // If `order` is provided, keep keys even if not present in the first row
      // (module tables render blank cells for missing fields).
      if (config?.order?.length) {
        return true;
      }
      return keysSet.has(k);
    });

    return finalKeys.map((dataIndex, idx) => {
      const key = `${dataIndex}_${idx}`;
      const column: TableColumn = {
        title: titleMap[dataIndex] ?? dataIndex,
        dataIndex,
        key,
        ellipsis: true
      };
      if (linkTextDataIndex.has(dataIndex)) {
        column.customRender = ({ text, record }) => {
          if (record?.url && text) {
            return h('a', { href: record.url, target: '_blank' }, text);
          }
          return text;
        };
      }
      return column;
    });
  };

  const resetForm = () => {
    Object.assign(form, defaultForm);
  };

  const clearTabData = () => {
    tabList.forEach((tab) => {
      tabState[tab.key].data = [];
      tabState[tab.key].columns = [];
      tabState[tab.key].loading = false;
      tabState[tab.key].loadedSignature = undefined;
      resetTabPagination(tab.key);
      tabHasData[tab.key] = false;
    });
  };

  const syncTabsHasDataFromCounts = () => {
    tabList.forEach((tab) => {
      const field = tabCountFieldMap[tab.key];
      const raw = (form as any)?.[field] ?? (props.data as any)?.[field] ?? 0;
      tabHasData[tab.key] = Number(raw) > 0;
    });
  };

  const loadTabData = async (key: string, force = false) => {
    const taxpayerCode = form.code ?? props.data?.code;
    const companyId = form.id ?? props.data?.id;
    const identity = taxpayerCode
      ? `tax:${taxpayerCode}`
      : companyId
      ? `id:${companyId}`
      : undefined;
    const state = tabState[key];
    const api = tabApiMap[key]?.page;
    if (!api) {
      state.data = [];
      state.columns = [];
      state.pagination.total = 0;
      state.loadedSignature = undefined;
      return;
    }
    if (!identity) {
      state.data = [];
      state.columns = [];
      state.pagination.total = 0;
      state.loadedSignature = undefined;
      return;
    }
    const signature = `${identity}|p:${state.pagination.current}|l:${state.pagination.pageSize}`;
    if (!force && state.loadedSignature === signature) {
      return;
    }
    state.loading = true;
    try {
      const fetchPage = async (page: number) => {
        return api({
          taxpayerCode,
          companyId,
          page,
          limit: state.pagination.pageSize
        });
      };

      const requestedPage = state.pagination.current;
      let res = await fetchPage(requestedPage);
      let list = res?.list || [];
      const total =
        typeof (res as any)?.count === 'number' ? (res as any).count : list.length;

      if (total > 0 && list.length === 0 && requestedPage > 1) {
        setTabPagination(key, { current: 1 });
        res = await fetchPage(1);
        list = res?.list || [];
      }

      state.pagination.total =
        typeof (res as any)?.count === 'number' ? (res as any).count : list.length;
      // Keep the count field in sync (only when backend returns a count), so Tab highlight can update after import/refresh.
      const countField = tabCountFieldMap[key];
      if (countField && typeof (res as any)?.count === 'number') {
        (form as any)[countField] = (res as any).count;
      }
      state.data = list;
      tabHasData[key] = (state.pagination.total ?? 0) > 0;
      if (!state.columns.length) {
        state.columns = buildColumns(key, state.data);
      }
      state.loadedSignature = `${identity}|p:${state.pagination.current}|l:${state.pagination.pageSize}`;
    } catch (e: any) {
      state.data = [];
      state.columns = [];
      state.pagination.total = 0;
      state.loadedSignature = undefined;
      message.error(e?.message ?? '查询失败');
    } finally {
      state.loading = false;
    }
  };

  const reloadTab = (key: string) => {
    loadTabData(key, true);
  };

  watch(
    () => activeTab.value,
    (key) => {
      loadTabData(key);
    }
  );

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        showRelatedImport.value = false;
        resetForm();
        clearTabData();
        if (props.data) {
          assignObject(form, props.data);
        }
        activeTab.value = tabList[0].key;
        syncTabsHasDataFromCounts();
        loadTabData(activeTab.value, true);
      } else {
        showRelatedImport.value = false;
        resetForm();
        clearTabData();
      }
    },
    { immediate: true }
  );

  watch(
    () => props.data,
    (data) => {
      if (!props.visible || !data) {
        return;
      }
      showRelatedImport.value = false;
      resetForm();
      clearTabData();
      assignObject(form, data);
      syncTabsHasDataFromCounts();
      loadTabData(activeTab.value, true);
    }
  );
</script>

<style scoped>
  /* Tab label highlight when the module record-count field is > 0. */
  .credit-company-tab-has-data {
    color: #ff4d4f;
    font-weight: 600;
  }
</style>
