<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="form.weightMin" placeholder="最小值" />
                <a-input style="width: 50%" v-model="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="form.quantityMin" placeholder="最小值" />
                <a-input style="width: 50%" v-model="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="form.amountMin" placeholder="最小值" />
                <a-input style="width: 50%" v-model="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="form.teuMin" placeholder="最小值" />
                <a-input style="width: 50%" v-model="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-input v-model:value="form.originCountry" placeholder="原产国" />
            </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-input v-model:value="form.destinationCountry" placeholder="目的国" />
            </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="end">
        <a-button type="primary" @click="handleSearch">搜索</a-button>
      </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,
            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()">详细信息</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"><strong>联系方式:</strong> postal code:{{ supplier.postal_code }}</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 :hsCodeData="companyHsCodeData" />
                  </div>
                  <div class="analysis-item">
                    <TradePartners :data="tradePartnersData" />
                  </div>
                  <div class="analysis-item">
                    <RegionDistribution :data="regionDistributionData" />
                  </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 :companies="companiesData" @compare="handleCompareClick" />
      </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 :hs-code-data="hsCodeData" @update:sortMode="handleSortMode" />
          </div>
          <a-row :gutter="16">
            <!-- 新增行 -->
            <a-col :span="12">
              <!-- 左侧列 -->
              <div class="analysis-item">
                <OriginCountryAnalysis :origin-country-data="originCountryData" @update:sortMode="handleSortModeOriginCountryData"  />
              </div>
            </a-col>
            <a-col :span="12">
              <!-- 右侧列 -->
              <div class="analysis-item">
                <DestinationCountryAnalysis :destination-country-data="destinationCountryData" @update:sortMode="handleSortModeDestinationCountryData"/>
              </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 :origPortData="origPortData"></OrigPortAnalysis>
          </div>
          <div class="analysis-item">
            <DestPortAnalysis :destPortData="destPortData"></DestPortAnalysis>
          </div>

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

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

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import dayjs, { Dayjs } from 'dayjs';
import {
  list,
  listCompanies,
  getTrendReport,
  getHsCodeReport,
  getOrigCountryReport,
  getDestCountryReport,
  getSupplierReport,
  getBuyerReport,
  getOrigPortReport,
  getDestPortReport,
  getTransTypeReport,
  getIncotermsReport,
  getCompanyInfo,
  getMonthly,
  getCompanyHsCode,
  getCompanyPartner,
  getRegionDistribution,
  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 supplier = ref<{ name: string; address: string; postal_code: string } | null>(null);

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

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

const form = ref({
  product: '',
  hsCode: '',
  startDate: dayjs('20230101'),//后面更换
  endDate: dayjs('20230630'),//后面更换
  supplier: '',
  supplierReg: '',
  supplierAddress: '',
  options: ['excludeNVL'],
  buyer: '',
  buyerReg: '',
  buyerAddress: '',
  buyerOptions: ['excludeNVL'],
  originCountry: '',
  destinationCountry: '',
  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);

// 修改 handleSearch 方法
const handleSearch = async () => {
  showDataContent.value = true;

  // 构建查询参数
  const params = {
    // 固定参数
    source_type: 1,
    data_source: ['IMP_AMERICA_BL_SEA'],

    // 表单参数
    prod_desc: form.value.product,
    hs_code: form.value.hsCode,
    supplier: form.value.supplier,
    supplier_reg: form.value.supplierReg,
    supplier_address: form.value.supplierAddress,
    buyer: form.value.buyer,
    buyer_reg: form.value.buyerReg,
    buyer_address: form.value.buyerAddress,
    origin_country: form.value.originCountry,
    destination_country: form.value.destinationCountry,
    orig_port: form.value.origPort,
    dest_port: form.value.destPort,
    customs: form.value.customs,
    transport_mode: form.value.transportMode,
    incoterms: form.value.incoterms,
    main_order_no: form.value.mainOrderNo,
    sub_order_no: form.value.subOrderNo,
    container_no: form.value.containerNo,
    carrier: form.value.carrier,
    ship_name: form.value.shipName,
    brand: form.value.brand,

    // 日期处理
    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 ? [form.value.weightMin || '', form.value.weightMax || ''] : undefined,
    quantity: form.value.quantityMin || form.value.quantityMax ? [form.value.quantityMin || '', form.value.quantityMax || ''] : undefined,
    amount: form.value.amountMin || form.value.amountMax ? [form.value.amountMin || '', form.value.amountMax || ''] : undefined,
    teu: form.value.teuMin || form.value.teuMax ? [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'),
  };

  // 移除所有 undefined 和空字符串的属性
  Object.keys(params).forEach((key) => {
    if (params[key] === undefined || params[key] === '') {
      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
  }
};

const showAdvancedSearch = ref(false);

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

// 修改 onMounted，不再自动加载数据
onMounted(() => {
  Object.assign(queryParam, {
    source_type: 1,
    data_source: ['IMP_AMERICA_BL_SEA'],
  });
});

// Add these new variables
const tableData = ref([]);
const loading = ref(false);
const pagination = ref({
  current: 1,
  pageSize: 10,
  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.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,
  }));
};

// 处理对比点击
const handleCompareClick = (company) => {
  console.log('Compare clicked for company:', company.name);
};

// Consolidate handleTabChange function
const handleTabChange = async (key: string) => {
  activeTabKey.value = key;
  if (key === 'companies') {
    try {
      const res = await listCompanies(queryParam);
      if (res.result && res.result.companies) {
        handleCompaniesData(res.result.companies);
      }
    } catch (error) {
      console.error('Failed to fetch companies:', error);
    }
  } else if (key === 'tradeAnalysis') {
    // Load trade analysis data
    await Promise.all([
      loadMonthlyTrendData(),
      fetchHsCodeData(),
      fetchOriginCountryData(),
      fetchDestinationCountryData(),
      fetchBuyerData(),
    ]);
  } else if (key === 'shippingAnalysis') {
    // Load shipping analysis data
    await Promise.all([
      fetchOrigPortData(),
      fetchDestPortData(),
      fetchTransTypeData(),
      fetchIncotermsData()
    ]);
  }
};

// 月度趋势分析数据
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 hsCodeData = ref({});

// 获取HS编码数据
const fetchHsCodeData = async (sortMode = 'count') => {
  const params = {
    ...queryParam,
    sort: sortMode,
  };
  const res = await getHsCodeReport(params);
  hsCodeData.value = res.result.data.result;
};

const originCountryData = ref({});

// 获取原产国数据
const fetchOriginCountryData = async (sortMode = 'count') => {
  const params = {
    ...queryParam,
    sort: sortMode
  };
  const res = await getOrigCountryReport(params);
  originCountryData.value = res.result.data.result;
};

const destinationCountryData = ref({});

// 获取目的国数据
const fetchDestinationCountryData = async (sortMode = 'count') => {
  const params = {
    ...queryParam,
    sort: sortMode
  };
  const res = await getDestCountryReport(params);
  destinationCountryData.value = res.result.data.result;
};

const buyerData = ref({});

// 获取采购商数据
const fetchBuyerData = async () => {
  const params = {
    ...queryParam,
  };
  const res = await getBuyerReport(params);
  buyerData.value = res.result.data.result;
};

const origPortData = ref({});
// 获取起运港数据
const fetchOrigPortData = async () => {
  const params = {
    ...queryParam,
  };
  const res = await getOrigPortReport(params);
  origPortData.value = res.result.data.result;
}

const destPortData = ref({});
// 获取起运港数据
const fetchDestPortData = async () => {
  const params = {
    ...queryParam,
  };
  const res = await getDestPortReport(params);
  destPortData.value = res.result.data.result;
}

const transTypeData = ref({});
// 获取运输方式数据
const fetchTransTypeData = async () => {
  const params = {
    ...queryParam,
  };
  const res = await getTransTypeReport(params);
  transTypeData.value = res.result.data.result;
}

const incotermsData = ref({});
// 获取成交方式数据
const fetchIncotermsData = async () => {
  const params = {
    ...queryParam,
  };
  const res = await getIncotermsReport(params);
  incotermsData.value = res.result.data.result;
}

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();
  await fetchCompanyHsCodeData();
  await fetchTradePartnersData();
  await fetchRegionDistributionData();
};

const handleFreightIntroClick = async () => {

}

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();
  await fetchCompanyHsCodeData();
  await fetchTradePartnersData();
  await fetchRegionDistributionData();
}

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);
  }
};

