<template>
  <div class="search-form">
    <!-- 原有的查询条件区域 -->
    <div class="query-container">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-form-item label="产品" labelAlign="left">
            <a-input v-model:value="form.product" placeholder="产品" />
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="HS编码" labelAlign="left">
            <a-input v-model:value="form.hsCode" placeholder="HS编码" />
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="起始日期" labelAlign="left">
            <a-date-picker v-model:value="form.startDate" placeholder="起始日期" />
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="截止日期" labelAlign="left">
            <a-date-picker v-model:value="form.endDate" placeholder="截止日期" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="6">
          <a-form-item label="供应商" labelAlign="left">
            <a-input v-model:value="form.supplier" placeholder="供应商" />
          </a-form-item>
        </a-col>
        <!-- <a-col :span="6">
          <a-form-item label="供应商注册号" labelAlign="left">
            <a-input v-model:value="form.supplierReg" placeholder="供应商注册号" />
          </a-form-item>
        </a-col> -->
        <a-col :span="6">
          <a-form-item label="供应商地址" labelAlign="left">
            <a-input v-model:value="form.supplierAddress" placeholder="供应商地址" />
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <div class="checkbox-group">
            <a-checkbox-group v-model:value="form.options">
              <a-checkbox value="excludeLogistics">去除物流</a-checkbox>
              <a-checkbox value="excludeNVL">去除NVL</a-checkbox>
            </a-checkbox-group>
          </div>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="6">
          <a-form-item label="采购商" labelAlign="left">
            <a-input v-model:value="form.buyer" placeholder="采购商" />
          </a-form-item>
        </a-col>
        <!-- <a-col :span="6">
          <a-form-item label="采购商注册号" labelAlign="left">
            <a-input v-model:value="form.buyerReg" placeholder="采购商注册号" />
          </a-form-item>
        </a-col> -->
        <a-col :span="6">
          <a-form-item label="采购商地址" labelAlign="left">
            <a-input v-model:value="form.buyerAddress" placeholder="采购商地址" />
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <div class="checkbox-group">
            <a-checkbox-group v-model:value="form.buyerOptions">
              <a-checkbox value="excludeLogistics">去除物流</a-checkbox>
              <a-checkbox value="excludeNVL">去除NVL</a-checkbox>
            </a-checkbox-group>
          </div>
        </a-col>
      </a-row>

      <!-- 额外搜索框 -->
      <div v-if="showAdvancedSearch">
        <a-row :gutter="16">
          <a-col :span="6">
            <a-form-item label="重量范围" labelAlign="left">
              <a-input-group compact>
                <a-input style="width: 50%" v-model:value="form.weightMin" placeholder="最小值" />
                <a-input style="width: 50%" v-model:value="form.weightMax" placeholder="最大值" />
              </a-input-group>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="数量范围" labelAlign="left">
              <a-input-group compact>
                <a-input style="width: 50%" v-model:value="form.quantityMin" placeholder="最小值" />
                <a-input style="width: 50%" v-model:value="form.quantityMax" placeholder="最大值" />
              </a-input-group>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="金额范围" labelAlign="left">
              <a-input-group compact>
                <a-input style="width: 50%" v-model:value="form.amountMin" placeholder="最小值" />
                <a-input style="width: 50%" v-model:value="form.amountMax" placeholder="最大值" />
              </a-input-group>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="TEU范围" labelAlign="left">
              <a-input-group compact>
                <a-input style="width: 50%" v-model:value="form.teuMin" placeholder="最小值" />
                <a-input style="width: 50%" v-model:value="form.teuMax" placeholder="最大值" />
              </a-input-group>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="6">
            <a-form-item label="原产国" labelAlign="left">
              <a-select
                v-model:value="form.originCountry"
                mode="multiple"
                placeholder="原产国"
                :options="countryOptions"
                :filterOption="filterCountryOption"
                showSearch
              />
            </a-form-item>
          </a-col>
          <!-- <a-col :span="6">
            <a-form-item label="起运港" labelAlign="left">
              <a-input v-model:value="form.origPort" placeholder="起运港" />
            </a-form-item>
          </a-col> -->
          <a-col :span="6">
            <a-form-item label="目的国" labelAlign="left">
              <a-select
                v-model:value="form.destinationCountry"
                mode="multiple"
                placeholder="目的国"
                :options="countryOptions"
                :filterOption="filterCountryOption"
                showSearch
              />
            </a-form-item>
          </a-col>
          <!-- <a-col :span="6">
            <a-form-item label="目的港" labelAlign="left">
              <a-input v-model:value="form.destPort" placeholder="目的港" />
            </a-form-item>
          </a-col> -->
        </a-row>
        <a-row :gutter="16">
          <!-- <a-col :span="6">
            <a-form-item label="海关" labelAlign="left">
              <a-input v-model:value="form.customs" placeholder="海关" />
            </a-form-item>
          </a-col> -->
          <!-- <a-col :span="6">
            <a-form-item label="运输方式" labelAlign="left">
              <a-input v-model:value="form.transportMode" placeholder="运输方式" />
            </a-form-item>
          </a-col> -->
          <!-- <a-col :span="6">
            <a-form-item label="成交方式" labelAlign="left">
              <a-input v-model:value="form.incoterms" placeholder="成交方式" />
            </a-form-item>
          </a-col> -->
          <a-col :span="6">
            <a-form-item label="主单号" labelAlign="left">
              <a-input v-model:value="form.mainOrderNo" placeholder="主单号" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="6">
            <a-form-item label="分单号" labelAlign="left">
              <a-input v-model:value="form.subOrderNo" placeholder="分单号" />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="集装箱号" labelAlign="left">
              <a-input v-model:value="form.containerNo" placeholder="集装箱号" />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="承运人" labelAlign="left">
              <a-input v-model:value="form.carrier" placeholder="承运人" />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="船名" labelAlign="left">
              <a-input v-model:value="form.shipName" placeholder="船名" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="6">
            <a-form-item label="商标" labelAlign="left">
              <a-input v-model:value="form.brand" placeholder="商标" />
            </a-form-item>
          </a-col>
          <a-col :span="18">
            <a-form-item label="其他" labelAlign="left">
              <a-input v-model:value="form.other" placeholder="其他" />
            </a-form-item>
          </a-col>
        </a-row>
      </div>

      <!-- 更多搜索按钮 -->
      <a-row :gutter="16" style="margin-top: 16px">
        <a-col :span="6">
          <a-button @click="toggleAdvancedSearch">
            {{ showAdvancedSearch ? '收起' : '更多搜索' }}
          </a-button>
        </a-col>
      </a-row>

      <!-- 按钮行 -->
      <a-row class="button-row" justify="space-between">
        <a-col :span="12">
          <a-button @click="handleDataSourceClick">数据源</a-button>
        </a-col>
        <a-col :span="12" style="text-align: right">
          <a-button type="primary" @click="handleSearch">搜索</a-button>
        </a-col>
      </a-row>
    </div>
  </div>

  <!-- 使用 v-show 控制数据展示区域的显示/隐藏 -->
  <div v-show="showDataContent" class="table-container">
    <a-tabs v-model:activeKey="activeTabKey" @change="handleTabChange" class="custom-tabs" type="card">
      <a-tab-pane key="transaction" tab="交易信息">
        <a-card title="交易信息">
          <template #extra>
            <span>排序：</span>
            <a-radio-group v-model:value="sortMode" button-style="solid" style="margin-left: 16px;"
              @change="handleSortChange">
              <a-radio-button value="date">交易日期</a-radio-button>
              <a-radio-button value="weight">交易重量</a-radio-button>
            </a-radio-group>
          </template>
          <a-table :columns="columns" :data-source="tableData" :loading="loading" :pagination="{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            pageSizeOptions: ['10', '20', '30', '40', '50'],
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            onChange: handleTableChange,
            onShowSizeChange: handleTableChange,
          }" @change="handleTableChange">

            <template #bodyCell="{ column, record, text }">
              <template v-if="column.key === 'supplier_t'">
                <a @click="handleSupplierClick(record.supplier_id)">{{ text }}</a>
              </template>
              <template v-if="column.key === 'buyer_t'">
                <a @click="handleBuyerClick(record.buyer_id)">{{ text }}</a>
              </template>
              <template v-if="column.key === 'freight_intro'">
                <a @click="handleFreightIntroClick(record)">详细信息</a>
              </template>
            </template>
          </a-table>
        </a-card>

        <div :inert="isModalVisible">
          <!-- 其他内容 -->
          <a-modal v-model:open="isModalVisible" title="企业详情" :width="1200" @close="closeModal">
            <div>
              <div v-if="supplier">
                <h1>{{ supplier.name }}</h1> <!-- 添加企业名称 -->
                <p><strong>地址:</strong> {{ supplier.address }}</p> <!-- 添加企业地址 -->
                <p v-if="supplier.postal_code || supplier.phone || supplier.email">
                  <strong>联系方式:</strong>
                  <span v-if="supplier.postal_code" class="contact-info">postal code: {{ supplier.postal_code[0]
                    }}</span>
                  <span v-if="supplier.phone" class="contact-info">phone: {{ supplier.phone[0] }}</span>
                  <span v-if="supplier.email" class="contact-info">email: {{ supplier.email[0] }}</span>
                </p>
              </div>
            </div>
            <!-- 选项卡 -->
            <a-tabs v-model:activeKey="activeTabKey1" @change="handleTabChange1" type="card">
              <a-tab-pane key="tradeOverview" tab="贸易总览">
                <!-- 贸易总览内容 -->
                <div class="analysis-content">
                  <div class="analysis-item">
                    <FreightHistory :data="freightHistoryData" />
                  </div>
                  <div class="analysis-item">
                    <CompanyProduct :queryParam="queryParam" :comId="selectedComId" />
                  </div>
                  <div class="analysis-item">
                    <TradePartners :queryParam="queryParam" :comId="selectedComId" />
                  </div>
                  <div class="analysis-item">
                    <RegionDistribution :queryParam="queryParam" :comId="selectedComId" />
                  </div>
                </div>
              </a-tab-pane>
              <a-tab-pane key="importDetails" tab="进口详单">
                <!-- 新增表格展示进口详单 -->
                <a-table :columns="importDetailsColumns" :data-source="importDetailsData" :loading="loading"
                  :pagination="{
                    current: paginationImportDetails.current,
                    pageSize: paginationImportDetails.pageSize,
                    total: paginationImportDetails.total,
                    showSizeChanger: true,
                    showQuickJumper: true,
                    showTotal: (total) => `共 ${total} 条`,
                    onChange: handleTableChangeImportDetails,
                  }" />
              </a-tab-pane>
              <a-tab-pane key="exportDetails" tab="出口详单">
                <a-table :columns="exportDetailsColumns" :data-source="exportDetailsData" :loading="loading"
                  :pagination="{
                    current: paginationExportDetails.current,
                    pageSize: paginationExportDetails.pageSize,
                    total: paginationExportDetails.total,
                    showSizeChanger: true,
                    showQuickJumper: true,
                    showTotal: (total) => `共 ${total} 条`,
                    onChange: handleTableChangeExportDetails,
                  }" />
              </a-tab-pane>
            </a-tabs>
          </a-modal>
        </div>
      </a-tab-pane>

      <a-tab-pane key="companies" tab="企业列表">
        <company-list :queryParam="queryParam" />
      </a-tab-pane>

      <a-tab-pane key="tradeAnalysis" tab="贸易类分析报告">
        <div class="analysis-content">
          <div class="analysis-item">
            <trade-analysis :monthly-trend-data="monthlyTrendData" />
          </div>
          <div class="analysis-item">
            <HsCodeAnalysis :queryParam="queryParam" />
          </div>
          <a-row :gutter="16">
            <!-- 新增行 -->
            <a-col :span="12">
              <!-- 左侧列 -->
              <div class="analysis-item">
                <OriginCountryAnalysis :queryParam="queryParam" />
              </div>
            </a-col>
            <a-col :span="12">
              <!-- 右侧列 -->
              <div class="analysis-item">
                <DestinationCountryAnalysis :queryParam="queryParam" />
              </div>
            </a-col>
          </a-row>
          <div class="analysis-item">
            <SupplierList :queryParam="queryParam" />
          </div>
          <div class="analysis-item">
            <BuyerList :queryParam="queryParam" />
          </div>
        </div>
      </a-tab-pane>

      <a-tab-pane key="shippingAnalysis" tab="航运类分析报告">
        <div class="analysis-content">
          <div class="analysis-item">
            <OrigPortAnalysis :queryParam="queryParam"></OrigPortAnalysis>
          </div>
          <div class="analysis-item">
            <DestPortAnalysis :queryParam="queryParam"></DestPortAnalysis>
          </div>

          <div class="analysis-item">
            <TransTypeAnalysis :queryParam="queryParam"></TransTypeAnalysis>
          </div>

          <div class="analysis-item">
            <IncotermsAnalysis :queryParam="queryParam"></IncotermsAnalysis>
          </div>
        </div>
      </a-tab-pane>
    </a-tabs>
  </div>

  <a-modal v-model:open="isFreightIntroModalVisible" title="货运介绍" :width="1200"
    @close="isFreightIntroModalVisible = false">
    <div class="freight-intro">
      <a-row gutter="16">
        <a-col :span="12">
          <span class="label">日期</span>
          <span>{{ freightIntroData.date }}</span>
        </a-col>
        <a-col :span="12">
          <span class="label">主单号</span>
          <span>{{ freightIntroData.master_bill_no }}</span>
        </a-col>
      </a-row>
      <a-divider />
      <a-row gutter="16">
        <a-col :span="12">
          <span class="title">供应商</span>
          <h3>{{ freightIntroData.supplier_t }}</h3>
          <p>{{ freightIntroData.supplier_addr }}</p>
        </a-col>
        <a-col :span="12">
          <span class="title">采购商</span>
          <h3>{{ freightIntroData.buyer_t }}</h3>
          <p>{{ freightIntroData.buyer_addr }}</p>
          <span class="title">通知人</span>
          <h3>{{ freightIntroData.others?.notify }}</h3>
          <p>{{ freightIntroData.others?.notify_info }}</p>
        </a-col>
      </a-row>
      <a-divider />
      <a-row gutter="16">
        <a-col :span="24">
          <span class="title">产品信息</span>
          <a-row>
            <a-col :span="12">
              <p><span class="label">数量</span> {{ freightIntroData.quantity }}</p>
            </a-col>
            <a-col :span="12">
              <p><span class="label">重量</span> {{ freightIntroData.weight }}</p>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <p><span class="label">TEU</span> {{ freightIntroData.teu }}</p>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="24">
              <span class="label">产品描述</span>
              <span>{{ freightIntroData.prod_desc }}</span>
            </a-col>
          </a-row>
        </a-col>
      </a-row>
      <a-divider />
      <a-row gutter="16">
        <span class="title">货运信息</span>
        <a-col :span="24">
          <a-row>
            <a-col :span="12">
              <span class="label">原产国</span>
              <span>{{ freightIntroData.orig_country_cn }}</span>
            </a-col>
            <a-col :span="12">
              <span class="label">起运港</span>
              <span>{{ freightIntroData.orig_port }}</span>
            </a-col>
            <a-col :span="12">
              <span class="label">目的国</span>
              <span>{{ freightIntroData.dest_country_cn }}</span>
            </a-col>
            <a-col :span="12">
              <span class="label">目的港</span>
              <span>{{ freightIntroData.dest_port }}</span>
            </a-col>
            <a-col :span="12">
              <span class="label">承运人</span>
              <span>{{ freightIntroData.carrier_name }}</span>
            </a-col>
            <a-col :span="12">
              <span class="label">船名</span>
              <span>{{ freightIntroData.vessel_name }}</span>
            </a-col>
            <a-col :span="24">
              <span class="label">运输方式</span>
              <span>{{ freightIntroData.trans_type }}</span>
            </a-col>
            <a-col :span="24">
              <span class="label">集装箱号</span>
              <span>{{ freightIntroData.container_no }}</span>
            </a-col>
          </a-row>

        </a-col>
      </a-row>
      <a-divider />
      <a-row gutter="16">
        <span class="title">更多详情</span>
        <a-col :span="24">
          <a-row>
            <a-col v-if="freightIntroData.others?.updateDate" :span="12">
              <span class="label">Update Date</span>
              <span>{{ freightIntroData.others.updateDate }}</span>
            </a-col>
            <a-col v-if="freightIntroData.others?.runDate" :span="12">
              <span class="label">Run Date</span>
              <span>{{ freightIntroData.others.runDate }}</span>
            </a-col>
            <a-col v-if="freightIntroData.others?.vesselCountry" :span="12">
              <span class="label">Vessel Country</span>
              <span>{{ freightIntroData.others.vesselCountry }}</span>
            </a-col>
            <a-col v-if="freightIntroData.others?.billType" :span="12">
              <span class="label">Bill Type</span>
              <span>{{ freightIntroData.others.billType }}</span>
            </a-col>
            <a-col v-if="freightIntroData.others?.manifestNumber" :span="12">
              <span class="label">Manifest Number</span>
              <span>{{ freightIntroData.others.manifestNumber }}</span>
            </a-col>
            <a-col v-if="freightIntroData.others?.measurement" :span="12">
              <span class="label">Measurement</span>
              <span>{{ freightIntroData.others.measurement }}</span>
            </a-col>
            <a-col v-if="freightIntroData.others?.recordStatus" :span="12">
              <span class="label">Record Status</span>
              <span>{{ freightIntroData.others.recordStatus }}</span>
            </a-col>
            <a-col v-if="freightIntroData.others?.voyageNumber" :span="12">
              <span class="label">Voyage Number</span>
              <span>{{ freightIntroData.others.voyageNumber }}</span>
            </a-col>
            <a-col v-if="conveyanceData" :span="12">
              <span class="label">Imo Number Lloyds Number</span>
              <span>{{ conveyanceData }}</span>
            </a-col>
            <a-col v-if="freightIntroData.others?.secondaryNotify" :span="12">
              <span class="label">Secondary Notify</span>
              <span>{{ freightIntroData.others.secondaryNotify }}</span>
            </a-col>
            <a-col v-if="freightIntroData.others?.estimatedArrivalDate" :span="12">
              <span class="label">Estimated Arrival Date</span>
              <span>{{ freightIntroData.others.estimatedArrivalDate }}</span>
            </a-col>
            <a-col v-if="freightIntroData.others?.PlaceOfReceipt" :span="12">
              <span class="label">Place Of Receipt</span>
              <span>{{ freightIntroData.others.PlaceOfReceipt }}</span>
            </a-col>
            <a-col :span="12">
              <span class="label">数据来源</span>
              <span>暂定</span>
            </a-col>
          </a-row>
        </a-col>
      </a-row>
      <a-row gutter="16">
        <span class="title">集装箱详情</span>
        <a-col :span="24">
          <a-row>
            <a-col :span="12" v-for="container in freightIntroData.others?.containers" :key="container.containerNumber">
              <a-card :title="container.containerNumber">
                <p><span class="label">Service Type:</span> {{ container.serviceType }}</p>
                <p><span class="label">Piece Count:</span> {{ container.pieceCount }}</p>
                <p><span class="label">Description Code:</span> {{ container.descriptionCode }}</p>
                <p><span class="label">Container Number:</span> {{ container.containerNumber }}</p>
                <p><span class="label">Load Status:</span> {{ container.loadStatus }}</p>
                <p><span class="label">Seal Number:</span> {{ container.sealNumber }}</p>
                <p><span class="label">Length:</span> {{ container.length }}</p>
                <p><span class="label">Width:</span> {{ container.width }}</p>
                <p><span class="label">Marks:</span> {{ container.marks || 'NO MARKS'}}</p>
                <p><span class="label">Type Code:</span> {{ container.typeCode }}</p>
                <p><span class="label">Height:</span> {{ container.height }}</p>
              </a-card>
            </a-col>
          </a-row>
        </a-col>
      </a-row>
    </div>
  </a-modal>

  <!-- 数据源选择弹窗 -->
  <a-modal v-model:open="isDataSourceVisible" title="数据源选择" width="800px">
    <a-row :gutter="24">
      <!-- 进口国家列 -->
      <a-col :span="12">
        <div class="data-source-column">
          <div class="column-header">
            <h4>进口数据源</h4>
            <a-checkbox 
              v-model:checked="allImportSelected"
              :indeterminate="isImportIndeterminate"
              @change="handleImportSelectAll"
            >
              全选
            </a-checkbox>
          </div>
          <a-checkbox-group v-model:value="selectedImport">
            <a-checkbox v-for="(sourceCode, displayName) in importCountries" :key="sourceCode" :value="sourceCode">
              {{ displayName }}
            </a-checkbox>
          </a-checkbox-group>
        </div>
      </a-col>
      
      <!-- 出口国家列 -->
      <a-col :span="12">
        <div class="data-source-column">
          <div class="column-header">
            <h4>出口数据源</h4>
            <a-checkbox 
              v-model:checked="allExportSelected"
              :indeterminate="isExportIndeterminate"
              @change="handleExportSelectAll"
            >
              全选
            </a-checkbox>
          </div>
          <a-checkbox-group v-model:value="selectedExport">
            <a-checkbox v-for="(sourceCode, displayName) in exportCountries" :key="sourceCode" :value="sourceCode">
              {{ displayName }}
            </a-checkbox>
          </a-checkbox-group>
        </div>
      </a-col>
    </a-row>
    
    <template #footer>
      <a-button @click="handleDataSourceCancel">取消</a-button>
      <a-button type="primary" @click="handleDataSourceConfirm">确定</a-button>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, computed } from 'vue';
