<script setup lang="ts">
import * as echarts from 'echarts';
import { onMounted, ref } from 'vue';
import { http } from '../api/http';

const overview = ref<Record<string, number>>({});
const trendEl = ref<HTMLDivElement>();
const providerEl = ref<HTMLDivElement>();

async function load() {
  overview.value = await http.get('/dashboard/overview');
  const trends = (await http.get('/dashboard/trends?days=30')) as any[];
  const providers = (await http.get('/dashboard/providers')) as any[];

  echarts.init(trendEl.value!).setOption({
    tooltip: { trigger: 'axis' },
    legend: { bottom: 0 },
    grid: { left: 42, right: 20, top: 28, bottom: 42 },
    xAxis: { type: 'category', data: trends.map((item) => item.day) },
    yAxis: { type: 'value' },
    series: [
      { name: '消费', type: 'bar', stack: 'credits', data: trends.map((item) => item.consumedCredits) },
      { name: '充值', type: 'line', data: trends.map((item) => item.rechargedCredits) },
    ],
  });

  echarts.init(providerEl.value!).setOption({
    tooltip: { trigger: 'item' },
    series: [
      {
        type: 'pie',
        radius: ['42%', '72%'],
        data: providers.map((item) => ({ name: item.modelName || item.modelId, value: item.credits })),
      },
    ],
  });
}

onMounted(load);
</script>

<template>
  <div>
    <div class="page-head">
      <div>
        <h1>仪表盘</h1>
        <p>全平台租户、积分与模型调用概览</p>
      </div>
    </div>
    <div class="metric-grid">
      <div class="metric"><span>总租户</span><strong>{{ overview.totalTenants || 0 }}</strong></div>
      <div class="metric"><span>活跃租户</span><strong>{{ overview.activeTenants || 0 }}</strong></div>
      <div class="metric"><span>总用户</span><strong>{{ overview.totalUsers || 0 }}</strong></div>
      <div class="metric"><span>今日新增</span><strong>{{ overview.todayNewTenants || 0 }}</strong></div>
      <div class="metric"><span>今日消费</span><strong>{{ overview.todayConsumedCredits || 0 }}</strong></div>
      <div class="metric"><span>今日充值</span><strong>{{ overview.todayRechargedCredits || 0 }}</strong></div>
    </div>
    <div class="panel-grid">
      <div class="panel"><div ref="trendEl" class="chart-box" /></div>
      <div class="panel"><div ref="providerEl" class="chart-box" /></div>
    </div>
  </div>
</template>
