<!-- 编辑弹窗 -->
<template>
  <a-drawer
    width="96%"
    :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="8"
      class="credit-company-tabs"
    >
      <a-tab-pane v-for="tab in tabList" :key="tab.key" :tab="tab.label">
        <a-space style="margin-bottom: 12px">
          <a-button
            type="primary"
            :disabled="!form.id"
            @click="openRelatedImport(tab.key)"
          >
            导入(多)
          </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"
    />
  </a-drawer>
</template>

<script lang="ts" setup>
  import { computed, h, reactive, ref, watch } from 'vue';
  import { message } from 'ant-design-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 {
    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: '历史法定代表人' }
  ];

  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 = {
    order?: string[];
    hidden?: string[];
    titleMap?: Record<string, string>;
  };

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

  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: [
        'name',
        'role',
        'caseNumber',
        'procurementName',
        'winningName',
        'winningPrice',
        'releaseDate',
        'url',
        'createTime',
        'updateTime'
      ],
      hidden: [
        'type',
        'parentId',
        'sortNumber',
        'recommend',
        'expirationTime',
        'updateTime'
      ],
      titleMap: {
        name: '项目名称',
        role: '企业角色',
        caseNumber: '案号',
        procurementName: '招采单位名称',
        winningName: '中标单位名称',
        winningPrice: '中标金额',
        releaseDate: '发布日期',
        url: '链接地址',
        createTime: '创建时间',
        updateTime: '修改时间'
      }
    },
    对外投资: {
      titleMap: {
        registeredCapital: '注册资本',
        establishmentDate: '成立日期',
        legalRepresentative: '法定代表人姓名',
        shareholdingRatio: '持股比例',
        subscribedInvestmentAmount: '认缴出资额',
        subscribedInvestmentDate: '认缴出资日期',
        indirectShareholdingRatio: '间接持股比例',
        investmentDate: '投资日期',
        region: '所属地区',
        industry: '所属行业',
        investmentCount: '投资数量',
        relatedProductsInstitutions: '关联产品/机构'
      }
    },
    风险关系: {
      titleMap: {
        mainBodyName: '主体名称',
        registrationStatus: '登记状态',
        registeredCapital: '注册资本',
        provinceRegion: '省份地区',
        associatedRelation: '关联关系',
        riskRelation: '风险关系'
      }
    },
    竞争对手: {
      titleMap: {
        legalRepresentative: '法定代表人',
        registeredCapital: '注册资本',
        establishmentDate: '成立日期',
        registrationStatus: '登记状态',
        industry: '所属行业',
        province: '所属省份',
        mainCompanyName: '企业名称'
      }
    },
    供应商: {
      titleMap: {
        supplier: '供应商',
        purchaseAmount: '采购金额(万元)',
      }
    },
    立案信息: {
      titleMap: {
        dataType: '数据状态',
        appellee: '被告/被上诉人',
        otherPartiesThirdParty: '其他当事人/第三人',
        plaintiffAppellant: '原告/上诉人',
        causeOfAction: '案由',
        involvedAmount: '涉案金额'
      },
      hidden: ['dataStatus']
    },
    诉前调解: {
      titleMap: {
        dataType: '数据状态',
        plaintiffAppellant: '原告/上诉人',
        appellee: '被告/被上诉人',
        otherPartiesThirdParty: '其他当事人/第三人',
        causeOfAction: '案由',
        involvedAmount: '涉案金额'

      },
      hidden: ['dataStatus']
    },
    开庭公告: {
      titleMap: {
        dataType: '数据状态',
        plaintiffAppellant: '原告/上诉人',
        appellee: '被告/被上诉人',
        otherPartiesThirdParty: '其他当事人/第三人',
        causeOfAction: '案由',
        involvedAmount: '涉案金额'
      }
    },
    法院公告: {
      titleMap: {
        dataType: '数据状态',
        plaintiffAppellant: '原告/上诉人',
        appellee: '被告/被上诉人',
        otherPartiesThirdParty: '其他当事人/第三人',
        causeOfAction: '案由',
        involvedAmount: '涉案金额'
      }
    },
    送达公告: {
      titleMap: {
        dataType: '数据状态',
        plaintiffAppellant: '原告/上诉人',
        appellee: '被告/被上诉人',
        otherPartiesThirdParty: '其他当事人/第三人',
        causeOfAction: '案由',
        involvedAmount: '涉案金额'
      }
    },
    裁判文书: {
      titleMap: {
        dataType: '数据状态',
        plaintiffAppellant: '原告/上诉人',
        appellee: '被告/被上诉人',
        otherPartiesThirdParty: '其他当事人/第三人',
        causeOfAction: '案由',
        involvedAmount: '涉案金额'
      }
    },
    被执行人: {
      titleMap: {
        historyId: '历史被执行人ID',
        historyName: '历史被执行人名称'
      },
      hidden: ['historyId','dataStatus']
    },
    失信被执行人: {
      titleMap: {
        dataType: '数据状态',
        plaintiffAppellant: '原告/上诉人',
        appellee: '被告/被上诉人',
        otherPartiesThirdParty: '其他当事人/第三人',
        causeOfAction: '案由',
        involvedAmount: '涉案金额',
      },
      hidden: ['dataStatus']
    },
    终本案件: {
      titleMap: {
        dataType: '数据状态',
        plaintiffAppellant: '原告/上诉人',
        appellee: '被告/被上诉人',
        otherPartiesThirdParty: '其他当事人/第三人',
        causeOfAction: '案由',
        involvedAmount: '涉案金额'
      },
      hidden: ['dataStatus']
    },
    限制高消费: {
      titleMap: {
        dataType: '数据状态',
        plaintiffAppellant: '原告/上诉人',
        appellee: '被告/被上诉人',
        otherPartiesThirdParty: '其他当事人/第三人',
        causeOfAction: '案由',
        involvedAmount: '涉案金额'
      },
      hidden: ['dataStatus']
    },
    股权冻结: {
      titleMap: {
        dataType: '数据状态',
        plaintiffAppellant: '原告/上诉人',
        appellee: '被告/被上诉人',
        otherPartiesThirdParty: '其他当事人/第三人',
        causeOfAction: '案由',
        involvedAmount: '涉案金额'
      },
      hidden: ['dataStatus']
    },
    司法案件: {
      titleMap: {
        reason: '案由',
        infoType: '案件类型',
        country: '国家',
        province: '省份',
        city: '城市',
        region: '地区',
        address: '地址',
        caseProgress: '案件进度',
        caseIdentity: '案件身份',
        court: '法院',
        processDate: '进程时间',
        caseAmount: '案件金额（元）',
        expirationTime: '到期时间'
      },
      hidden: ['parentId','type']

    },
    附近企业: {
      order: [
        'name',
        'registrationStatus',
        'legalPerson',
        'registeredCapital',
        'establishDate',
        'code',
        'address',
        'phone',
        'email',
        'domain',
        'createTime'
      ],
      titleMap: {
        name: '企业名称',
        registrationStatus: '登记状态',
        legalPerson: '法定代表人',
        registeredCapital: '注册资本',
        establishDate: '成立日期',
        code: '统一社会信用代码',
        address: '注册地址',
        phone: '有效手机号',
        email: '邮箱',
        domain: '官网网址',
        createTime: '创建时间'
      }
    },
    分支机构: {
      order: [
        'name',
        'curator',
        'region',
        'establishDate',
        'statusText',
        'createTime'
      ],
      titleMap: {
        name: '分支机构名称',
        curator: '负责人',
        region: '地区',
        establishDate: '成立日期',
        statusText: '状态',
        createTime: '创建时间'
      }
    },
    破产重整: {
      order: ['code', 'type', 'party', 'court', 'publicDate', 'createTime'],
      titleMap: {
        code: '案号',
        type: '案件类型',
        party: '当事人',
        court: '经办法院',
        publicDate: '公开日期',
        createTime: '创建时间'
      }
    },
    行政许可: {
      order: [
        'code',
        'name',
        'statusText',
        'type',
        'validityStart',
        'validityEnd',
        'licensingAuthority',
        'createTime'
      ],
      titleMap: {
        code: '许可编号',
        name: '许可证名称',
        statusText: '许可状态',
        type: '许可类型',
        validityStart: '有效期自',
        validityEnd: '有效期至',
        licensingAuthority: '许可机关',
        createTime: '创建时间'
      }
    },
    疑似关系: {
      order: [
        'name',
        'statusText',
        'legalPerson',
        'registeredCapital',
        'createDate',
        'relatedParty',
        'type',
        'detail',
        'createTime'
      ],
      titleMap: {
        name: '企业名称',
        statusText: '状态',
        legalPerson: '法定代表人',
        registeredCapital: '注册资本',
        createDate: '成立日期',
        relatedParty: '关联方',
        type: '疑似关系类型',
        detail: '疑似关系详情',
        createTime: '创建时间'
      }
    },
    专利: {
      order: [
        'name',
        'type',
        'statusText',
        'registerNo',
        'registerDate',
        'publicNo',
        'publicDate',
        'inventor',
        'patentApplicant',
        'createTime'
      ],
      titleMap: {
        name: '发明名称',
        type: '专利类型',
        statusText: '法律状态',
        registerNo: '申请号',
        registerDate: '申请日',
        publicNo: '公开(公告)号',
        publicDate: '公开(公告)日期',
        inventor: '发明人',
        patentApplicant: '申请(专利权)人',
        createTime: '创建时间'
      }
    },
    历史法定代表人: {
      order: ['name', 'registerDate', 'publicDate', 'createTime'],
      titleMap: {
        name: '名称',
        registerDate: '任职日期',
        publicDate: '卸任日期',
        createTime: '创建时间'
      }
    }
  };

  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>>({});
  tabList.forEach((tab) => {
    tabState[tab.key] = {
      loading: false,
      data: [],
      columns: [],
      pagination: {
        current: 1,
        pageSize: 20,
        total: 0
      },
      loadedSignature: undefined
    };
  });
  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);
  };

  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 keysFromData = Object.keys(rows[0]);
    const keysSet = new Set(keysFromData);
    const keys = config?.order?.length ? config.order : keysFromData;
    const finalKeys = keys.filter((k) => keysSet.has(k) && !hidden.has(k));

    const linkTextKeys = new Set(['name', 'code', 'caseNumber', 'registerNo']);
    return finalKeys.map((key) => {
      const column: TableColumn = {
        title: titleMap[key] ?? key,
        dataIndex: key,
        key,
        ellipsis: true
      };
      if (linkTextKeys.has(key)) {
        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);
    });
  };

  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);
      const total = res?.count ?? 0;
      let list = res?.list || [];

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

      state.pagination.total = res?.count ?? 0;
      state.data = list;
      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;
        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);
      loadTabData(activeTab.value, true);
    }
  );
</script>
