<template>
  <div class="art-page-view space-y-4">
    <ElCard shadow="never">
      <div class="grid gap-4 md:grid-cols-2">
        <div class="stat-card">
          <div class="stat-label">{{ t('store.alerts.summary.expiringSoon') }}</div>
          <div class="stat-value">{{ summary.expiringSoonCount }}</div>
        </div>
        <div class="stat-card">
          <div class="stat-label">{{ t('store.alerts.summary.expired') }}</div>
          <div class="stat-value text-danger">{{ summary.expiredCount }}</div>
        </div>
      </div>
    </ElCard>

    <ElCard class="art-table-card" shadow="never">
      <ElForm :model="formFilters" inline class="flex flex-wrap gap-4">
        <ElFormItem :label="t('store.alerts.search.tenantId')">
          <ElInput
            v-model="formFilters.tenantId"
            clearable
            class="w-48"
            :placeholder="t('store.alerts.search.tenantIdPlaceholder')"
          />
        </ElFormItem>
        <ElFormItem :label="t('store.alerts.search.daysThreshold')">
          <ElInputNumber v-model="formFilters.daysThreshold" :min="1" class="w-40" />
        </ElFormItem>
        <ElFormItem :label="t('store.alerts.search.expired')">
          <ElSelect v-model="formFilters.expired" class="w-40" clearable>
            <ElOption
              v-for="option in expiredOptions"
              :key="String(option.value)"
              :label="option.label"
              :value="option.value"
            />
          </ElSelect>
        </ElFormItem>
        <ElFormItem>
          <ElButton type="primary" @click="handleSearch">{{
            t('table.searchBar.search')
          }}</ElButton>
          <ElButton @click="handleReset">{{ t('table.searchBar.reset') }}</ElButton>
        </ElFormItem>
      </ElForm>

      <ArtTableHeader
        v-model:columns="columns"
        v-model:showSearchBar="showSearchBar"
        :loading="loading"
        @refresh="refreshData"
      />

      <ArtTable
        :data="data"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        @pagination:current-change="handleCurrentChange"
        @pagination:size-change="handleSizeChange"
      >
        <template #qualificationType="{ row }">
          <span>{{ getQualificationTypeText(row.qualificationType) }}</span>
        </template>
        <template #expiresAt="{ row }">
          <span>{{ formatDate(row.expiresAt) }}</span>
        </template>
        <template #isExpired="{ row }">
          <ElTag :type="row.isExpired ? 'danger' : 'warning'">
            {{
              row.isExpired ? t('store.alerts.status.expired') : t('store.alerts.status.expiring')
            }}
          </ElTag>
        </template>
        <template #storeBusinessStatus="{ row }">
          <ElTag :type="getBusinessStatusType(row.storeBusinessStatus)">
            {{ getBusinessStatusText(row.storeBusinessStatus) }}
          </ElTag>
        </template>
      </ArtTable>
    </ElCard>
  </div>
</template>

