<template>
  <div class="company-list">
    <div class="sort-controls">
      <a-radio-group v-model:value="companyType" style="margin-right: 16px">
        <a-radio-button value="supplier">供应商</a-radio-button>
        <a-radio-button value="purchaser">采购商</a-radio-button>
      </a-radio-group>
      <a-radio-group v-model:value="sortMode" @change="fetchCompanies">
        <a-radio-button value="count">按交易次数</a-radio-button>
        <a-radio-button value="weight">按交易重量</a-radio-button>
      </a-radio-group>
    </div>

    <a-table
      :columns="columns"
      :data-source="companies"
      :pagination="{
        current: currentPage,
        pageSize: pageSize,
        total: total,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        showQuickJumper: true,
        showLessItems: true,
        showTotal: total => `共 ${total} 条`,
        onChange: handlePageChange,
        onShowSizeChange: handlePageSizeChange
      }"
      row-key="val"
      style="margin-top: 16px"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <a-button type="link" @click="showDetail(record)">详情</a-button>
        </template>
      </template>
    </a-table>

    <a-modal v-model:visible="detailVisible" title="企业详情" @ok="detailVisible = false">
      <template v-if="selectedCompany">
        <a-descriptions bordered :column="1">
          <a-descriptions-item label="企业名称">{{ selectedCompany.result.name }}</a-descriptions-item>
          <a-descriptions-item label="地址">{{ selectedCompany.result.address }}</a-descriptions-item>
          <a-descriptions-item label="邮编">
            <template v-if="selectedCompany.result.postal_code && selectedCompany.result.postal_code.length">
              <div v-for="(code, index) in selectedCompany.result.postal_code" :key="index">
                {{ code }}
              </div>
            </template>
            <span v-else>无</span>
          </a-descriptions-item>
          <a-descriptions-item label="邮箱">
            <template v-if="selectedCompany.result.email && selectedCompany.result.email.length">
              <div v-for="(email, index) in selectedCompany.result.email" :key="index">
                {{ email }}
              </div>
            </template>
            <span v-else>无</span>
          </a-descriptions-item>
          <a-descriptions-item label="电话">
            <template v-if="selectedCompany.result.phone && selectedCompany.result.phone.length">
              <div v-for="(phone, index) in selectedCompany.result.phone" :key="index">
                {{ phone }}
              </div>
            </template>
            <span v-else>无</span>
          </a-descriptions-item>
        </a-descriptions>
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted, watch } from 'vue'
  import { getSupplierReport, getBuyerReport, getCompanyInfo } from '../customsData.api'
  import { message } from 'ant-design-vue'

  interface Company {
    val: string
    count: number
    fk: string
    // ... other company fields
  }

  interface CompanyDetail {
    uuid: string
    name: string
    phone: string[] | null
    email: string[] | null
    fax: string | null
    postal_code: string[] | null
    city: string | null
    address: string
    country: string
  }

  const companies = ref<Company[]>([])
  const detailVisible = ref(false)
  const selectedCompany = ref<Company | null>(null)
  const sortMode = ref<'count' | 'weight'>('count')
  const companyType = ref<'supplier' | 'purchaser'>('supplier')
  const currentPage = ref(1)
  const pageSize = ref(20)
  const total = ref(0)

  const props = defineProps({
    queryParam: {
      type: Object,
      required: true,
      default: () => ({}),
    },
  });

  const fetchCompanies = async () => {
    try {
      const params = {
        ...props.queryParam,
        sort: sortMode.value,
        page: currentPage.value,
        page_size: pageSize.value
      }
      
      const response = companyType.value === 'supplier' 
        ? await getSupplierReport(params)
        : await getBuyerReport(params)
        
      companies.value = response.result.data.result.buckets
      total.value = response.result.data.result.numBuckets || 0
    } catch (error) {
      message.error(companyType.value === 'supplier' 
        ? '没有搜索到供应商信息'
        : '没有搜索到采购商信息')
    }
  }

  const showDetail = async (company: Company) => {
    try {
      // Create a copy of queryParam and remove pagination related fields
      const { page, page_size, ...otherParams } = props.queryParam
      
      const params = {
        ...otherParams,
        com_id: company.fk,
        com_role: companyType.value === 'supplier' ? 2 : 1
      }
      const response = await getCompanyInfo(params)
      selectedCompany.value = response.result.data
      detailVisible.value = true
    } catch (error) {
      message.error('没有搜索到企业详情')
    }
  }

  const handlePageChange = (page: number) => {
    currentPage.value = page
    fetchCompanies()
  }

  const handlePageSizeChange = (current: number, size: number) => {
    pageSize.value = size
    currentPage.value = 1
    fetchCompanies()
  }

  const columns = [
    {
      title: '企业名称',
      dataIndex: 'val',
      key: 'val',
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
    },
  ]

  onMounted(() => {
    fetchCompanies()
  })

  watch(() => props.queryParam, () => {
    currentPage.value = 1
    fetchCompanies()
  }, { deep: true })

  watch(companyType, () => {
    currentPage.value = 1
    fetchCompanies()
  })
</script>

<style lang="less" scoped>
  .company-list {
    padding: 16px;

    .sort-controls {
      margin-bottom: 16px;
      text-align: right;
    }
  }
</style>
