<template>
  <div>
    <!-- 1. 筛选区 -->
    <ElCard class="art-search-card" shadow="never">
      <ElForm :model="formFilters" label-width="100px">
        <ElRow :gutter="16">
          <ElCol :span="8">
            <ElFormItem :label="$t('quotaPackage.purchases.search.tenant')">
              <ElSelect
                v-model="formFilters.tenantId"
                :placeholder="$t('quotaPackage.purchases.search.tenantPlaceholder')"
                filterable
                remote
                clearable
                :remote-method="handleSearchTenant"
                :loading="tenantLoading"
                style="width: 100%"
                @change="handleTenantChange"
              >
                <ElOption
                  v-for="tenant in tenantOptions"
                  :key="tenant.id"
                  :label="tenant.name"
                  :value="tenant.id"
                />
              </ElSelect>
            </ElFormItem>
          </ElCol>
          <ElCol :span="16" class="text-right">
            <ElButton @click="handleReset">{{ $t('table.searchBar.reset') }}</ElButton>
            <ElButton type="primary" @click="handleSearch" v-ripple>
              {{ $t('table.searchBar.search') }}
            </ElButton>
          </ElCol>
        </ElRow>
      </ElForm>
    </ElCard>

    <!-- 2. 表格区 -->
    <ElCard class="art-table-card" shadow="never">
      <ArtTableHeader
        v-model:columns="columns"
        v-model:showSearchBar="showSearchBar"
        :loading="loading"
        @refresh="handleSearch"
      />

      <ArtTable
        :data="data"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        @pagination:current-change="handleCurrentChange"
        @pagination:size-change="handleSizeChange"
      >
        <template #quotaValue="{ row }">
          {{ formatQuotaValue(row.quotaType, row.quotaValue) }}
        </template>
        <template #price="{ row }">
          <span class="text-primary font-medium">￥{{ row.price }}</span>
        </template>
      </ArtTable>
    </ElCard>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { ElMessage } from 'element-plus'
  import ArtTable from '@/components/core/tables/art-table/index.vue'
  import ArtTableHeader from '@/components/core/tables/art-table-header/index.vue'
  import { useTable } from '@/hooks/core/useTable'
  import { fetchTenantQuotaPurchases } from '@/api/quotaPackage'
  import { fetchGetTenantList } from '@/api/tenant'
  import type { ColumnOption } from '@/types/component'
  import {
    ElButton,
    ElCard,
    ElCol,
    ElForm,
    ElFormItem,
    ElOption,
    ElRow,
    ElSelect
  } from 'element-plus'

  defineOptions({ name: 'TenantQuotaPurchaseList' })

  const { t } = useI18n()

  // 1. 筛选状态
  const showSearchBar = ref(true)
  const tenantLoading = ref(false)
  const tenantOptions = ref<Api.Tenant.TenantDto[]>([])
  const tenantNameMap = ref<Record<string, string>>({})

  const formFilters = ref({
    tenantId: '' as string
  })

  // 2. 搜索租户（远程）
  const handleSearchTenant = async (query: string) => {
    if (!query) return

    tenantLoading.value = true
    try {
      const res = await fetchGetTenantList({
        Keyword: query,
        Page: 1,
        PageSize: 20
      })
      tenantOptions.value = res.items || []
      tenantNameMap.value = Object.fromEntries(tenantOptions.value.map((x) => [x.id, x.name]))
    } catch (error) {
      console.error('Search tenant error:', error)
    } finally {
      tenantLoading.value = false
    }
  }

  // 3. 选中租户变化（补全名称映射）
  const handleTenantChange = (tenantId: string) => {
    if (!tenantId) return
    const tenant = tenantOptions.value.find((x) => x.id === tenantId)
    if (tenant) {
      tenantNameMap.value = { ...tenantNameMap.value, [tenantId]: tenant.name }
    }
  }

  // 4. 配额类型文本
  const getQuotaTypeText = (quotaType: number) => {
    const map: Record<number, string> = {
      0: t('quotaPackage.quotaType.storeCount'),
      1: t('quotaPackage.quotaType.accountCount'),
      2: t('quotaPackage.quotaType.storage'),
      3: t('quotaPackage.quotaType.smsCredits'),
      4: t('quotaPackage.quotaType.deliveryOrders'),
      5: t('quotaPackage.quotaType.promotionSlots')
    }
    return map[quotaType] || '-'
  }

  // 5. 格式化配额值
  const formatQuotaValue = (quotaType: number, value: number) => {
    switch (quotaType) {
      case 2: // Storage
        return `${value} GB`
      case 3: // SmsCredits
        return `${value} ${t('quotaPackage.unit.sms')}`
      case 4: // DeliveryOrders
        return `${value} ${t('quotaPackage.unit.orders')}`
      default:
        return value.toString()
    }
  }

  // 6. 日期格式化
  const formatDateTime = (value?: string) => {
    if (!value) return '-'
    return new Date(value).toLocaleString()
  }

  // 7. 表格配置（需要先选租户）
  type PurchaseApiFn = (params: {
    page?: number
    pageSize?: number
  }) => Promise<Api.Common.PageResult<Api.QuotaPackage.TenantQuotaPurchaseDto>>

  const purchaseApiFn: PurchaseApiFn = async (params) => {
    return fetchTenantQuotaPurchases(formFilters.value.tenantId, params)
  }

  const {
    data,
    loading,
    pagination,
    columns,
    getData: getDataByPage,
    clearData,
    handleCurrentChange,
    handleSizeChange
  } = useTable<PurchaseApiFn, Api.QuotaPackage.TenantQuotaPurchaseDto>({
    core: {
      apiFn: purchaseApiFn,
      immediate: false,
      paginationKey: {
        current: 'page',
        size: 'pageSize'
      },
      columnsFactory: (): ColumnOption<Api.QuotaPackage.TenantQuotaPurchaseDto>[] => [
        {
          type: 'globalIndex',
          label: t('quotaPackage.purchases.table.index'),
          width: 60,
          fixed: 'left'
        },
        {
          prop: 'tenantId',
          label: t('quotaPackage.purchases.table.tenantName'),
          minWidth: 160,
          formatter: (row) => tenantNameMap.value[row.tenantId] || '-'
        },
        {
          prop: 'quotaPackageName',
          label: t('quotaPackage.purchases.table.quotaPackageName'),
          minWidth: 180,
          showOverflowTooltip: true
        },
        {
          prop: 'quotaType',
          label: t('quotaPackage.purchases.table.quotaType'),
          width: 140,
          formatter: (row) => getQuotaTypeText(row.quotaType)
        },
        {
          prop: 'quotaValue',
          label: t('quotaPackage.purchases.table.quotaValue'),
          width: 140,
          useSlot: true
        },
        {
          prop: 'price',
          label: t('quotaPackage.purchases.table.price'),
          width: 120,
          useSlot: true
        },
        {
          prop: 'purchasedAt',
          label: t('quotaPackage.purchases.table.purchasedAt'),
          width: 180,
          formatter: (row) => formatDateTime(row.purchasedAt)
        },
        {
          prop: 'expiredAt',
          label: t('quotaPackage.purchases.table.expiredAt'),
          width: 180,
          formatter: (row) => formatDateTime(row.expiredAt)
        }
      ]
    }
  })

  // 8. 搜索与重置
  const handleSearch = () => {
    if (!formFilters.value.tenantId) {
      ElMessage.warning(t('quotaPackage.purchases.message.selectTenantFirst'))
      clearData()
      return
    }

    void getDataByPage()
  }

  const handleReset = () => {
    formFilters.value.tenantId = ''
    clearData()
  }

  // 9. 生命周期
  onMounted(() => {
    // 初始化加载（等待用户选择租户）
  })
</script>

<style scoped>
  .art-search-card {
    margin-bottom: 16px;
  }
</style>