import dayjs from 'dayjs';
import { useMessage } from '@/hooks/web/useMessage';
import {
  list,
  getTrendReport,
  getCompanyInfo,
  getMonthly,
  getCompanyRecord
} from './customsData.api';
import { columns } from './customsData.data';
import CompanyList from './components/CompanyList.vue';
import TradeAnalysis from './components/TradeAnalysis.vue';
import HsCodeAnalysis from './components/HsCodeAnalysis.vue';
import OriginCountryAnalysis from './components/OriginCountryAnalysis.vue';
import DestinationCountryAnalysis from './components/DestinationCountryAnalysis.vue';
import SupplierList from './components/SupplierList.vue';
import BuyerList from './components/BuyerList.vue';
import OrigPortAnalysis from './components/OrigPortAnalysis.vue';
import DestPortAnalysis from './components/DestPortAnalysis.vue';
import TransTypeAnalysis from './components/TransTypeAnalysis.vue';
import IncotermsAnalysis from './components/IncotermsAnalysis.vue';
import FreightHistory from './components/FreightHistory.vue';
import TradePartners from './components/TradePartners.vue';
import RegionDistribution from './components/RegionDistribution.vue';
import CompanyProduct from './components/CompanyProduct.vue';

const { createMessage } = useMessage();

const supplier = ref<{ name: string; address: string; postal_code: string; phone: string; email: string } | null>(null);

