<template>
  <div class="monitoring-page">
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="page-title">Prompt 模板监控</h1>
          <p class="page-desc">查看 Prompt 模板的使用统计和 Token 消耗</p>
        </div>
        <div class="header-actions">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 280px;"
            @change="loadStats"
          />
          <el-select
            v-model="filterScene"
            placeholder="场景筛选"
            clearable
            style="width: 140px;"
            @change="loadStats"
          >
            <el-option label="对话场景" value="chat" />
            <el-option label="问答场景" value="qa" />
            <el-option label="摘要场景" value="summary" />
            <el-option label="翻译场景" value="translation" />
            <el-option label="代码场景" value="code" />
            <el-option label="自定义场景" value="custom" />
          </el-select>
        </div>
      </div>
    </div>

    <el-row :gutter="20" class="stats-cards">
      <el-col :span="8">
        <el-card shadow="hover" class="stat-card">
          <el-statistic title="总使用次数" :value="stats.totalUsage">
            <template #suffix>
              <span class="stat-suffix">次</span>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="stat-card">
          <el-statistic title="模板数量" :value="stats.templates.length">
            <template #suffix>
              <span class="stat-suffix">个</span>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="stat-card">
          <el-statistic title="场景数量" :value="Object.keys(stats.sceneBreakdown).length">
            <template #suffix>
              <span class="stat-suffix">个</span>
            </template>
          </el-statistic>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20">
      <el-col :span="16">
        <el-card shadow="hover" class="template-stats-card" v-loading="loading">
          <template #header>
            <span>模板使用统计</span>
          </template>
          <el-table :data="stats.templates" stripe style="width: 100%">
            <el-table-column prop="templateName" label="模板名称" min-width="150" />
            <el-table-column prop="scene" label="场景" width="100">
              <template #default="{ row }">
                <el-tag :type="getSceneTagType(row.scene)" size="small">
                  {{ getSceneLabel(row.scene) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="usageCount" label="使用次数" width="100" sortable>
              <template #default="{ row }">
                <el-tag type="primary">{{ row.usageCount }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="avgTokens" label="平均 Token" width="100" sortable>
              <template #default="{ row }">
                {{ row.avgTokens.toFixed(0) }}
              </template>
            </el-table-column>
            <el-table-column prop="avgPromptTokens" label="平均 Prompt Token" width="130">
              <template #default="{ row }">
                {{ row.avgPromptTokens.toFixed(0) }}
              </template>
            </el-table-column>
            <el-table-column prop="avgCompletionTokens" label="平均 Completion Token" width="150">
              <template #default="{ row }">
                {{ row.avgCompletionTokens.toFixed(0) }}
              </template>
            </el-table-column>
            <el-table-column prop="lastUsedTime" label="最后使用时间" width="170">
              <template #default="{ row }">
                {{ row.lastUsedTime ? formatTime(row.lastUsedTime) : '-' }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card shadow="hover" class="scene-breakdown-card">
          <template #header>
            <span>场景分布</span>
          </template>
          <div class="scene-list">
            <div
              v-for="(count, scene) in stats.sceneBreakdown"
              :key="scene"
              class="scene-item"
            >
              <div class="scene-info">
                <el-tag :type="getSceneTagType(scene)" size="small">
                  {{ getSceneLabel(scene) }}
                </el-tag>
                <span class="scene-count">{{ count }} 次</span>
              </div>
              <el-progress
                :percentage="getPercentage(count)"
                :stroke-width="8"
                :show-text="false"
              />
            </div>
            <el-empty v-if="Object.keys(stats.sceneBreakdown).length === 0" description="暂无数据" />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  getPromptTemplateStats,
  type PromptTemplateStatsResponse
} from '@/api/monitoring'

const loading = ref(false)
const dateRange = ref<[string, string] | null>(null)
const filterScene = ref('')

const stats = ref<PromptTemplateStatsResponse>({
  totalUsage: 0,
  templates: [],
  sceneBreakdown: {}
})

const getSceneLabel = (scene: string) => {
  const labels: Record<string, string> = {
    chat: '对话场景',
    qa: '问答场景',
    summary: '摘要场景',
    translation: '翻译场景',
    code: '代码场景',
    custom: '自定义场景'
  }
  return labels[scene] || scene
}

const getSceneTagType = (scene: string): '' | 'success' | 'warning' | 'danger' | 'info' => {
  const typeMap: Record<string, '' | 'success' | 'warning' | 'danger' | 'info'> = {
    chat: '',
    qa: 'success',
    summary: 'warning',
    translation: 'danger',
    code: 'info',
    custom: 'info'
  }
  return typeMap[scene] || 'info'
}

const formatTime = (time: string) => {
  if (!time) return '-'
  return new Date(time).toLocaleString('zh-CN')
}

const getPercentage = (count: number) => {
  if (stats.value.totalUsage === 0) return 0
  return Math.round((count / stats.value.totalUsage) * 100)
}

const loadStats = async () => {
  loading.value = true
  try {
    const params: Record<string, string | undefined> = {}
    if (dateRange.value) {
      params.startDate = dateRange.value[0]
      params.endDate = dateRange.value[1]
    }
    if (filterScene.value) {
      params.scene = filterScene.value
    }
    stats.value = await getPromptTemplateStats(params)
  } catch (error) {
    ElMessage.error('加载统计数据失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadStats()
})
</script>

<style scoped>
.monitoring-page {
  padding: 24px;
}

.page-header {
  margin-bottom: 24px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
  flex-wrap: wrap;
}

.title-section {
  flex: 1;
  min-width: 300px;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 700;
  color: var(--el-text-color-primary);
}

.page-desc {
  margin: 0;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.stats-cards {
  margin-bottom: 24px;
}

.stat-card {
  text-align: center;
  padding: 12px 0;
}

.stat-suffix {
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.template-stats-card {
  border-radius: 8px;
}

.scene-breakdown-card {
  border-radius: 8px;
}

.scene-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.scene-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.scene-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.scene-count {
  font-size: 14px;
  color: var(--el-text-color-secondary);
}
</style>
