<!--
TD-002 集成指南（配额使用历史接口）：
1. 后端补充接口：GET /api/admin/v1/tenants/{id}/quota-usage-history
2. 前端调整步骤：
   - 启用 fetchGetTenantQuotaUsageHistory 方法（src/api/tenant.ts）
   - 修改 loadQuotaUsage 使用新接口（替换 fetchGetTenantQuotaUsage）
   - 移除本地模拟逻辑（quotaUsageSnapshotRecordedAt）
   - 更新 QuotaUsageHistoryRow 使用真实 changeType
   - 移除 ElAlert 提示条
3. 测试验证：分页、排序、changeType 显示正确
-->

<!--
╔═══════════════════════════════════════════════════════════════════════════╗
║ TD-002 集成指南：配额使用历史接口                                          ║
╠═══════════════════════════════════════════════════════════════════════════╣
║ 状态：当前使用临时方案（实时数据 + 本地模拟）                              ║
║                                                                           ║
║ 后端待补充接口：                                                           ║
║   GET /api/admin/v1/tenants/{tenantId}/quota-usage-history               ║
║   Query: Page=1, PageSize=10, StartDate?, EndDate?, QuotaType?           ║
║   Response: { items: QuotaUsageHistoryDto[], totalCount: number }        ║
║                                                                           ║
║ 前端集成步骤（后端接口就绪后）：                                            ║
║ 1. 启用 fetchGetTenantQuotaUsageHistory 方法（src/api/tenant.ts:76）     ║
║ 2. 修改 loadQuotaUsage 函数（约第 383 行）：                               ║
║    - 替换：fetchGetTenantQuotaUsage → fetchGetTenantQuotaUsageHistory    ║
║    - 使用真实分页参数：{ Page: usagePage.value, PageSize: usagePageSize } ║
║ 3. 移除本地模拟逻辑：                                                      ║
║    - 删除 quotaUsageSnapshotRecordedAt 变量（第 259 行）                  ║
║    - 删除 QuotaUsageHistoryRow 本地视图模型（第 253-256 行）              ║
║    - quotaUsageList 类型改为 QuotaUsageHistoryDto[]                      ║
║ 4. 更新 ElTable 列绑定：                                                   ║
║    - recordedAt: 直接使用 row.recordedAt                                 ║
║    - changeType: 直接使用 row.changeType（不再固定为 'snapshot'）         ║
║ 5. 移除/更新 ElAlert 提示：                                                ║
║    - 选项A：完全移除提示条（推荐）                                          ║
║    - 选项B：改为"支持查询历史记录（最近 30 天）"                             ║
║ 6. 测试验证：                                                              ║
║    - 分页切换（usagePage 变化触发 API 调用）                               ║
║    - 数据排序（recordedAt 倒序）                                          ║
║    - changeType 标签显示（increase/decrease/init/snapshot）              ║
║                                                                           ║
║ 预期数据示例（QuotaUsageHistoryDto）：                                     ║
║   {                                                                       ║
║     quotaType: 2,                                                         ║
║     usedValue: 512,                                                       ║
║     limitValue: 1024,                                                     ║
║     recordedAt: "2025-12-18T10:30:00Z",                                   ║
║     changeType: "increase"                                                ║
║   }                                                                       ║
╚═══════════════════════════════════════════════════════════════════════════╝
-->