// 当前激活的标签页
const activeTabKey = ref('transaction');

// 查询参数
const queryParam = reactive<any>({});

const form = ref({
  product: '',
  hsCode: '',
  startDate: dayjs().subtract(1, 'year'), // Set start date to one year ago
  endDate: dayjs(), // Set end date to today
  supplier: '',
  // supplierReg: '',
  supplierAddress: '',
  options: ['excludeNVL'],
  buyer: '',
  // buyerReg: '',
  buyerAddress: '',
  buyerOptions: ['excludeNVL'],
  originCountry: [] as string[],
  destinationCountry: [] as string[],
  port: '',
  transportMode: '',
  weightMin: null,
  weightMax: null,
  quantityMin: null,
  quantityMax: null,
  amountMin: null,
  amountMax: null,
  teuMin: null,
  teuMax: null,
  origPort: '',
  destPort: '',
  customs: '',
  incoterms: '',
  mainOrderNo: '',
  subOrderNo: '',
  containerNo: '',
  carrier: '',
  shipName: '',
  brand: '',
  other: '',
});

// 添加控制数据展示的状态
const showDataContent = ref(false);

// 添加 country options (you can populate this with actual country data)
const countryOptions = ref([
  { value: 'CN', label: '中国' },
  { value: 'IN', label: '印度' },
  { value: 'VN', label: '越南' },
  { value: 'US', label: '美国' },
  { value: 'MX', label: '墨西哥' },
  { value: 'RU', label: '俄罗斯' },
  { value: 'DE', label: '德国' },
  { value: 'JP', label: '日本' },
  { value: 'TR', label: '土耳其' },
  { value: 'KR', label: '韩国' },
  { value: 'ID', label: '印度尼西亚' },
  { value: 'IT', label: '意大利' },
  { value: 'TW', label: '中国台湾' },
  { value: 'HK', label: '中国香港' },
  { value: 'SG', label: '新加坡' },
  { value: 'TH', label: '泰国' },
  { value: 'GB', label: '英国' },
  { value: 'ES', label: '西班牙' },
  { value: 'BR', label: '巴西' },
  { value: 'FR', label: '法国' },
  { value: 'EC', label: '厄瓜多尔' },
  { value: 'BE', label: '比利时' },
  { value: 'CO', label: '哥伦比亚' },
  { value: 'MY', label: '马来西亚' },
  { value: 'BD', label: '孟加拉国' },
  { value: 'PL', label: '波兰' },
  { value: 'ZA', label: '南非' },
  { value: 'NL', label: '荷兰' },
  { value: 'AR', label: '阿根廷' },
  { value: 'PE', label: '秘鲁' },
  { value: 'CL', label: '智利' },
  { value: 'CH', label: '瑞士' },
  { value: 'PK', label: '巴基斯坦' },
  { value: 'PH', label: '菲律宾' },
  { value: 'UA', label: '乌克兰' },
  { value: 'PA', label: '巴拿马' },
  { value: 'CZ', label: '捷克' },
  { value: 'LK', label: '斯里兰卡' },
  { value: 'SE', label: '瑞典' },
  { value: 'CA', label: '加拿大' },
  { value: 'KZ', label: '哈萨克斯坦' },
  { value: 'CR', label: '哥斯达黎加' },
  { value: 'AT', label: '奥地利' },
  { value: 'AE', label: '阿联酋' },
  { value: 'PT', label: '葡萄牙' },
  { value: 'LT', label: '立陶宛' },
  { value: 'HU', label: '匈牙利' },
  { value: 'RO', label: '罗马尼亚' },
  { value: 'AU', label: '澳大利亚' },
  { value: 'DK', label: '丹麦' },
  { value: 'UZ', label: '乌兹别克斯坦' },
  { value: 'GT', label: '危地马拉' },
  { value: 'FI', label: '芬兰' },
  { value: 'IL', label: '以色列' },
  { value: 'UY', label: '乌拉圭' },
  { value: 'KH', label: '柬埔寨' },
  { value: 'MA', label: '摩洛哥' },
  { value: 'BY', label: '白俄罗斯' },
  { value: 'SK', label: '斯洛伐克' },
  { value: 'IE', label: '爱尔兰' },
  { value: 'PY', label: '巴拉圭' },
  { value: 'EG', label: '埃及' },
  { value: 'HN', label: '洪都拉斯' },
  { value: 'BG', label: '保加利亚' },
  { value: 'MO', label: '中国澳门' },
  { value: 'MD', label: '摩尔多瓦' },
  { value: 'SA', label: '沙特阿拉伯' },
  { value: 'NZ', label: '新西兰' },
  { value: 'SI', label: '斯洛文尼亚' },
  { value: 'UG', label: '乌干达' },
  { value: 'DO', label: '多米尼加' },
  { value: 'GR', label: '希腊' },
  { value: 'ET', label: '埃塞俄比亚' },
  { value: 'SV', label: '萨尔瓦多' },
  { value: 'MM', label: '缅甸' },
  { value: 'KE', label: '肯尼亚' },
  { value: 'OM', label: '阿曼' },
  { value: 'BS', label: '巴哈马' },
  { value: 'LV', label: '拉脱维亚' },
  { value: 'RS', label: '塞尔维亚' },
  { value: 'TN', label: '突尼斯' },
  { value: 'EE', label: '爱沙尼亚' },
  { value: 'BZ', label: '伯利兹' },
  { value: 'NI', label: '尼加拉瓜' },
  { value: 'CI', label: '科特迪瓦' },
  { value: 'VG', label: '英属维尔京群岛' },
  { value: 'IR', label: '伊朗' },
  { value: 'NO', label: '挪威' },
  { value: 'JM', label: '牙买加' },
  { value: 'WS', label: '萨摩亚' },
  { value: 'TZ', label: '坦桑尼亚' },
  { value: 'LU', label: '卢森堡' },
  { value: 'NP', label: '尼泊尔' },
  { value: 'SC', label: '塞舌尔' },
  { value: 'AZ', label: '阿塞拜疆' },
  { value: 'HR', label: '克罗地亚' },
  { value: 'LI', label: '列支敦士登' },
  { value: 'BW', label: '博茨瓦纳' },
  { value: 'HT', label: '海地' },
  { value: 'GE', label: '格鲁吉亚' }
]);

