<template>
  <div class="app-container token-stats-page">
    <!-- 筛选栏 -->
    <el-card shadow="never" class="filter-card">
      <el-form :inline="true" size="small">
        <el-form-item label="租户">
          <el-select v-model="query.companyId" placeholder="选择租户" filterable clearable style="width:220px">
            <el-option v-for="c in companyOptions" :key="c.value" :label="c.label" :value="c.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker v-model="dateRange" type="daterange" range-separator="至"
                          start-placeholder="开始日期" end-placeholder="结束日期"
                          value-format="yyyy-MM-dd" style="width:260px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="fetchData">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="16" class="stats-row" v-if="dailyData.length > 0">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-value">{{ totalTokens | formatNumber }}</div>
          <div class="stat-label">总Token消耗</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-value">{{ totalCost | formatMoney }}</div>
          <div class="stat-label">预估费用</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-value">{{ totalRequests | formatNumber }}</div>
          <div class="stat-label">请求次数</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-value">{{ modelData.length }}</div>
          <div class="stat-label">使用模型数</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- Tab：按日 / 按模型 / 按实例 -->
    <el-card shadow="never" style="margin-top:16px">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="按日统计" name="daily">
          <el-table v-loading="loading" :data="dailyData" border>
            <el-table-column prop="date" label="日期" width="120" />
            <el-table-column prop="totalTokens" label="Token数" sortable />
            <el-table-column prop="totalCost" label="预估费用">
              <template slot-scope="scope">{{ scope.row.totalCost | formatMoney }}</template>
            </el-table-column>
            <el-table-column prop="requestCount" label="请求数" />
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="按模型统计" name="model">
          <el-table v-loading="loading" :data="modelData" border>
            <el-table-column prop="model" label="模型" width="220" />
            <el-table-column prop="totalTokens" label="Token数" sortable />
            <el-table-column prop="totalCost" label="预估费用">
              <template slot-scope="scope">{{ scope.row.totalCost | formatMoney }}</template>
            </el-table-column>
            <el-table-column prop="requestCount" label="请求数" />
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="按实例统计" name="instance">
          <el-table v-loading="loading" :data="instanceData" border>
            <el-table-column prop="instanceId" label="实例ID" width="120" />
            <el-table-column prop="totalTokens" label="Token数" sortable />
            <el-table-column prop="totalCost" label="预估费用">
              <template slot-scope="scope">{{ scope.row.totalCost | formatMoney }}</template>
            </el-table-column>
            <el-table-column prop="requestCount" label="请求数" />
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import { getTokenDaily, getTokenByModel, getTokenByInstance } from '@/api/workflow/lobster-token'
import { listAllCompanies } from '@/api/workflow/lobster-admin'

export default {
  name: 'TokenStats',
  filters: {
    formatNumber(val) { return (val || 0).toLocaleString() },
    formatMoney(val) { return '¥' + ((val || 0) / 10000).toFixed(4) }
  },
  data() {
    const end = new Date()
    const start = new Date()
    start.setDate(start.getDate() - 30)
    return {
      loading: false,
      activeTab: 'daily',
      query: { companyId: null, startDate: '', endDate: '' },
      dateRange: [this.formatDate(start), this.formatDate(end)],
      companyOptions: [],
      dailyData: [],
      modelData: [],
      instanceData: []
    }
  },
  computed: {
    totalTokens() { return this.dailyData.reduce((s, r) => s + (r.totalTokens || 0), 0) },
    totalCost() { return this.dailyData.reduce((s, r) => s + (r.totalCost || 0), 0) },
    totalRequests() { return this.dailyData.reduce((s, r) => s + (r.requestCount || 0), 0) }
  },
  mounted() {
    this.fetchCompanies()
  },
  methods: {
    formatDate(d) { return d.toISOString().slice(0, 10) },
    fetchCompanies() {
      listAllCompanies().then(res => {
        this.companyOptions = (res.data || []).map(c => ({ value: c.companyId || c.value, label: c.companyName || c.label || '未知' }))
      }).catch(() => {})
    },
    fetchData() {
      if (!this.query.companyId) { this.$message.warning('请选择租户'); return }
      if (!this.dateRange || this.dateRange.length < 2) { this.$message.warning('请选择日期范围'); return }
      this.query.startDate = this.dateRange[0]
      this.query.endDate = this.dateRange[1]
      this.loading = true
      Promise.all([
        getTokenDaily(this.query),
        getTokenByModel(this.query),
        getTokenByInstance(this.query)
      ]).then(([d, m, i]) => {
        this.dailyData = (d.data && d.data.list) ? d.data.list : []
        this.modelData = (m.data && m.data.list) ? m.data.list : []
        this.instanceData = (i.data && i.data.list) ? i.data.list : []
      }).finally(() => { this.loading = false })
    },
    handleTabClick() {}
  }
}
</script>
<style scoped>
.token-stats-page { padding: 10px; }
.filter-card { margin-bottom: 0; }
.stats-row { margin-top: 16px; }
.stat-card { text-align: center; }
.stat-value { font-size: 28px; font-weight: bold; color: #409EFF; }
.stat-label { font-size: 13px; color: #909399; margin-top: 8px; }
</style>