<template>
  <ElDrawer
    v-model="visible"
    :title="t('tenant.quota.title')"
    size="900px"
    direction="rtl"
    @closed="handleClosed"
  >
    <div class="px-4" v-loading="isAnyLoading">
      <!-- 部分1: 配额使用情况（卡片网格） -->
      <ElCard class="mb-4" shadow="never">
        <template #header>
          <div class="font-semibold">{{ t('tenant.quota.usageSummary') }}</div>
        </template>

        <div class="grid grid-cols-2 gap-4">
          <ElCard
            v-for="item in quotaUsageList"
            :key="item.quotaType"
            shadow="never"
            class="border border-[var(--el-border-color-lighter)]"
          >
            <div class="flex items-center justify-between">
              <div class="font-semibold">{{ getQuotaTypeText(item.quotaType) }}</div>
              <div class="text-sm text-[var(--el-text-color-secondary)]">
                {{ formatPercentage(getUsagePercentage(item.usedValue, item.limitValue)) }}
              </div>
            </div>

            <div class="mt-3 space-y-1 text-sm">
              <div class="flex items-center justify-between">
                <span class="text-[var(--el-text-color-secondary)]">{{
                  t('tenant.quota.limitValue')
                }}</span>
                <span>{{ formatQuotaValue(item.limitValue, item.quotaType) }}</span>
              </div>
              <div class="flex items-center justify-between">
                <span class="text-[var(--el-text-color-secondary)]">{{
                  t('tenant.quota.usedValue')
                }}</span>
                <span>{{ formatQuotaValue(item.usedValue, item.quotaType) }}</span>
              </div>
              <div class="flex items-center justify-between">
                <span class="text-[var(--el-text-color-secondary)]">{{
                  t('tenant.quota.remainingValue')
                }}</span>
                <span>{{ formatQuotaValue(item.remainingValue, item.quotaType) }}</span>
              </div>
            </div>

            <ElProgress
              class="mt-3"
              :percentage="getUsagePercentage(item.usedValue, item.limitValue)"
              :stroke-width="8"
              :color="getProgressColor(getUsagePercentage(item.usedValue, item.limitValue))"
            />
          </ElCard>
        </div>
      </ElCard>

      <!-- 部分2: 配额使用明细（表格+分页） -->
      <ElCard class="mb-4" shadow="never">
        <template #header>
          <div class="font-semibold">{{ t('tenant.quota.usageHistory') }}</div>
        </template>

        <!-- TD-002：后端缺少“配额使用明细历史”接口，当前使用 quota-usage 的实时数据快照模拟展示 -->
        <ElAlert class="mb-3" type="info" :closable="false" show-icon>
          {{ t('tenant.quota.historyNotice') }}
        </ElAlert>

        <ElTable :data="quotaUsagePagedList" border size="small">
          <ElTableColumn :label="t('tenant.quota.recordedAt')" min-width="170">
            <template #default="{ row }">
              {{ formatDateTimeYmdHms(row.recordedAt) }}
            </template>
          </ElTableColumn>
          <ElTableColumn :label="t('tenant.quota.changeType')" min-width="110" align="center">
            <template #default="{ row }">
              <ElTag :type="getChangeTypeTagType(row.changeType)" size="small">
                {{ getChangeTypeText(row.changeType) }}
              </ElTag>
            </template>
          </ElTableColumn>
          <ElTableColumn :label="t('tenant.quota.quotaType')" min-width="160">
            <template #default="{ row }">
              {{ getQuotaTypeText(row.quotaType) }}
            </template>
          </ElTableColumn>
          <ElTableColumn :label="t('tenant.quota.usedValue')" min-width="120" align="right">
            <template #default="{ row }">
              {{ formatQuotaValue(row.usedValue, row.quotaType) }}
            </template>
          </ElTableColumn>
          <ElTableColumn :label="t('tenant.quota.limitValue')" min-width="120" align="right">
            <template #default="{ row }">
              {{ formatQuotaValue(row.limitValue, row.quotaType) }}
            </template>
          </ElTableColumn>
          <ElTableColumn :label="t('tenant.quota.usagePercentage')" min-width="120" align="right">
            <template #default="{ row }">
              {{ formatPercentage(getUsagePercentage(row.usedValue, row.limitValue)) }}
            </template>
          </ElTableColumn>
        </ElTable>

        <div class="mt-3 flex justify-end">
          <ElPagination
            v-model:current-page="usagePage"
            :page-size="usagePageSize"
            layout="prev, pager, next, total"
            :total="quotaUsageList.length"
          />
        </div>
      </ElCard>

      <!-- 部分3: 配额购买记录（表格+分页） -->
      <ElCard shadow="never">
        <template #header>
          <div class="font-semibold">{{ t('tenant.quota.purchaseHistory') }}</div>
        </template>

        <ElTable :data="purchaseList" border size="small" v-loading="purchaseLoading">
          <ElTableColumn :label="t('tenant.quota.orderNo')" min-width="140">
            <template #default="{ row }">
              <!-- TD-002：后端未提供订单号字段，当前使用购买记录ID进行前端格式化展示 -->
              <ElTooltip
                :content="`${t('tenant.quota.fullOrderId')}: ${row.id}`"
                placement="top"
                :show-after="200"
              >
                <span class="cursor-help">{{ formatOrderNo(row.id, row.purchasedAt) }}</span>
              </ElTooltip>
            </template>
          </ElTableColumn>
          <ElTableColumn :label="t('tenant.quota.purchasedAt')" min-width="170">
            <template #default="{ row }">
              {{ formatDateTime(row.purchasedAt) }}
            </template>
          </ElTableColumn>
          <ElTableColumn :label="t('tenant.quota.quotaType')" min-width="160">
            <template #default="{ row }">
              {{ getQuotaTypeText(row.quotaType) }}
            </template>
          </ElTableColumn>
          <ElTableColumn :label="t('tenant.quota.purchaseValue')" min-width="120" align="right">
            <template #default="{ row }">
              {{ formatQuotaValue(row.quotaValue, row.quotaType) }}
            </template>
          </ElTableColumn>
          <ElTableColumn :label="t('tenant.quota.price')" min-width="110" align="right">
            <template #default="{ row }">
              {{ formatPrice(row.price) }}
            </template>
          </ElTableColumn>
          <ElTableColumn
            :label="t('tenant.quota.quotaPackage')"
            min-width="160"
            show-overflow-tooltip
          >
            <template #default="{ row }">
              {{ row.quotaPackageName || '-' }}
            </template>
          </ElTableColumn>
        </ElTable>

        <div class="mt-3 flex justify-end">
          <ElPagination
            v-model:current-page="purchasePage"
            :page-size="purchasePageSize"
            layout="prev, pager, next, total"
            :total="purchaseTotalCount"
            @current-change="handlePurchasePageChange"
          />
        </div>
      </ElCard>
    </div>
  </ElDrawer>