// 修改 handleSearch 方法
const handleSearch = async () => {
  // 清空 queryParam
  Object.keys(queryParam).forEach((key) => {
    delete queryParam[key];
  });
  
  showDataContent.value = true;

  // 构建查询参数
  const params = {
    source_type: 1,
    // 动态获取数据源
    data_source: [...selectedImport.value, ...selectedExport.value],
    // 表单参数
    prod_desc: form.value.product,
    hs_code: form.value.hsCode,
    supplier_t: form.value.supplier,
    // supplier_reg: form.value.supplierReg,
    supplier_addr: form.value.supplierAddress,
    buyer_t: form.value.buyer,
    // buyer_reg: form.value.buyerReg,
    buyer_addr: form.value.buyerAddress,
    orig_country_code: form.value.originCountry.length > 0 ? form.value.originCountry : undefined,
    dest_country_code: form.value.destinationCountry.length > 0 ? form.value.destinationCountry : undefined,
    // orig_port_t: form.value.origPort,
    // dest_port_t: form.value.destPort,
    // customs: form.value.customs,
    transport_mode: form.value.transportMode,
    incoterms: form.value.incoterms,
    master_bill_no: form.value.mainOrderNo,
    sub_bill_no: form.value.subOrderNo,
    container_no: form.value.containerNo,
    carrier_name: form.value.carrier,
    vessel_name: form.value.shipName,
    brand: form.value.brand,
    others: form.value.other,

    // 日期处理
    date: form.value.startDate && form.value.endDate ? [form.value.startDate.format('YYYYMMDD'), form.value.endDate.format('YYYYMMDD')] : undefined,

    // 范围值处理
    weight: form.value.weightMin || form.value.weightMax ? handleRangeValue(form.value.weightMin, form.value.weightMax) : undefined,
    quantity: form.value.quantityMin || form.value.quantityMax ? handleRangeValue(form.value.quantityMin, form.value.quantityMax) : undefined,
    amount: form.value.amountMin || form.value.amountMax ? handleRangeValue(form.value.amountMin, form.value.amountMax) : undefined,
    teu: form.value.teuMin || form.value.teuMax ? handleRangeValue(form.value.teuMin, form.value.teuMax) : undefined,

    // 选项处理
    supplier_ex_log: form.value.options?.includes('excludeLogistics'),
    supplier_ex_nvl: form.value.options?.includes('excludeNVL'),
    buyer_ex_log: form.value.buyerOptions?.includes('excludeLogistics'),
    buyer_ex_nvl: form.value.buyerOptions?.includes('excludeNVL'),
  };

  // 清除空值参数
  Object.keys(params).forEach((key) => {
    const value = params[key];
    if (value === undefined || value === null || value === '') {
      delete params[key];
    } else if (Array.isArray(value)) {
      // 处理数组类型的参数
      if (value.length === 0 || value.every(item => item === '' || item === null || item === undefined)) {
        delete params[key];
      } else {
        // 过滤掉数组中的空值
        params[key] = value.filter(item => item !== '' && item !== null && item !== undefined);
      }
    } else if (typeof value === 'object') {
      // 处理对象类型的参数
      if (Object.keys(value).length === 0) {
        delete params[key];
      }
    }
  });

  // 将参数保存到 queryParam 以供其他地方使用
  Object.assign(queryParam, params);
  
  if (activeTabKey.value === 'transaction') {
    pagination.value.current = 1; // Reset to first page
    await handleTableChange(pagination.value);
  } else if (activeTabKey.value === 'companies') {
    await handleTabChange('companies'); // Load companies data
  } else if (activeTabKey.value === 'tradeAnalysis') {
    await handleTabChange('tradeAnalysis'); // Load trade analysis data
  } else if (activeTabKey.value === 'shippingAnalysis') {
    await handleTabChange('shippingAnalysis'); // Load shipping analysis data
  }
};