<script setup lang="ts">
  import { ref } from 'vue'
  import { useI18n } from 'vue-i18n'
  import {
    ElButton,
    ElCard,
    ElForm,
    ElFormItem,
    ElInput,
    ElInputNumber,
    ElOption,
    ElSelect,
    ElTag
  } 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 { fetchQualificationAlerts } from '@/api/storeAudit'
  import { StoreBusinessStatus } from '@/enums/StoreBusinessStatus'
  import { StoreQualificationType } from '@/enums/StoreQualificationType'
  import { formatDate } from '@/utils/billing'
  import { defaultResponseAdapter } from '@/utils/table/tableUtils'
  import type { ColumnOption } from '@/types/component'

  defineOptions({ name: 'PlatformQualificationAlerts' })

  interface QualificationAlertFilters {
    tenantId: string
    daysThreshold?: number
    expired?: boolean
  }

  interface ExpiredOption {
    label: string
    value: boolean
  }

  // 1. 基础状态
  const { t } = useI18n()
  const showSearchBar = ref(true)
  const summary = ref<Api.Store.StoreQualificationAlertSummaryDto>({
    expiringSoonCount: 0,
    expiredCount: 0
  })

  // 2. 查询筛选
  const formFilters = ref<QualificationAlertFilters>({
    tenantId: '',
    daysThreshold: undefined,
    expired: undefined
  })
  const expiredOptions = ref<ExpiredOption[]>([
    { label: t('store.alerts.status.expired'), value: true },
    { label: t('store.alerts.status.expiring'), value: false }
  ])

  // 3. 表格配置
  const {
    data,
    loading,
    pagination,
    columns,
    searchParams,
    refreshData,
    handleCurrentChange,
    handleSizeChange
  } = useTable<typeof fetchQualificationAlerts, Api.Store.StoreQualificationAlertDto>({
    core: {
      apiFn: fetchQualificationAlerts,
      apiParams: {
        Page: 1,
        PageSize: 20
      },
      paginationKey: {
        current: 'Page',
        size: 'PageSize'
      },
      columnsFactory: (): ColumnOption<Api.Store.StoreQualificationAlertDto>[] => [
        { type: 'globalIndex', label: '#', width: 60, fixed: 'left' },
        { prop: 'storeName', label: t('store.alerts.table.storeName'), minWidth: 160 },
        { prop: 'storeCode', label: t('store.alerts.table.storeCode'), minWidth: 140 },
        { prop: 'tenantName', label: t('store.alerts.table.tenantName'), minWidth: 160 },
        {
          prop: 'qualificationType',
          label: t('store.alerts.table.qualificationType'),
          width: 140,
          useSlot: true
        },
        { prop: 'expiresAt', label: t('store.alerts.table.expiresAt'), width: 140, useSlot: true },
        { prop: 'daysUntilExpiry', label: t('store.alerts.table.daysUntilExpiry'), width: 140 },
        { prop: 'isExpired', label: t('store.alerts.table.status'), width: 120, useSlot: true },
        {
          prop: 'storeBusinessStatus',
          label: t('store.alerts.table.businessStatus'),
          width: 120,
          useSlot: true
        }
      ]
    },
    transform: {
      responseAdapter: (response) => {
        const result = defaultResponseAdapter<Api.Store.StoreQualificationAlertDto>(response)
        const typed = response as Api.Store.StoreQualificationAlertResultDto
        summary.value = typed?.summary ?? { expiringSoonCount: 0, expiredCount: 0 }
        return result
      }
    }
  })

  // 4. 查询操作
  const handleSearch = () => {
    searchParams.tenantId = formFilters.value.tenantId.trim() || undefined
    searchParams.daysThreshold = formFilters.value.daysThreshold || undefined
    searchParams.expired = formFilters.value.expired
    refreshData()
  }
  const handleReset = () => {
    formFilters.value = {
      tenantId: '',
      daysThreshold: undefined,
      expired: undefined
    }
    searchParams.tenantId = undefined
    searchParams.daysThreshold = undefined
    searchParams.expired = undefined
    refreshData()
  }

  // 5. 展示辅助
  const getQualificationTypeText = (type: StoreQualificationType) => {
    switch (type) {
      case StoreQualificationType.BusinessLicense:
        return t('store.qualification.type.businessLicense')
      case StoreQualificationType.FoodServiceLicense:
        return t('store.qualification.type.foodService')
      case StoreQualificationType.StorefrontPhoto:
        return t('store.qualification.type.storefront')
      case StoreQualificationType.InteriorPhoto:
        return t('store.qualification.type.interior')
      default:
        return '-'
    }
  }
  const getBusinessStatusType = (status: StoreBusinessStatus) => {
    switch (status) {
      case StoreBusinessStatus.Open:
        return 'success'
      case StoreBusinessStatus.Resting:
        return 'warning'
      case StoreBusinessStatus.ForceClosed:
        return 'danger'
      default:
        return 'info'
    }
  }
  const getBusinessStatusText = (status: StoreBusinessStatus) => {
    switch (status) {
      case StoreBusinessStatus.Open:
        return t('store.businessStatus.open')
      case StoreBusinessStatus.Resting:
        return t('store.businessStatus.resting')
      case StoreBusinessStatus.ForceClosed:
        return t('store.businessStatus.forceClosed')
      default:
        return t('store.businessStatus.unknown')
    }
  }
</script>

<style scoped>
  .stat-card {
    display: flex;
    flex-direction: column;
    gap: 6px;
    padding: 12px 14px;
    background: var(--el-fill-color-blank);
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 12px;
  }

  .stat-label {
    font-size: 13px;
    color: var(--el-text-color-secondary);
  }

  .stat-value {
    font-size: 22px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }

  .text-danger {
    color: var(--el-color-danger);
  }
</style>
