<!-- SPEC: PJ2026-010405 云端控制台 / Usage. -->
<!-- Implementation reference: draft-2026-07-13-p0-cloud-console. -->
<!-- Responsibility: 展示账本 authority 的额度、用量、账务与预留。 -->

<script setup lang="ts">
import { CreditCard, LayoutDashboard, ListTodo } from "lucide-vue-next";
import { computed } from "vue";
import DataGrid from "@/components/common/DataGrid.vue";
import type { DataGridColumn } from "@/components/common/DataGrid.vue";
import ViewModeSwitch from "@/components/console/ViewModeSwitch.vue";
import SectionFrame from "@/components/layout/SectionFrame.vue";
import StatusStrip from "@/components/layout/StatusStrip.vue";
import type { ResourceEntitlementSummary, UsageLedgerRow, UsageReservationRow, UsageServiceSummary, UsageSummary } from "@/types";

const props = defineProps<{ summary: UsageSummary }>();
const activeTab = defineModel<"overview" | "ledger" | "reservations">("activeTab", { required: true });
const entitlementColumns: DataGridColumn[] = [{ key: "resource", label: "Resource" }, { key: "status", label: "Status" }, { key: "monthly", label: "Monthly" }, { key: "concurrent", label: "Concurrent" }, { key: "rpm", label: "RPM" }];
const serviceColumns: DataGridColumn[] = [{ key: "service", label: "Service" }, { key: "resource", label: "Resource" }, { key: "credits", label: "Credits", align: "right" }, { key: "quantity", label: "Quantity", align: "right" }, { key: "records", label: "Records", align: "right" }, { key: "lastUsed", label: "Last used" }];
const ledgerColumns: DataGridColumn[] = [{ key: "time", label: "Time" }, { key: "kind", label: "Kind" }, { key: "reason", label: "Reason" }, { key: "delta", label: "Delta", align: "right" }, { key: "balance", label: "Balance", align: "right" }];
const reservationColumns: DataGridColumn[] = [{ key: "reservation", label: "Reservation" }, { key: "service", label: "Service" }, { key: "resource", label: "Resource" }, { key: "credits", label: "Credits", align: "right" }, { key: "expires", label: "Expires" }];
const credits = computed(() => props.summary.credits ?? {});
const usage = computed(() => props.summary.usage ?? {});
const plan = computed(() => props.summary.plan ?? {});
const entitlements = computed(() => props.summary.entitlements ?? []);
const services = computed(() => usage.value.byService ?? []);
const ledgerRows = computed(() => props.summary.ledger?.rows ?? []);
const reservations = computed(() => props.summary.reservations?.active ?? []);
const statusItems = computed(() => [
  { id: "authority", label: "Authority", value: "PK01 user-billing" },
  { id: "plan", label: "Plan status", value: plan.value.status || "active", tone: "ok" as const },
  { id: "records", label: "Records", value: formatNumber(usage.value.recordCount) },
  { id: "reservations", label: "Active reservations", value: formatNumber(props.summary.reservations?.activeCount) }
]);