// 修改 handleRangeValue 函数
const handleRangeValue = (min: string | null, max: string | null) => {
  if (min || max) {
    return [min || '*', max || '*'];
  }
  return undefined;
};

const showAdvancedSearch = ref(false);

const toggleAdvancedSearch = () => {
  showAdvancedSearch.value = !showAdvancedSearch.value;
};

// 修改 onMounted，不再自动加载数据
onMounted(() => {
  Object.assign(queryParam, {
    source_type: 1,
    data_source: [...selectedImport.value, ...selectedExport.value], // 初始使用全选数据源
  });
});

// Add these new variables
const tableData = ref([]);
const loading = ref(false);
const pagination = ref({
  current: 1,
  pageSize: 50,
  total: 0,
});

// Replace registerTransactionTable with this new method
const handleTableChange = async (pag, filters, sorter) => {
  loading.value = true;
  try {
    const params = {
      sort: sortMode.value,
      page: pag.current,
      page_size: pag.pageSize,
      ...queryParam,
    };

    const res = await list(params);
    if (res.code != 200) {
      createMessage.error(res.message);
    } else if (res.result.data.result && res.result.data.result.docs) {
      // 处理日期格式
      tableData.value = res.result.data.result.docs.map((item) => ({
        ...item,
        date: item.date ? item.date.split(' ')[0] : '', // 只保留日期部分
      }));
      pagination.value = {
        current: pag.current,
        pageSize: pag.pageSize,
        total: res.result.data.result.numFound || 0,
      };
    }
  } catch (error) {
    console.error('Failed to fetch data:', error);
  } finally {
    loading.value = false;
  }
};

// 企业列表数据
const companiesData = ref([]);

// 处理企业列表数据
const handleCompaniesData = (companies) => {
  companiesData.value = companies.map((company) => ({
    name: company.name,
    totalRecords: company.total_records,
    matchedRecords: company.matched_records,
    address: company.address,
    phone: company.phone,
    email: company.email,
  }));
};

// Consolidate handleTabChange function
const handleTabChange = async (key: string) => {
  activeTabKey.value = key;
  if (key === 'companies') {
   
  } else if (key === 'tradeAnalysis') {
    // Load trade analysis data
    await Promise.all([
      loadMonthlyTrendData(),
    ]);
  } else if (key === 'shippingAnalysis') {

  }
};

// 月度趋势分析数据
const monthlyTrendData = ref([]);

// 加载月度趋势分析数据
const loadMonthlyTrendData = async () => {
  try {
    const params = {
      ...queryParam,
    };

    const res = await getTrendReport(params);
    if (res.result.data.result && res.result.data.result) {
      // 处理日期格式
      monthlyTrendData.value = res.result.data.result.map((item) => ({
        ...item,
      }));
    }
  } catch (error) {
    console.error('Failed to fetch data:', error);
  } finally {
    loading.value = false;
  }
};

const isModalVisible = ref(false);

// Add a new ref to store the selected supplierId
const selectedComId = ref<string | null>(null);

// Modify the handleSupplierClick function to set the selectedComId
const handleSupplierClick = async (supplierId) => {
  loading.value = true;
  selectedComId.value = supplierId; // Set the selected comId
  const params = {
    com_id: supplierId,
    com_role: 2,
    ...queryParam,
  };
  const response = await getCompanyInfo(params);
  supplier.value = {
    ...response.result.data.result,
    postal_code: response.result.data.result.postal_code ? response.result.data.result.postal_code.join(',') : ''
  };
  loading.value = false;
  isModalVisible.value = true;
  activeTabKey1.value = 'tradeOverview';
  await loadFreightHistoryData();
};

// Add a new ref for controlling the modal visibility
const isFreightIntroModalVisible = ref(false);
const freightIntroData = ref({
  others: {
    conveyance: 'SomePrefix:DesiredData'
  }
});

// Computed property to extract data after ':'
const conveyanceData = computed(() => {
  const conveyance = freightIntroData.value.others?.conveyance || '';
  return conveyance.includes(':') ? conveyance.split(':')[1].trim() : conveyance;
});

// Modify the handleFreightIntroClick function
const handleFreightIntroClick = (record) => {
  freightIntroData.value = record;
  isFreightIntroModalVisible.value = true; // Open the modal
};

const handleBuyerClick = async (buyerId) => {
  loading.value = true;
  selectedComId.value = buyerId;
  const params = {
    com_id: buyerId,
    com_role: 1,
    ...queryParam,
  };
  const response = await getCompanyInfo(params);
  supplier.value = {
    ...response.result.data.result,
    postal_code: response.result.data.result.postal_code ? response.result.data.result.postal_code.join(',') : ''
  };
  loading.value = false;
  isModalVisible.value = true;
  activeTabKey1.value = 'tradeOverview';
  await loadFreightHistoryData();
}

