<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>
      <ElTabPane label="工具调用" name="tools">
        <ElTable v-loading="loading" :data="toolRows" row-key="code">
          <ElTableColumn prop="name" label="工具" min-width="160" />
          <ElTableColumn prop="code" label="编码" min-width="140" />
          <ElTableColumn prop="requests" label="调用数" width="110" />
          <ElTableColumn prop="success" label="成功" width="100" />
          <ElTableColumn prop="failed" label="失败" width="100" />
          <ElTableColumn prop="avg_latency_ms" label="平均延迟(ms)" width="130" />
        </ElTable>
      </ElTabPane>
      <ElTabPane label="审批授权" name="approvals">
        <ElTable v-loading="loading" :data="approvalRows" row-key="key">
          <ElTableColumn label="申请类型" width="140">
            <template #default="{ row }">{{ ({ model: '模型', resource: '资源/渠道', tool: '工具' } as Record<string, string>)[row.kind as string] || row.kind }}</template>
          </ElTableColumn>
          <ElTableColumn label="状态" width="120">
            <template #default="{ row }">{{ ({ pending: '待审批', approved: '已通过', rejected: '已驳回', cancelled: '已取消' } as Record<string, string>)[row.status as string] || row.status }}</template>
          </ElTableColumn>
          <ElTableColumn prop="count" label="数量" width="110" />
        </ElTable>
      </ElTabPane>
      <ElTabPane label="安全事件" name="security">
        <div class="mb-4 grid grid-cols-3 gap-4">
          <ElCard shadow="never"><div class="text-g-500 text-sm">登录成功</div><b class="mt-2 block text-2xl">{{ securityStats.success || 0 }}</b></ElCard>
          <ElCard shadow="never"><div class="text-g-500 text-sm">登录失败</div><b class="mt-2 block text-2xl">{{ securityStats.failed || 0 }}</b></ElCard>
          <ElCard shadow="never"><div class="text-g-500 text-sm">来源 IP 数</div><b class="mt-2 block text-2xl">{{ securityStats.ips || 0 }}</b></ElCard>
        </div>
        <ElTable v-loading="loading" :data="securityTopIPs" row-key="ip">
          <ElTableColumn prop="ip" label="来源 IP" min-width="220" />
          <ElTableColumn prop="count" label="登录次数" width="140" />
        </ElTable>
      </ElTabPane>
    </ElTabs>
  </div>
</template>

<script setup lang="ts">
  import { fetchDailyUsage } from '@/api/audit'
  import { fetchApprovalReport, fetchSecurityReport, fetchToolUsageReport } from '@/api/governance'

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

  function fmtLocal(d: Date) {
    const pad = (v: number) => String(v).padStart(2, '0')
    return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
  }
  function daysAgo(n: number) {
    const d = new Date()
    d.setDate(d.getDate() - n)
    return fmtLocal(d)
  }
  function today() {
    return fmtLocal(new Date())
  }
  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))
  })

  const toolRows = ref<any[]>([])
  const approvalRows = ref<any[]>([])
  const securityTopIPs = ref<any[]>([])
  const securityStats = ref<{ success: number; failed: number; ips: number }>({ success: 0, failed: 0, ips: 0 })

  async function load() {
    loading.value = true
    try {
      const params = { from: range.value[0], to: range.value[1] }
      dailyUsage.value = await fetchDailyUsage(params)
      toolRows.value = await fetchToolUsageReport(params)
      approvalRows.value = await fetchApprovalReport(params)
      const security = await fetchSecurityReport(params)
      securityTopIPs.value = security.top_ips || []
      const stats = { success: 0, failed: 0, ips: 0 }
      for (const item of security.login_stats || []) {
        if (item.success) stats.success += item.count
        else stats.failed += item.count
        stats.ips += item.distinct_ips
      }
      securityStats.value = stats
    } finally {
      loading.value = false
    }
  }

  onMounted(load)
</script>
