<template>
  <div class="page-content">
    <div class="mb-5 flex items-center justify-between gap-4">
      <div>
        <h2 class="text-xl font-semibold">租户概览</h2>
        <p class="text-g-500 mt-1 text-sm">以部门为租户维度,查看各租户账号、API Key 与今日用量</p>
      </div>
      <ElButton :loading="loading" @click="load">刷新</ElButton>
    </div>
    <ElTable v-loading="loading" :data="tenants" row-key="id">
      <ElTableColumn prop="name" label="租户(部门)" min-width="200" />
      <ElTableColumn prop="portal_users" label="门户账号" width="100" />
      <ElTableColumn label="Key 配额" width="150">
        <template #default="{ row }">
          {{ row.enabled_api_keys }} / {{ row.max_api_keys || '∞' }}
        </template>
      </ElTableColumn>
      <ElTableColumn label="月 Token 配额" width="170">
        <template #default="{ row }">
          {{ (row.month_tokens || 0).toLocaleString() }} / {{ row.max_monthly_tokens ? row.max_monthly_tokens.toLocaleString() : '∞' }}
        </template>
      </ElTableColumn>
      <ElTableColumn prop="today_requests" label="今日请求" width="110" />
      <ElTableColumn prop="today_tokens" label="今日 Tokens" width="130" />
    </ElTable>
    <div v-if="!loading && !tenants.length" class="py-10 text-center text-g-400">暂无租户数据</div>
  </div>
</template>

<script setup lang="ts">
  import request from '@/utils/http'

  interface TenantRow {
    id: string
    name: string
    max_api_keys: number
    max_monthly_tokens: number
    portal_users: number
    enabled_api_keys: number
    today_requests: number
    today_tokens: number
    month_tokens: number
  }

  const loading = ref(false)
  const tenants = ref<TenantRow[]>([])

  async function load() {
    loading.value = true
    try {
      const result = await request.get<{ tenants: TenantRow[] }>({ url: '/api/v1/admin/tenants/overview' })
      tenants.value = result.tenants || []
    } finally {
      loading.value = false
    }
  }

  onMounted(load)
</script>