</template>

<script setup lang="ts">
  import { computed, ref } from 'vue'
  import { useI18n } from 'vue-i18n'
  import { ElMessage } from 'element-plus'
  import { fetchGetTenantQuotaPurchases, fetchGetTenantQuotaUsage } from '@/api/tenant'
  import type { QuotaUsageHistoryDto } from '@/types/tenant'

  defineOptions({ name: 'TenantQuotaDrawer' })

  const { t } = useI18n()

  const visible = ref(false)
  const tenantId = ref<string>('')
  const currentLoadToken = ref(0)

  const quotaUsageLoading = ref(false)
  const purchaseLoading = ref(false)

  const quotaUsageList = ref<Api.QuotaPackage.TenantQuotaUsageDto[]>([])

  const usagePage = ref(1)
  const usagePageSize = 10

  const purchasePage = ref(1)
  const purchasePageSize = 10
  const purchaseTotalCount = ref(0)
  const purchaseList = ref<Api.QuotaPackage.TenantQuotaPurchaseDto[]>([])

  const isAnyLoading = computed(() => quotaUsageLoading.value || purchaseLoading.value)

  type QuotaUsageChangeType = QuotaUsageHistoryDto['changeType']
  type QuotaUsageHistoryRow = QuotaUsageHistoryDto

  // TD-002：历史接口缺失，recordedAt 暂用“拉取时刻”的快照时间模拟（ISO 字符串）。
  const quotaUsageSnapshotRecordedAt = ref<string>('')

  const getUsagePercentage = (usedValue: number, limitValue: number) => {
    if (!limitValue) return 0
    return Math.min(Math.round((usedValue / limitValue) * 100), 100)
  }

  const formatPercentage = (percentage: number) => `${percentage}%`

  const getProgressColor = (percentage: number) => {
    if (percentage >= 80) return 'var(--el-color-danger)'
    if (percentage >= 50) return 'var(--el-color-warning)'
    return 'var(--el-color-success)'
  }

  const getQuotaUnit = (quotaType: number) => {
    // TenantQuotaType: 0=Store, 1=Account, 2=StorageGb, 3=SmsCredits, 4=DeliveryOrders
    switch (quotaType) {
      case 2:
        return 'GB'
      default:
        return ''
    }
  }

  const formatQuotaValue = (value: number, quotaType: number) => {
    const unit = getQuotaUnit(quotaType)
    return unit ? `${value} ${unit}` : value.toString()
  }

  const formatPrice = (price: number) => price.toFixed(2)

  const formatDateTime = (value?: string) => {
    if (!value) return '-'
    return new Date(value).toLocaleString()
  }

  const formatDateTimeYmdHms = (value?: string) => {
    if (!value) return '-'

    const date = new Date(value)
    if (Number.isNaN(date.getTime())) return '-'

    const pad2 = (v: number) => v.toString().padStart(2, '0')
    const yyyy = date.getFullYear()
    const mm = pad2(date.getMonth() + 1)
    const dd = pad2(date.getDate())
    const hh = pad2(date.getHours())
    const mi = pad2(date.getMinutes())
    const ss = pad2(date.getSeconds())

    return `${yyyy}-${mm}-${dd} ${hh}:${mi}:${ss}`
  }

  // TD-002：后端订单号缺失，前端临时格式化展示（QP-{YYYYMMDD}-{后8位ID}）。
  const formatOrderNo = (id: string, purchasedAt: string): string => {
    const safeId = id || ''

    // 1) ISO 字符串优先直接取日期片段，避免时区转换导致跨日
    const isoDatePart = purchasedAt?.slice(0, 10)
    const datePart = isoDatePart && /^\d{4}-\d{2}-\d{2}$/.test(isoDatePart) ? isoDatePart : ''
    const yyyymmdd = datePart ? datePart.replace(/-/g, '') : ''

    // 2) ID 后 8 位（不足 8 位则用完整 ID）
    const idSuffix = safeId.length >= 8 ? safeId.slice(-8) : safeId

    return `QP-${yyyymmdd || '00000000'}-${idSuffix}`
  }

  const getQuotaTypeText = (quotaType: number) => {
    switch (quotaType) {
      case 0:
        return t('tenant.quota.type.store')
      case 1:
        return t('tenant.quota.type.account')
      case 2:
        return t('tenant.quota.type.storageGb')
      case 3:
        return t('tenant.quota.type.smsCredits')
      case 4:
        return t('tenant.quota.type.deliveryOrders')
      default:
        return t('tenant.quota.type.unknown', { value: quotaType })
    }
  }

  const getChangeTypeText = (changeType: QuotaUsageChangeType) => {
    // TD-002：当前为实时数据快照，历史变更类型待后端补充
    if (changeType === 'snapshot') return t('tenant.quota.snapshot')
    return t('tenant.quota.snapshot')
  }

  const getChangeTypeTagType = (changeType: QuotaUsageChangeType) => {
    switch (changeType) {
      case 'increase':
        return 'success'
      case 'decrease':
        return 'warning'
      case 'init':
      case 'snapshot':
      default:
        return 'info'
    }
  }

  const quotaUsageHistoryList = computed<QuotaUsageHistoryRow[]>(() => {
    const recordedAt = quotaUsageSnapshotRecordedAt.value || new Date().toISOString()

    return quotaUsageList.value.map((item) => ({
      quotaType: item.quotaType,
      usedValue: item.usedValue,
      limitValue: item.limitValue,
      recordedAt,
      changeType: 'snapshot'
    }))
  })

  const quotaUsagePagedList = computed(() => {
    const start = (usagePage.value - 1) * usagePageSize
    const end = start + usagePageSize
    return quotaUsageHistoryList.value.slice(start, end)
  })

  // TD-002: 当前使用临时方案（fetchGetTenantQuotaUsage + 本地模拟）
  // 后端接口就绪后，替换为 fetchGetTenantQuotaUsageHistory
  // 详见文件头部「TD-002 集成指南」
  const loadQuotaUsage = async (token: number) => {
    if (!tenantId.value) return

    quotaUsageLoading.value = true
    try {
      /**
       * TD-002（配额使用历史接口缺失）
       * - 当前实现：使用 fetchGetTenantQuotaUsage 获取实时数据（quota-usage），并在前端补齐 recordedAt/changeType 用于“使用明细”展示
       * - 未来接口：GET /api/admin/v1/tenants/{id}/quota-usage-history?page=1&pageSize=10
       * - 预期响应：{ items: QuotaUsageHistoryDto[], totalCount: number }（实际类型为 Api.Common.PageResult<QuotaUsageHistoryDto>）
       * - DTO 字段：quotaType、usedValue、limitValue、recordedAt、changeType
       */

      // 1. 获取配额使用情况（实时数据）
      const list = await fetchGetTenantQuotaUsage(tenantId.value)
      if (token !== currentLoadToken.value) return
      quotaUsageList.value = list
      quotaUsageSnapshotRecordedAt.value = new Date().toISOString()
    } catch (error) {
      console.error(error)
      ElMessage.error(t('tenant.error.loadQuotaFailed'))
    } finally {
      quotaUsageLoading.value = false
    }
  }

  const loadQuotaPurchases = async (token: number) => {
    if (!tenantId.value) return

    purchaseLoading.value = true
    try {
      // 1. 获取配额购买记录（分页）
      const result = await fetchGetTenantQuotaPurchases(tenantId.value, {
        Page: purchasePage.value,
        PageSize: purchasePageSize
      })

      if (token !== currentLoadToken.value) return
      purchaseList.value = result.items
      purchaseTotalCount.value = result.totalCount
    } catch (error) {
      console.error(error)
      ElMessage.error(t('tenant.error.loadQuotaFailed'))
    } finally {
      purchaseLoading.value = false
    }
  }

  const handlePurchasePageChange = async (page: number) => {
    // 1. 更新分页并重新拉取
    purchasePage.value = page
    await loadQuotaPurchases(currentLoadToken.value)
  }

  const open = async (id: string) => {
    visible.value = true

    // 1. 初始化状态
    tenantId.value = id
    usagePage.value = 1
    purchasePage.value = 1
    currentLoadToken.value += 1
    const token = currentLoadToken.value

    // 2. 并行加载数据
    await Promise.all([loadQuotaUsage(token), loadQuotaPurchases(token)])
  }

  const handleClosed = () => {
    // 1. 关闭时清理状态
    currentLoadToken.value += 1
    tenantId.value = ''
    quotaUsageList.value = []
    usagePage.value = 1
    quotaUsageSnapshotRecordedAt.value = ''

    purchaseList.value = []
    purchaseTotalCount.value = 0
    purchasePage.value = 1
  }

  defineExpose({ open })
</script>
