<!-- SPEC: PJ2026-010405 云端控制台. -->
<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { usageAPI } from "@/api";
import AsyncBoundary from "@/components/common/AsyncBoundary.vue";
import PageCommandBar from "@/components/layout/PageCommandBar.vue";
import UsageWorkspace from "@/components/usage/UsageWorkspace.vue";
import type { UsageSummary } from "@/types";

const summary = ref<UsageSummary | null>(null);
const route = useRoute();
const router = useRouter();
const loading = ref(true);
const error = ref<string | null>(null);
const loaded = ref(false);
const activeTab = computed<"overview" | "ledger" | "reservations">({ get: () => route.query.tab === "ledger" ? "ledger" : route.query.tab === "reservations" ? "reservations" : "overview", set: (value) => { const query = { ...route.query }; if (value === "overview") delete query.tab; else query.tab = value; void router.replace({ query }); } });
const asyncState = computed(() => loading.value ? summary.value ? "refreshing" : "initial-loading" : error.value ? summary.value ? "partial" : "error" : loaded.value ? "ready" : "empty");
onMounted(() => void refresh());
async function refresh(): Promise<void> { loading.value = true; const response = await usageAPI.summary(); if (!response.ok) error.value = response.error ?? `HTTP ${response.status}`; else { summary.value = response.data; error.value = null; } loading.value = false; loaded.value = true; }
</script>

<template>
  <section class="route-stack usage-page">
    <PageCommandBar eyebrow="User" title="用量与配额" description="PK01 PostgreSQL ledger 派生的余额、消费和预留。" />
    <AsyncBoundary :state="asyncState" :has-content="Boolean(summary)" label="加载用户账务 summary" empty-title="暂无用量数据" empty-description="当前账号还没有账务 summary。" error-title="用量接口不可用" :error="error || '请求未完成'" @retry="refresh">
      <UsageWorkspace v-if="summary" v-model:active-tab="activeTab" :summary="summary" />
    </AsyncBoundary>
  </section>
</template>