const freightHistoryData = ref([]);

// Fetch freight history data for both roles and combine
const loadFreightHistoryData = async () => {
  try {
    const params = {
      com_id: selectedComId.value,
      ...queryParam,
    };

    // Fetch export data (com_role: 2)
    const exportParams = { ...params, com_role: 2 };
    const exportRes = await getMonthly(exportParams);
    const exportData = exportRes?.result?.data?.result?.as_supplier?.monthly?.buckets?.map((item) => ({
      val: item.val,
      num_supplier: item.count,
      num_buyer: 0, // Initialize import count
    })) || [];

    // Fetch import data (com_role: 1)
    const importParams = { ...params, com_role: 1 };
    const importRes = await getMonthly(importParams);
    const importData = importRes?.result?.data?.result?.as_buyer?.monthly?.buckets?.map((item) => ({
      val: item.val,
      num_supplier: 0,
      num_buyer: item.count, // Initialize export count
    })) || [];

    // Combine data by date
    const combinedData = [...exportData, ...importData].reduce((acc, item) => {
      const existing = acc.find((i) => i.val === item.val);
      if (existing) {
        existing.num_supplier += item.num_supplier;
        existing.num_buyer += item.num_buyer;
      } else {
        acc.push(item);
      }
      return acc;
    }, []);

    freightHistoryData.value = combinedData;
  } catch (error) {
    console.error('Failed to fetch freight history data:', error);
  }
};

// Call the function to load data
onMounted(() => {
});

// Current active tab for the modal
const activeTabKey1 = ref('tradeOverview'); // Set default tab key

// Handle tab change for the modal
const handleTabChange1 = async (key: string) => {
  activeTabKey1.value = key;
  if (key === 'tradeOverview') {
    await loadFreightHistoryData(); // Load freight history data
  } else if (key === 'importDetails') {
    await loadImportDetailsData();
  } else if (key === 'exportDetails') {
    await loadExportDetailsData(); // Load export details data
  } else if (key === 'exportTradingPartners') {
    // Load export trading partners data
    console.log('Load export trading partners data');
  } else if (key === 'enterpriseAtlas') {
    // Load enterprise atlas data
    console.log('Load enterprise atlas data');
  }
};

const exportDetailsData = ref([]); // 新增用于存储出口详单数据
const exportDetailsColumns = [ // 新增表格列定义
  {
    title: '供应商',
    dataIndex: 'supplier_t',
    key: 'supplier_t',
  },
  {
    title: '采购商',
    dataIndex: 'buyer_t',
    key: 'buyer_t',
  },
  {
    title: '货运介绍',
    dataIndex: 'freightDescription',
    key: 'freightDescription',
  },
  {
    title: '日期',
    dataIndex: 'date',
    key: 'date',
    sorter: (a, b) => new Date(a.date) - new Date(b.date),
  },
];

const paginationExportDetails = ref({
  current: 1,
  pageSize: 10,
  total: 0,
});

const handleTableChangeExportDetails = async (pag, filters, sorter) => {
  paginationExportDetails.value.current = pag.current; // 更新当前页
  paginationExportDetails.value.pageSize = pag.pageSize; // 更新每页条数
  // 其他处理逻辑...
};

const loadExportDetailsData = async () => { // 新增加载出口详单数据的方法
  loading.value = true;
  try {
    const params = {
      com_id: selectedComId.value,
      com_role: 2,
      ...queryParam,
    };
    const res = await getCompanyRecord(params);
    exportDetailsData.value = res.data.result.as_supplier.response.docs.map((item) => ({
      ...item,
      date: item.date ? item.date.split(' ')[0] : '', // 只保留日期部分
    })); // 存储回的数据
  } catch (error) {
    console.error('Failed to fetch export details:', error);
  } finally {
    loading.value = false;
  }
};

const importDetailsData = ref([]); // 新增用于存储进口详单数据
const importDetailsColumns = [ // 新增表格列定义
  {
    title: '供应商',
    dataIndex: 'supplier_t',
    key: 'supplier_t',
  },
  {
    title: '采购商',
    dataIndex: 'buyer_t',
    key: 'buyer_t',
  },
  {
    title: '货运介绍',
    dataIndex: 'freightDescription',
    key: 'freightDescription',
  },
  {
    title: '日期',
    dataIndex: 'date',
    key: 'date',
    sorter: (a, b) => new Date(a.date) - new Date(b.date),
  },
];

const paginationImportDetails = ref({
  current: 1,
  pageSize: 10,
  total: 0,
});

const handleTableChangeImportDetails = async (pag, filters, sorter) => {
  paginationImportDetails.value.current = pag.current; // 更新当前页
  paginationImportDetails.value.pageSize = pag.pageSize; // 更新每页条数
  // 其他处理逻辑...
};

const loadImportDetailsData = async () => { // 新增加载进口详单数据的方法
  loading.value = true;
  try {
    const params = {
      com_id: selectedComId.value,
      com_role: 1,
      ...queryParam,
    };
    const res = await getCompanyRecord(params);
    importDetailsData.value = res.data.result.as_buyer.response.docs.map((item) => ({
      ...item,
      date: item.date ? item.date.split(' ')[0] : '', // 只保留日期部分
    })); // 存储回的数据
  } catch (error) {
    console.error('Failed to fetch import details:', error);
  } finally {
    loading.value = false;
  }
};

// 修改关闭弹窗的逻辑
const closeModal = () => {
  activeTabKey1.value = 'tradeOverview'
  isModalVisible.value = false; // 关闭弹窗
  resetModalData(); // 重置数据
};

// 添加重置数据的函数
const resetModalData = () => {
  supplier.value = null; // 重置供应商信息
  freightHistoryData.value = []; // 重置货运历史数据
};

const sortMode = ref('date'); // Set default sort mode to 'date'

// Modify handleSortChange to include sort parameter in the API request
const handleSortChange = async (event) => {
  sortMode.value = event.target.value; // Update sort mode
  await handleTableChange(pagination.value)
};

// 新增数据源相关状态
const isDataSourceVisible = ref(false);