// 企业HS编码数据
const companyHsCodeData = ref({});

// 获取企业HS编码数据
const fetchCompanyHsCodeData = async () => {
  const params = {
    com_id: selectedComId.value,
    com_role: 2,
    ...queryParam,
  };
  const res = await getCompanyHsCode(params);
  companyHsCodeData.value.as_supplier = res.data.result.as_supplier.hs_code;
  const params1 = {
    com_id: selectedComId.value,
    com_role: 1,
    ...queryParam,
  };
  const res1 = await getCompanyHsCode(params1);
  companyHsCodeData.value.as_buyer = res1.data.result.as_buyer?.hs_code;

};

// 贸易伙伴数据
const tradePartnersData = ref({});

// 获取贸易伙伴数据
const fetchTradePartnersData = async () => {
  const params = {
    com_id: selectedComId.value,
    com_role: 2,
    ...queryParam,
  };
  const res = await getCompanyPartner(params);
  tradePartnersData.value.as_supplier = res.data.result.as_supplier.buyer;
  const params1 = {
    com_id: selectedComId.value,
    com_role: 1,
    ...queryParam,
  };
  const res1 = await getCompanyPartner(params1);
  tradePartnersData.value.as_buyer = res1.data.result.as_buyer.buyer;
};

const regionDistributionData = ref({});
// 获取企业区域分布数据
const fetchRegionDistributionData = async () => {
  const params = {
    com_id: selectedComId.value,
    com_role: 2,
    ...queryParam,
  };
  const res = await getRegionDistribution(params);
  regionDistributionData.value.as_supplier = res.data.result.as_supplier.dest_country;
  const params1 = {
    com_id: selectedComId.value,
    com_role: 1,
    ...queryParam,
  };
  const res1 = await getRegionDistribution(params1);
  regionDistributionData.value.as_buyer = res1.data.result.as_buyer.dest_country;
};

// 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 = []; // 重置货运历史数据
  companyHsCodeData.value = {}; // 重置企业HS编码数据
  tradePartnersData.value = {}; // 重置贸易伙伴数据
  regionDistributionData.value = {}; // 重置区域分布数据
};
const handleSortMode = (value) => {
  fetchHsCodeData(value);
};

const handleSortModeOriginCountryData = (value) => {
  fetchOriginCountryData(value);
}

const handleSortModeDestinationCountryData = (value) => {
  fetchDestinationCountryData(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)
};
</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;
}
</style>