function formatNumber(value: unknown): string { const number = Number(value ?? 0); return Number.isFinite(number) ? new Intl.NumberFormat("zh-CN").format(number) : "0"; }
function formatSignedCredits(value: unknown): string { const number = Number(value ?? 0); return `${number > 0 ? "+" : ""}${formatNumber(number)}`; }
function formatDate(value: unknown): string { const text = String(value ?? "").trim(); if (!text) return "-"; const date = new Date(text); return Number.isNaN(date.getTime()) ? text : date.toLocaleString("zh-CN", { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" }); }
function entitlementKey(row: ResourceEntitlementSummary): string { return row.id || row.resourceType || "entitlement"; }
function serviceKey(row: UsageServiceSummary): string { return `${row.serviceId}:${row.resourceType || "generic"}`; }
function ledgerKey(row: UsageLedgerRow): string { return row.id; }
function reservationKey(row: UsageReservationRow): string { return row.reservationId; }
</script>

<template>
  <div class="usage-workspace">
    <StatusStrip :items="statusItems" label="用量状态" live="polite" />
    <div class="overview-grid usage-metrics">
      <article class="metric-card"><span>Plan</span><strong>{{ plan.displayName || summary.planId || 'default' }}</strong></article>
      <article class="metric-card"><span>可用 credit</span><strong>{{ formatNumber(credits.available) }}</strong></article>
      <article class="metric-card"><span>余额</span><strong>{{ formatNumber(credits.balance) }}</strong></article>
      <article class="metric-card"><span>已预留</span><strong>{{ formatNumber(credits.reserved) }}</strong></article>
    </div>
    <ViewModeSwitch
      v-model="activeTab"
      :options="[
        { value: 'overview', label: '资源与服务', icon: LayoutDashboard },
        { value: 'ledger', label: `最近账务 ${ledgerRows.length}`, icon: CreditCard },
        { value: 'reservations', label: `预留 ${reservations.length}`, icon: ListTodo },
      ]"
      label="用量详情"
    />

    <template v-if="activeTab === 'overview'">
      <SectionFrame title="资源授权" :description="`${entitlements.length} resources / ${plan.status || 'active'}`" :body-padding="false">
        <DataGrid :columns="entitlementColumns" :rows="entitlements" :row-key="entitlementKey" :interactive="false" density="compact" empty-text="当前 plan 没有资源授权记录。" aria-label="资源授权">
          <template #cell-resource="{ row }"><code>{{ (row as ResourceEntitlementSummary).resourceType }}</code></template>
          <template #cell-status="{ row }"><span class="status-pill" :data-status="(row as ResourceEntitlementSummary).enabled ? 'active' : 'disabled'">{{ (row as ResourceEntitlementSummary).enabled ? 'enabled' : 'disabled' }}</span></template>
          <template #cell-monthly="{ row }">{{ formatNumber((row as ResourceEntitlementSummary).monthlyUsageCredits) }} / {{ (row as ResourceEntitlementSummary).monthlyQuotaUnlimited ? 'unlimited' : formatNumber((row as ResourceEntitlementSummary).monthlyQuotaCredits) }}</template>
          <template #cell-concurrent="{ row }">{{ formatNumber((row as ResourceEntitlementSummary).activeReservations) }} / {{ (row as ResourceEntitlementSummary).concurrencyUnlimited ? 'unlimited' : formatNumber((row as ResourceEntitlementSummary).maxConcurrentReservations) }}</template>
          <template #cell-rpm="{ row }">{{ formatNumber((row as ResourceEntitlementSummary).rpmUsed) }} / {{ (row as ResourceEntitlementSummary).rpmUnlimited ? 'unlimited' : formatNumber((row as ResourceEntitlementSummary).rpmLimit) }}</template>
        </DataGrid>
      </SectionFrame>
      <SectionFrame title="服务用量" :description="`${formatNumber(usage.recordCount)} records / ${formatNumber(usage.totalCredits)} credits`" :body-padding="false">
        <DataGrid :columns="serviceColumns" :rows="services" :row-key="serviceKey" :interactive="false" density="compact" empty-text="暂无服务用量。" aria-label="服务用量">
          <template #cell-service="{ row }"><code>{{ (row as UsageServiceSummary).serviceId }}</code></template><template #cell-resource="{ row }">{{ (row as UsageServiceSummary).resourceType || 'generic' }}</template>
          <template #cell-credits="{ row }">{{ formatNumber((row as UsageServiceSummary).credits) }}</template><template #cell-quantity="{ row }">{{ formatNumber((row as UsageServiceSummary).quantity) }}</template>
          <template #cell-records="{ row }">{{ formatNumber((row as UsageServiceSummary).recordCount) }}</template><template #cell-lastUsed="{ row }">{{ formatDate((row as UsageServiceSummary).lastUsedAt) }}</template>
        </DataGrid>
      </SectionFrame>
    </template>

    <SectionFrame v-else-if="activeTab === 'ledger'" title="最近账务" :description="`${ledgerRows.length} rows`" :body-padding="false">
      <DataGrid :columns="ledgerColumns" :rows="ledgerRows" :row-key="ledgerKey" :interactive="false" density="compact" empty-text="暂无 ledger 记录。" aria-label="最近账务">
        <template #cell-time="{ row }">{{ formatDate((row as UsageLedgerRow).createdAt) }}</template><template #cell-kind="{ row }">{{ (row as UsageLedgerRow).kind }}</template>
        <template #cell-reason="{ row }"><code>{{ (row as UsageLedgerRow).reason }}</code></template><template #cell-delta="{ row }">{{ formatSignedCredits((row as UsageLedgerRow).deltaCredits) }}</template><template #cell-balance="{ row }">{{ formatNumber((row as UsageLedgerRow).balanceAfter) }}</template>
      </DataGrid>
    </SectionFrame>

    <SectionFrame v-else title="Active reservations" :description="`${formatNumber(summary.reservations?.activeCount)} reserved`" :body-padding="false">
      <DataGrid :columns="reservationColumns" :rows="reservations" :row-key="reservationKey" :interactive="false" density="compact" empty-text="当前没有 active reservation。" aria-label="Active reservations">
        <template #cell-reservation="{ row }"><code>{{ (row as UsageReservationRow).reservationId }}</code></template><template #cell-service="{ row }"><code>{{ (row as UsageReservationRow).serviceId }}</code></template>
        <template #cell-resource="{ row }"><code>{{ (row as UsageReservationRow).resourceType || 'generic' }}</code></template><template #cell-credits="{ row }">{{ formatNumber((row as UsageReservationRow).estimatedCredits) }}</template><template #cell-expires="{ row }">{{ formatDate((row as UsageReservationRow).expiresAt) }}</template>
      </DataGrid>
    </SectionFrame>
  </div>
</template>

<style scoped>.usage-workspace { display: grid; gap: 12px; min-width: 0; }</style>