// 先定义数据源列表
const importCountries = ref({
  // 美洲地区 (共29条)
  
  '美国提单': 'IMP_AMERICA_BL_SEA',
  '哥斯达黎加关单': 'IMP_COSTARICA_CD_DEF',
  '萨尔瓦多提单': 'IMP_ELSALVADOR_BL_DEF',
  '危地马拉关单': 'IMP_GUATEMALA_CD_DEF',
  '洪都拉斯提单': 'IMP_HONDURAS_BL_DEF',
  '墨西哥关单（海运）': 'IMP_MEXICO_CD_SEA',
  '墨西哥关单（海陆空）': 'IMP_MEXICO_CD_ALL',
  '尼加拉瓜提单': 'IMP_NICARAGUA_BL_DEF',
  '巴拿马关单': 'IMP_PANAMA_CD_DEF',
  '巴拿马关单（自贸区）': 'IMP_PANAMA_CD_ZLC',
  '阿根廷关单': 'IMP_ARGENTINA_CD_DEF',
  '玻利维亚关单': 'IMP_BOLIVIA_CD_DEF',
  '巴西关单': 'IMP_BRAZIL_CD_DEF',
  '智利关单': 'IMP_CHILE_CD_DEF',
  '哥伦比亚提单': 'IMP_COLOMBIA_BL_DEF',
  '哥伦比亚关单': 'IMP_COLOMBIA_CD_DEF',
  '厄瓜多尔提单': 'IMP_ECUADOR_BL_ALL',
  '厄瓜多尔关单': 'IMP_ECUADOR_CD_DEF',
  '厄瓜多尔关单（周更新）': 'IMP_ECUADOR_CD_UDW',
  '巴拉圭关单': 'IMP_PARAGUAY_CD_DEF',
  '秘鲁关单': 'IMP_PERU_CD_DEF',
  '秘鲁提单': 'IMP_PERU_BL_ALL',
  '秘鲁（周更新）': 'IMP_PERU_CD_UDW',
  '乌拉圭提单': 'IMP_URUGUAY_BL_DEF',
  '乌拉圭关单': 'IMP_URUGUAY_CD_DEF',
  '委内瑞拉提单': 'IMP_VENEZUELA_BL_ALL',
  '委内瑞拉关单': 'IMP_VENEZUELA_CD_DEF',
  '巴拿马提单': 'IMP_PANAMA_BL_DEF',
  '阿根廷（半月更新）': 'IMP_ARGENTINA_CD_UDW',

  // 欧洲地区 (8条)
  '英国': 'IMP_ENGLAND_ED_DEF',
  '法国': 'IMP_FRANCE_ED_DEF',
  '德国': 'IMP_GERMANY_ED_DEF',
  '俄罗斯关单': 'IMP_RUSSIA_CD_DEF',
  '乌克兰关单': 'IMP_UKRAINE_CD_DEF',
  '哈萨克斯坦关单': 'IMP_KAZAKHSTAN_CD_DEF',
  '土耳其关单': 'IMP_TURKEY_CD_DEF',
  '摩尔多瓦关单': 'IMP_MOLDOVA_CD_DEF',

  // 亚洲地区 (16条)
  '印度关单': 'IMP_INDIA_CD_DEF',
  '印度（周更新）': 'IMP_INDIA_CD_UDW',
  '日本': 'IMP_JAPAN_ED_DEF',
  '韩国': 'IMP_KOREA_ED_DEF',
  '吉尔吉斯斯坦关单': 'IMP_KYRGYZSTAN_CD_DEF',
  '巴基斯坦提单': 'IMP_PAKISTAN_BL_DEF',
  '巴基斯坦关单': 'IMP_PAKISTAN_CD_DEF',
  '菲律宾关单': 'IMP_PHILIPPINES_CD_DEF',
  '斯里兰卡关单': 'IMP_SRILANKA_CD_DEF',
  '台湾': 'IMP_TAIWAN_ED_DEF',
  '乌兹别克斯坦关单': 'IMP_UZBEKISTAN_CD_DEF',
  '越南双边': 'IMP_VIETNAM_CD_CVB',
  '越南全境（英文）': 'IMP_VIETNAM_CD_AEN',
  '越南全境（越南语）': 'IMP_VIETNAM_CD_AVN',
  '新加坡关单': 'IMP_SINGAPORE_CD_DEF',
  '泰国': 'IMP_THAILAND_ED_DEF',

  // 非洲及其他 (19条)
  '埃塞俄比亚关单': 'IMP_ETHIOPIA_CD_DEF',
  '印度尼西亚关单': 'IMP_INDONESIA_CD_DEF',
  '乌干达关单': 'IMP_UGANDA_CD_DEF',
  '肯尼亚关单': 'IMP_KENYA_CD_DEF',
  '纳米比亚关单': 'IMP_NAMIBIA_CD_DEF',
  '利比里亚关单': 'IMP_LIBERIA_CD_DEF',
  '博茨瓦纳关单': 'IMP_BOTSWANA_CD_DEF',
  '孟加拉国关单': 'IMP_BANGLADESH_CD_DEF',
  '刚果金关单': 'IMP_CONGOKINSHASA_CD_DEF',
  '尼日利亚关单': 'IMP_NIGERIA_CD_DEF',
  '莱索托关单': 'IMP_LESOTHO_CD_DEF',
  '科特迪瓦关单': 'IMP_COTELVORY_CD_DEF',
  '斐济关单': 'IMP_FIJI_CD_DEF',
  '加纳关单': 'IMP_GHANA_CD_DEF',
  '喀麦隆关单': 'IMP_CAMEROON_CD_DEF',
  '乍得关单': 'IMP_CHAD_CD_DEF',
  '中非关单': 'IMP_CENTRALAFRICAN_CD_DEF',
  '津巴布韦关单': 'IMP_ZIMBABWE_CD_DEF',
  '坦桑尼亚关单': 'IMP_TANZANIA_CD_DEF',

  // 特殊数据 (6条)
  '一带一路': 'IMP_SILKWAY_CD_DEF',
  'Global Shipments': 'IMP_GLOBAL_BL_DEF',
  '中美洲边贸（周更新）': 'IMP_CABT_CD_UDW',
  '中美洲边贸（月更新）': 'IMP_CABT_CD_DEF',
  '过境数据': 'IMP_EACROSS_CD_DEF',
  '舱单航运数据': 'IMP_MANIFEST_BL_DEF'
});

const exportCountries = ref({
  // 美洲地区 (23条)
  '美国提单': 'EXP_AMERICA_BL_SEA',
  '哥斯达黎加关单': 'EXP_COSTARICA_CD_DEF',
  '危地马拉关单': 'EXP_GUATEMALA_CD_DEF',
  '巴拿马关单（自贸区）': 'EXP_PANAMA_CD_ZLC',
  '巴拿马关单': 'EXP_PANAMA_CD_DEF',
  '阿根廷关单': 'EXP_ARGENTINA_CD_DEF',
  '阿根廷（半月更新）': 'EXP_ARGENTINA_CD_UDW',
  '巴西关单': 'EXP_BRAZIL_CD_DEF',
  '智利关单': 'EXP_CHILE_CD_DEF',
  '哥伦比亚提单': 'EXP_COLOMBIA_BL_DEF',
  '哥伦比亚关单': 'EXP_COLOMBIA_CD_DEF',
  '厄瓜多尔提单': 'EXP_ECUADOR_BL_ALL',
  '厄瓜多尔关单': 'EXP_ECUADOR_CD_DEF',
  '厄瓜多尔关单（周更新）': 'EXP_ECUADOR_CD_UDW',
  '巴拉圭关单': 'EXP_PARAGUAY_CD_DEF',
  '秘鲁关单': 'EXP_PERU_CD_DEF',
  '秘鲁提单': 'EXP_PERU_BL_ALL',
  '秘鲁（周更新）': 'EXP_PERU_CD_UDW',
  '乌拉圭提单': 'EXP_URUGUAY_BL_DEF',
  '乌拉圭关单': 'EXP_URUGUAY_CD_DEF',
  '委内瑞拉提单': 'EXP_VENEZUELA_BL_ALL',
  '委内瑞拉关单': 'EXP_VENEZUELA_CD_DEF',
  '巴拿马提单': 'EXP_PANAMA_BL_DEF',
  '墨西哥关单（海运）': 'EXP_MEXICO_CD_SEA',
  '墨西哥关单（海陆空）': 'EXP_MEXICO_CD_ALL',

  // 欧洲地区 (6条)
  '英国': 'EXP_ENGLAND_ED_DEF',
  '俄罗斯关单': 'EXP_RUSSIA_CD_DEF',
  '乌克兰关单': 'EXP_UKRAINE_CD_DEF',
  '哈萨克斯坦关单': 'EXP_KAZAKHSTAN_CD_DEF',
  '土耳其关单': 'EXP_TURKEY_CD_DEF',
  '摩尔多瓦关单': 'EXP_MOLDOVA_CD_DEF',

  // 亚洲地区 (11条)
  '印度关单': 'EXP_INDIA_CD_DEF',
  '印度（周更新）': 'EXP_INDIA_CD_UDW',
  '巴基斯坦关单': 'EXP_PAKISTAN_CD_DEF',
  '菲律宾关单': 'EXP_PHILIPPINES_CD_DEF',
  '斯里兰卡关单': 'EXP_SRILANKA_CD_DEF',
  '台湾': 'EXP_TAIWAN_ED_DEF',
  '乌兹别克斯坦关单': 'EXP_UZBEKISTAN_CD_DEF',
  '越南双边': 'EXP_VIETNAM_CD_CVB',
  '越南全境（英文）': 'EXP_VIETNAM_CD_AEN',
  '越南全境（越南语）': 'EXP_VIETNAM_CD_AVN',
  '新加坡关单': 'EXP_SINGAPORE_CD_DEF',

  // 非洲及其他 (15条)
  '埃塞俄比亚关单': 'EXP_ETHIOPIA_CD_DEF',
  '印度尼西亚关单': 'EXP_INDONESIA_CD_DEF',
  '乌干达关单': 'EXP_UGANDA_CD_DEF',
  '纳米比亚关单': 'EXP_NAMIBIA_CD_DEF',
  '利比里亚关单': 'EXP_LIBERIA_CD_DEF',
  '博茨瓦纳关单': 'EXP_BOTSWANA_CD_DEF',
  '孟加拉国关单': 'EXP_BANGLADESH_CD_DEF',
  '刚果金关单': 'EXP_CONGOKINSHASA_CD_DEF',
  '尼日利亚关单': 'EXP_NIGERIA_CD_DEF',
  '莱索托关单': 'EXP_LESOTHO_CD_DEF',
  '科特迪瓦关单': 'EXP_COTELVORY_CD_DEF',
  '斐济关单': 'EXP_FIJI_CD_DEF',
  '喀麦隆关单': 'EXP_CAMEROON_CD_DEF',
  '津巴布韦关单': 'EXP_ZIMBABWE_CD_DEF',
  '坦桑尼亚关单': 'EXP_TANZANIA_CD_DEF'
});

