<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">按日/供应商/模型维度的用量与成本统计</p>
      </div>
      <div class="flex items-center gap-2">
        <ElDatePicker v-model="range" type="daterange" value-format="YYYY-MM-DD" :clearable="false" class="w-60" @change="load" />
        <ElButton :loading="loading" @click="load">查询</ElButton>
      </div>
    </div>

    <div class="mb-5 grid grid-cols-2 gap-4 lg:grid-cols-4">
      <ElCard shadow="never">
        <div class="text-g-500 text-sm">总请求</div>
        <b class="mt-2 block text-2xl">{{ totals.requests.toLocaleString() }}</b>
      </ElCard>
      <ElCard shadow="never">
        <div class="text-g-500 text-sm">失败率</div>
        <b class="mt-2 block text-2xl">{{ totals.requests ? ((totals.failed / totals.requests) * 100).toFixed(2) + '%' : '—' }}</b>
      </ElCard>
      <ElCard shadow="never">
        <div class="text-g-500 text-sm">总 Tokens</div>
        <b class="mt-2 block text-2xl">{{ totals.tokens.toLocaleString() }}</b>
      </ElCard>
      <ElCard shadow="never">
        <div class="text-g-500 text-sm">估算成本</div>
        <b class="mt-2 block text-2xl">{{ costText(totals.cost) }}</b>
      </ElCard>
    </div>

    <ElTabs v-model="activeTab">
      <ElTabPane label="按供应商" name="provider">
        <ElTable v-loading="loading" :data="providerRows" row-key="provider">
          <ElTableColumn prop="provider" label="供应商" min-width="180" />
          <ElTableColumn prop="requests" label="请求数" width="120" />
          <ElTableColumn prop="failed" label="失败" width="100" />
          <ElTableColumn prop="tokens" label="Tokens" width="140" />
          <ElTableColumn prop="cost" label="成本" width="140" />
        </ElTable>
      </ElTabPane>
      <ElTabPane label="按模型" name="model">
        <ElTable v-loading="loading" :data="modelRows" row-key="model">
          <ElTableColumn prop="provider" label="供应商" min-width="150" />
          <ElTableColumn prop="model" label="模型" min-width="200" />
          <ElTableColumn prop="requests" label="请求数" width="120" />
          <ElTableColumn prop="failed" label="失败" width="100" />
          <ElTableColumn prop="tokens" label="Tokens" width="140" />
          <ElTableColumn prop="cost" label="成本" width="140" />
        </ElTable>
      </ElTabPane>
      <ElTabPane label="按日期" name="daily">
        <ElTable v-loading="loading" :data="dailyRows" row-key="date">
          <ElTableColumn prop="date" label="日期" width="140" />
          <ElTableColumn prop="requests" label="请求数" width="120" />
          <ElTableColumn prop="failed" label="失败" width="100" />
          <ElTableColumn prop="tokens" label="Tokens" width="140" />
          <ElTableColumn prop="cost" label="成本" width="140" />
        </ElTable>
      </ElTabPane>
    </ElTabs>
  </div>
</template>

<script setup lang="ts">
  import { fetchDailyUsage } from '@/api/audit'

  const loading = ref(false)
  const activeTab = ref('provider')
  const range = ref<[string, string]>([daysAgo(6), today()])
  const dailyUsage = ref<any[]>([])

  function daysAgo(n: number) {
    const d = new Date()
    d.setDate(d.getDate() - n)
    return d.toISOString().slice(0, 10)
  }
  function today() {
    return new Date().toISOString().slice(0, 10)
  }
  function costText(value: number | null | undefined) {
    return value != null && value > 0 ? `USD ${(value / 1e6).toFixed(4)}` : '—'
  }

  const totals = computed(() =>
    dailyUsage.value.reduce(
      (total, row) => ({
        requests: total.requests + row.requests,
        failed: total.failed + row.failed_requests,
        tokens: total.tokens + row.prompt_tokens + row.completion_tokens,
        cost: total.cost + row.cost_microunits
      }),
      { requests: 0, failed: 0, tokens: 0, cost: 0 }
    )
  )

  const providerRows = computed(() => {
    const map = new Map<string, any>()
    for (const row of dailyUsage.value) {
      const key = row.provider_code || '未指定'
      const item = map.get(key) || { provider: key, requests: 0, failed: 0, tokens: 0, cost: 0 }
      item.requests += row.requests
      item.failed += row.failed_requests
      item.tokens += row.prompt_tokens + row.completion_tokens
      item.cost += row.cost_microunits
      map.set(key, item)
    }
    return [...map.values()].sort((a, b) => b.requests - a.requests)
  })

  const modelRows = computed(() => {
    const map = new Map<string, any>()
    for (const row of dailyUsage.value) {
      const key = `${row.provider_code || ''}:${row.model || ''}`
      const item = map.get(key) || { provider: row.provider_code || '未指定', model: row.model || '未指定', requests: 0, failed: 0, tokens: 0, cost: 0 }
      item.requests += row.requests
      item.failed += row.failed_requests
      item.tokens += row.prompt_tokens + row.completion_tokens
      item.cost += row.cost_microunits
      map.set(key, item)
    }
    return [...map.values()].sort((a, b) => b.requests - a.requests)
  })

  const dailyRows = computed(() => {
    const map = new Map<string, any>()
    for (const row of dailyUsage.value) {
      const key = String(row.date).slice(0, 10)
      const item = map.get(key) || { date: key, requests: 0, failed: 0, tokens: 0, cost: 0 }
      item.requests += row.requests
      item.failed += row.failed_requests
      item.tokens += row.prompt_tokens + row.completion_tokens
      item.cost += row.cost_microunits
      map.set(key, item)
    }
    return [...map.values()].sort((a, b) => b.date.localeCompare(a.date))
  })

  async function load() {
    loading.value = true
    try {
      dailyUsage.value = await fetchDailyUsage({ from: range.value[0], to: range.value[1] })
    } finally {
      loading.value = false
    }
  }

  onMounted(load)
</script>
