<template>
  <div class="art-page-view space-y-4">
    <ElCard shadow="never">
      <div class="grid gap-4 md:grid-cols-5">
        <div class="stat-card">
          <div class="stat-label">{{ t('store.audit.stats.pending') }}</div>
          <div class="stat-value">{{ statistics.pendingCount }}</div>
        </div>
        <div class="stat-card">
          <div class="stat-label">{{ t('store.audit.stats.overdue') }}</div>
          <div class="stat-value text-warning">{{ statistics.overdueCount }}</div>
        </div>
        <div class="stat-card">
          <div class="stat-label">{{ t('store.audit.stats.approved') }}</div>
          <div class="stat-value text-success">{{ statistics.approvedCount }}</div>
        </div>
        <div class="stat-card">
          <div class="stat-label">{{ t('store.audit.stats.rejected') }}</div>
          <div class="stat-value text-danger">{{ statistics.rejectedCount }}</div>
        </div>
        <div class="stat-card">
          <div class="stat-label">{{ t('store.audit.stats.avgProcessing') }}</div>
          <div class="stat-value">{{ statistics.avgProcessingHours }}</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.audit.search.keyword')">
          <ElInput
            v-model="formFilters.keyword"
            clearable
            class="w-64"
            :placeholder="t('store.audit.search.keywordPlaceholder')"
          />
        </ElFormItem>
        <ElFormItem :label="t('store.audit.search.tenantId')">
          <ElInput
            v-model="formFilters.tenantId"
            clearable
            class="w-48"
            :placeholder="t('store.audit.search.tenantIdPlaceholder')"
          />
        </ElFormItem>
        <ElFormItem :label="t('store.audit.search.dateRange')">
          <ElDatePicker
            v-model="formFilters.dateRange"
            type="daterange"
            unlink-panels
            range-separator="-"
            class="w-[320px]"
            :value-format="dateTimeFormat"
            :start-placeholder="t('store.audit.search.dateRangeStart')"
            :end-placeholder="t('store.audit.search.dateRangeEnd')"
          />
        </ElFormItem>
        <ElFormItem :label="t('store.audit.search.overdueOnly')">
          <ElSwitch
            v-model="formFilters.overdueOnly"
            :active-text="t('common.yes')"
            :inactive-text="t('common.no')"
          />
        </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="handleRefresh"
      />

      <ArtTable
        :data="data"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        @pagination:current-change="handleCurrentChange"
        @pagination:size-change="handleSizeChange"
      >
        <template #ownershipType="{ row }">
          <span>{{ getOwnershipTypeText(row.ownershipType) }}</span>
        </template>
        <template #submittedAt="{ row }">
          <span>{{ formatDateTime(row.submittedAt) }}</span>
        </template>
        <template #isOverdue="{ row }">
          <ElTag :type="row.isOverdue ? 'danger' : 'info'">
            {{ row.isOverdue ? t('store.audit.overdue') : t('store.audit.notOverdue') }}
          </ElTag>
        </template>
        <template #action="{ row }">
          <ElButton link type="primary" @click="handleDetail(row)">
            {{ t('store.audit.action.detail') }}
          </ElButton>
        </template>
      </ArtTable>
    </ElCard>

    <StoreAuditDetailDrawer ref="detailDrawerRef" @updated="handleUpdated" />
  </div>
</template>