// 然后初始化选中状态
const selectedImport = ref<string[]>(Object.values(importCountries.value));
const selectedExport = ref<string[]>(Object.values(exportCountries.value));

// 数据源按钮点击处理
const handleDataSourceClick = () => {
  isDataSourceVisible.value = true;
};

// 数据源确认处理
const handleDataSourceConfirm = () => {
  // 更新查询参数中的data_source
  queryParam.data_source = [...selectedImport.value, ...selectedExport.value];
  isDataSourceVisible.value = false;
};

// 数据源取消处理
const handleDataSourceCancel = () => {
  isDataSourceVisible.value = false;
  // 可选：重置选择
  selectedImport.value = [];
  selectedExport.value = [];
};

// 新增全选计算属性
const allImportSelected = computed({
  get: () => selectedImport.value.length === Object.values(importCountries.value).length,
  set: (val) => val ? selectedImport.value = Object.values(importCountries.value) : selectedImport.value = []
})

const isImportIndeterminate = computed(() => 
  selectedImport.value.length > 0 && selectedImport.value.length < Object.values(importCountries.value).length
)

const allExportSelected = computed({
  get: () => selectedExport.value.length === Object.values(exportCountries.value).length,
  set: (val) => val ? selectedExport.value = Object.values(exportCountries.value) : selectedExport.value = []
})

const isExportIndeterminate = computed(() => 
  selectedExport.value.length > 0 && selectedExport.value.length < Object.values(exportCountries.value).length
)

// 处理全选操作
const handleImportSelectAll = (e) => {
  selectedImport.value = e.target.checked ? Object.values(importCountries.value) : []
}

const handleExportSelectAll = (e) => {
  selectedExport.value = e.target.checked ? Object.values(exportCountries.value) : []
}

// 新增过滤函数
const filterCountryOption = (input: string, option: { label: string; value: string }) => {
  return option.label.toLowerCase().includes(input.toLowerCase());
};
</script>

<style scoped lang="less">
.search-form {
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 8px;
  margin-bottom: 16px;

  .query-container {
    background-color: #fff;
    padding: 16px;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);

    .ant-row {
      padding: 12px 0;

      &:not(:last-child) {
        border-bottom: 1px solid #e8e8e8;
      }
    }

    .button-row {
      padding: 16px 0 0;
      border-bottom: none !important;
      background-color: transparent !important;
    }

    .checkbox-group {
      display: flex;
      align-items: center;
      height: 100%;
    }
  }
}

// 添加新的样式
.table-container {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px 24px;
  margin: 0 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: opacity 0.3s ease-in-out;

  .custom-tabs {
    :deep(.ant-tabs-nav) {
      margin-bottom: 24px;

      &::before {
        border-bottom: 1px solid #f0f0f0;
      }

      .ant-tabs-tab {
        padding: 12px 24px;
        font-size: 14px;
        transition: all 0.3s;

        &:hover {
          color: @primary-color;
        }

        &.ant-tabs-tab-active {
          .ant-tabs-tab-btn {
            font-weight: 500;
          }
        }
      }

      .ant-tabs-ink-bar {
        height: 3px;
        border-radius: 3px 3px 0 0;
      }
    }

    :deep(.ant-tabs-content) {
      padding: 8px 0;
    }
  }
}

// 分析报告内容样式
.analysis-content {
  background: #fff;

  .analysis-item {
    margin-bottom: 24px; // 添加组件之间的间距

    &:last-child {
      margin-bottom: 0; // 最后一个组件不需要底部间距
    }

    :deep(.ant-card) {
      transition: all 0.3s ease;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

      &:hover {
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
      }
    }
  }
}

// 表格工具栏样式
:deep(.ant-table-wrapper) {
  .ant-table-title {
    padding: 16px 0;
  }
}

// 按钮样式优化
:deep(.ant-btn) {
  height: 32px;
  padding: 0 16px;
  border-radius: 4px;

  &.ant-btn-primary {
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
}

// 表格内容样式优化
:deep(.ant-table) {
  .ant-table-thead>tr>th {
    background: #fafafa;
    font-weight: 500;
  }

  .ant-table-tbody>tr>td {
    transition: background 0.3s;
  }

  .ant-table-tbody>tr:hover>td {
    background: #f5f5f5;
  }
}

// Add these new styles
.table-toolbar {
  margin-bottom: 16px;
  display: flex;
  justify-content: flex-end;
}

.contact-info {
  margin-right: 8px; // Adjust the value as needed for desired spacing
}

.freight-intro {
  .ant-row {
    margin-bottom: 16px;

    h3 {
      font-weight: bold;
      color: #333;
      margin-bottom: 8px;
    }

    p {
      margin: 0;
      color: #555;
    }
  }

  .ant-divider {
    margin: 16px 0;
  }

  .title {
    font-weight: bold;
    color: @primary-color;
    margin-bottom: 15px;
  }

  .label {
    font-weight: bold;
    width: 200px; // Set a fixed width for alignment
    display: inline-block; // Ensure the width is respected
  }
}

.data-source-column {
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  padding: 16px;
  height: 400px;
  overflow-y: auto;

  h4 {
    margin-bottom: 12px;
    color: @primary-color;
  }
  
  :deep(.ant-checkbox-group) {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }
}

.column-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  
  h4 {
    margin: 0;
  }
  
  .ant-checkbox-wrapper {
    margin-left: 8px;
  }
}
</style>
