<template>
  <AppShell>
    <div class="space-y-4">
      <h2 class="text-lg font-semibold">
        {{ adminMode ? '用量（全局）' : '我的用量' }}
      </h2>
      <div class="flex gap-2 items-center flex-wrap">
        <NDatePicker v-model:value="range" type="daterange" clearable />
        <NSelect
          v-if="adminMode"
          v-model:value="groupBy"
          :options="groupOpts"
          style="width: 160px"
        />
      </div>
      <NDataTable :data="rows" :columns="columns" />
    </div>
  </AppShell>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { NDataTable, NDatePicker, NSelect } from 'naive-ui'
import type { DataTableColumns } from 'naive-ui'

import AppShell from '@/layouts/AppShell.vue'
import { llmAdminApi, type AdminUsageGroupBy, type AdminUsageItem } from '@/api/llmAdmin'
import { chatApi, type UsageDailyItem } from '@/api/chat'
import { formatDate } from '@/utils/date'

interface Props {
  adminMode?: boolean
}
const props = withDefaults(defineProps<Props>(), { adminMode: false })

const now = Date.now()
const monthAgo = now - 30 * 86400_000
const range = ref<[number, number] | null>([monthAgo, now])
const groupBy = ref<AdminUsageGroupBy>('day')
const groupOpts: { label: string; value: AdminUsageGroupBy }[] = [
  { label: '按用户', value: 'user' },
  { label: '按模型', value: 'model' },
  { label: '按天', value: 'day' },
]

type Row = AdminUsageItem | UsageDailyItem
const rows = ref<Row[]>([])

const columns = computed<DataTableColumns<Row>>(() => {
  const tokenCols: DataTableColumns<Row> = [
    { title: 'Prompt', key: 'prompt_tokens' },
    { title: 'Completion', key: 'completion_tokens' },
    { title: 'Thinking', key: 'thinking_tokens' },
    {
      title: 'Cost USD',
      key: 'cost_usd',
      render: (r) => Number(r.cost_usd ?? 0).toFixed(4),
    },
  ]
  if (props.adminMode) {
    const labelCol: DataTableColumns<Row>[number] = {
      title: groupBy.value === 'user' ? '用户' : groupBy.value === 'model' ? '模型' : '日期',
      key: 'key',
      render: (r) => {
        const k = (r as AdminUsageItem).key
        if (groupBy.value === 'day') {
          return formatDate(k)
        }
        return k
      },
    }
    return [labelCol, ...tokenCols]
  }
  return [
    {
      title: '日期',
      key: 'day',
      render: (r) => formatDate((r as UsageDailyItem).day),
    },
    ...tokenCols,
  ]
})

async function reload() {
  const r = range.value
  if (!r) {
    rows.value = []
    return
  }
  const from = new Date(r[0]).toISOString()
  const to = new Date(r[1]).toISOString()
  if (props.adminMode) {
    rows.value = await llmAdminApi.adminUsage(from, to, groupBy.value)
  } else {
    rows.value = await chatApi.myDailyUsage(from, to)
  }
}

onMounted(reload)
watch([range, groupBy], reload)
</script>