<script setup lang="ts">
  import { onMounted, ref } from 'vue'
  import { useI18n } from 'vue-i18n'
  import {
    ElButton,
    ElCard,
    ElDatePicker,
    ElForm,
    ElFormItem,
    ElInput,
    ElSwitch,
    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 { fetchPendingStoreAudits, fetchStoreAuditStatistics } from '@/api/storeAudit'
  import { StoreOwnershipType } from '@/enums/StoreOwnershipType'
  import { formatDateTime } from '@/utils/billing'
  import StoreAuditDetailDrawer from '@/views/platform/store-audits/components/StoreAuditDetailDrawer.vue'
  import type { ColumnOption } from '@/types/component'

  defineOptions({ name: 'PlatformStoreAudits' })

  interface StoreAuditFilters {
    keyword: string
    tenantId: string
    dateRange: [string, string] | []
    overdueOnly: boolean
  }

  // 1. 基础状态
  const { t } = useI18n()
  const showSearchBar = ref(true)
  const detailDrawerRef = ref<InstanceType<typeof StoreAuditDetailDrawer>>()
  const statistics = ref<Api.StoreAudit.StoreAuditStatisticsDto>({
    pendingCount: 0,
    overdueCount: 0,
    approvedCount: 0,
    rejectedCount: 0,
    avgProcessingHours: 0,
    dailyTrend: []
  })
  const dateTimeFormat = 'YYYY-MM-DDTHH:mm:ss.SSSZ'

  // 2. 搜索表单
  const formFilters = ref<StoreAuditFilters>({
    keyword: '',
    tenantId: '',
    dateRange: [],
    overdueOnly: false
  })

  // 3. 表格配置
  const {
    data,
    loading,
    pagination,
    columns,
    searchParams,
    refreshData,
    handleCurrentChange,
    handleSizeChange
  } = useTable<typeof fetchPendingStoreAudits, Api.StoreAudit.PendingStoreAuditDto>({
    core: {
      apiFn: fetchPendingStoreAudits,
      apiParams: {
        Page: 1,
        PageSize: 20,
        sortBy: 'SubmittedAt',
        sortDesc: true
      },
      paginationKey: {
        current: 'Page',
        size: 'PageSize'
      },
      columnsFactory: (): ColumnOption<Api.StoreAudit.PendingStoreAuditDto>[] => [
        { type: 'globalIndex', label: '#', width: 60, fixed: 'left' },
        { prop: 'storeName', label: t('store.audit.table.storeName'), minWidth: 160 },
        { prop: 'storeCode', label: t('store.audit.table.storeCode'), minWidth: 140 },
        { prop: 'tenantName', label: t('store.audit.table.tenantName'), minWidth: 160 },
        { prop: 'merchantName', label: t('store.audit.table.merchantName'), minWidth: 160 },
        {
          prop: 'ownershipType',
          label: t('store.audit.table.ownershipType'),
          width: 120,
          useSlot: true
        },
        {
          prop: 'submittedAt',
          label: t('store.audit.table.submittedAt'),
          width: 180,
          useSlot: true
        },
        { prop: 'waitingDays', label: t('store.audit.table.waitingDays'), width: 120 },
        {
          prop: 'qualificationCount',
          label: t('store.audit.table.qualificationCount'),
          width: 120
        },
        { prop: 'isOverdue', label: t('store.audit.table.overdue'), width: 120, useSlot: true },
        { prop: 'action', label: t('common.action'), width: 140, fixed: 'right', useSlot: true }
      ]
    }
  })

  // 4. 查询与操作
  const handleSearch = () => {
    const [submittedFrom, submittedTo] = formFilters.value.dateRange || []
    searchParams.keyword = formFilters.value.keyword.trim() || undefined
    searchParams.tenantId = formFilters.value.tenantId.trim() || undefined
    searchParams.submittedFrom = submittedFrom || undefined
    searchParams.submittedTo = submittedTo || undefined
    searchParams.overdueOnly = formFilters.value.overdueOnly
    refreshData()
    void loadStatistics()
  }
  const handleReset = () => {
    formFilters.value = {
      keyword: '',
      tenantId: '',
      dateRange: [],
      overdueOnly: false
    }
    searchParams.keyword = undefined
    searchParams.tenantId = undefined
    searchParams.submittedFrom = undefined
    searchParams.submittedTo = undefined
    searchParams.overdueOnly = false
    refreshData()
    void loadStatistics()
  }
  const handleRefresh = () => {
    refreshData()
    void loadStatistics()
  }
  const handleDetail = (row: Api.StoreAudit.PendingStoreAuditDto) => {
    detailDrawerRef.value?.open(String(row.storeId))
  }
  const handleUpdated = () => {
    refreshData()
    void loadStatistics()
  }

  // 5. 统计数据
  const loadStatistics = async () => {
    const [dateFrom, dateTo] = formFilters.value.dateRange || []
    statistics.value = await fetchStoreAuditStatistics({
      dateFrom: dateFrom || undefined,
      dateTo: dateTo || undefined
    })
  }

  // 6. 展示辅助
  const getOwnershipTypeText = (type?: StoreOwnershipType) => {
    switch (type) {
      case StoreOwnershipType.SameEntity:
        return t('store.ownership.same')
      case StoreOwnershipType.DifferentEntity:
        return t('store.ownership.different')
      default:
        return '-'
    }
  }

  onMounted(() => {
    void loadStatistics()
  })
</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-warning {
    color: var(--el-color-warning);
  }

  .text-success {
    color: var(--el-color-success);
  }

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