feat: 新增多token用量查看

This commit is contained in:
Gsh
2025-11-29 22:48:23 +08:00
parent 94c52c62fe
commit 55469708f0
4 changed files with 825 additions and 120 deletions

View File

@@ -3,7 +3,6 @@ import { del, get, post, put } from '@/utils/request';
// 获取当前用户的模型列表
export function getModelList() {
// return get<GetSessionListVO[]>('/system/model/modelList');
return get<GetSessionListVO[]>('/ai-chat/model').json();
}
// 申请ApiKey
@@ -21,72 +20,36 @@ export function getRechargeLog() {
}
// 查询用户近7天token消耗
export function getLast7DaysTokenUsage() {
return get<any>('/usage-statistics/last7Days-token-usage').json();
// tokenId: 可选传入则查询该token的用量不传则查询全部
export function getLast7DaysTokenUsage(tokenId?: string) {
const url = tokenId
? `/usage-statistics/last7Days-token-usage?tokenId=${tokenId}`
: '/usage-statistics/last7Days-token-usage';
return get<any>(url).json();
}
// 查询用户token消耗各模型占比
export function getModelTokenUsage() {
return get<any>('/usage-statistics/model-token-usage').json();
// tokenId: 可选传入则查询该token的用量不传则查询全部
export function getModelTokenUsage(tokenId?: string) {
const url = tokenId
? `/usage-statistics/model-token-usage?tokenId=${tokenId}`
: '/usage-statistics/model-token-usage';
return get<any>(url).json();
}
// 以下为新增接口
// 获取当前用户得token列表
export function getTokenList() {
return get<any>('/token/list').json();
}
/*
返回数据:
[
{
"id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"name": "string",
"apiKey": "string",
"expireTime": "2025-11-29T07:34:23.850Z",
"premiumQuotaLimit": 0,
"premiumUsedQuota": 0,
"isDisabled": true,
"creationTime": "2025-11-29T07:34:23.850Z"
}
] */
// 创建token
export function createToken(data: any) {
return post<any>('/token', data).json();
}
/*
data:
{
"name": "string",
"expireTime": "2025-11-29T07:35:10.458Z",
"premiumQuotaLimit": 0
} */
/*
返回:
{
"id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"name": "string",
"apiKey": "string",
"expireTime": "2025-11-29T07:35:10.459Z",
"premiumQuotaLimit": 0,
"premiumUsedQuota": 0,
"isDisabled": true,
"creationTime": "2025-11-29T07:35:10.459Z"
} */
// 编辑token
export function editToken(data: any) {
return put('/token', data).json();
}
/*
data:
{
"id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"name": "string",
"expireTime": "2025-11-29T07:36:49.589Z",
"premiumQuotaLimit": 0
}
*/
// 删除token
export function deleteToken(id: string) {
@@ -102,3 +65,31 @@ export function enableToken(id: string) {
export function disableToken(id: string) {
return post(`/token/${id}/disable`).json();
}
// 新增接口2
// 获取可选择的token信息
export function getSelectableTokenInfo() {
return get<any>('/token/select-list').json();
}
/*
返回数据
[
{
"tokenId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"name": "string",
"isDisabled": true
}
] */
// 获取当前用户尊享包不同token用量占比饼图
export function getPremiumPackageTokenUsage() {
return get<any>('/usage-statistics/premium-token-usage/by-token').json();
}
/* 返回数据
[
{
"tokenId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"tokenName": "string",
"tokens": 0,
"percentage": 0
}
] */

View File

@@ -1,15 +1,15 @@
<script lang="ts" setup>
import { Plus, Refresh, Delete, Edit, View, Hide, DocumentCopy, Check, Close, Key } from '@element-plus/icons-vue';
import { Check, Close, Delete, DocumentCopy, Edit, Hide, Key, Plus, Refresh, View } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { onMounted, ref, computed } from 'vue';
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import {
getTokenList,
createToken,
editToken,
deleteToken,
disableToken,
editToken,
enableToken,
disableToken
getTokenList,
} from '@/api/model/index.ts';
import { isUserVip } from '@/utils/user';
import TokenFormDialog from './TokenFormDialog.vue';
@@ -42,7 +42,7 @@ const currentFormData = ref<TokenFormData>({
name: '',
expireTime: '',
premiumQuotaLimit: 0,
quotaUnit: '万'
quotaUnit: '万',
});
const router = useRouter();
@@ -55,15 +55,17 @@ async function fetchTokenList() {
loading.value = true;
const res = await getTokenList();
if (res.data) {
tokenList.value = res.data.map((item: TokenItem) => ({
tokenList.value = res.data.items.map((item: TokenItem) => ({
...item,
showKey: false
showKey: false,
}));
}
} catch (error) {
}
catch (error) {
console.error('获取Token列表失败:', error);
ElMessage.error('获取Token列表失败');
} finally {
}
finally {
loading.value = false;
}
}
@@ -106,7 +108,7 @@ function showCreateDialog() {
name: '',
expireTime: '',
premiumQuotaLimit: 0,
quotaUnit: '万'
quotaUnit: '万',
};
showFormDialog.value = true;
}
@@ -119,14 +121,15 @@ function showEditDialog(token: TokenItem) {
name: token.name,
expireTime: token.expireTime,
premiumQuotaLimit: token.premiumQuotaLimit,
quotaUnit: '万'
quotaUnit: '万',
};
showFormDialog.value = true;
}
// 处理表单提交(带防抖)
async function handleFormSubmit(data: TokenFormData) {
if (loading.value) return;
if (loading.value)
return;
try {
loading.value = true;
@@ -134,30 +137,34 @@ async function handleFormSubmit(data: TokenFormData) {
id: data.id,
name: data.name,
expireTime: data.expireTime || null,
premiumQuotaLimit: data.premiumQuotaLimit || 0
premiumQuotaLimit: data.premiumQuotaLimit || 0,
};
if (formMode.value === 'create') {
await createToken(submitData);
ElMessage.success('Token创建成功');
} else {
}
else {
await editToken(submitData);
ElMessage.success('Token更新成功');
}
showFormDialog.value = false;
await fetchTokenList();
} catch (error) {
}
catch (error) {
console.error('操作失败:', error);
ElMessage.error(formMode.value === 'create' ? '创建Token失败' : '编辑Token失败');
} finally {
}
finally {
loading.value = false;
}
}
// 删除Token带防抖
async function handleDelete(row: TokenItem) {
if (operatingTokenId.value === row.id) return;
if (operatingTokenId.value === row.id)
return;
try {
await ElMessageBox.confirm(
@@ -167,41 +174,47 @@ async function handleDelete(row: TokenItem) {
confirmButtonText: '确定删除',
cancelButtonText: '取消',
type: 'warning',
confirmButtonClass: 'el-button--danger'
}
confirmButtonClass: 'el-button--danger',
},
);
operatingTokenId.value = row.id;
await deleteToken(row.id);
ElMessage.success('Token已删除');
await fetchTokenList();
} catch (error) {
}
catch (error) {
if (error !== 'cancel') {
ElMessage.error('删除失败');
}
} finally {
}
finally {
operatingTokenId.value = '';
}
}
// 启用/禁用Token带防抖
async function handleToggle(row: TokenItem) {
if (operatingTokenId.value === row.id) return;
if (operatingTokenId.value === row.id)
return;
try {
operatingTokenId.value = row.id;
if (row.isDisabled) {
await enableToken(row.id);
ElMessage.success(`Token "${row.name}" 已启用`);
} else {
}
else {
await disableToken(row.id);
ElMessage.success(`Token "${row.name}" 已禁用`);
}
await fetchTokenList();
} catch (error) {
}
catch (error) {
console.error('操作失败:', error);
ElMessage.error('操作失败');
} finally {
}
finally {
operatingTokenId.value = '';
}
}
@@ -220,20 +233,22 @@ function copyApiKey(apiKey: string, name: string) {
// 格式化日期
function formatDateTime(dateStr: string | null | undefined) {
if (!dateStr) return '-';
if (!dateStr)
return '-';
const date = new Date(dateStr);
return date.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit'
minute: '2-digit',
});
}
// 格式化配额数字
function formatQuota(num: number | null | undefined): string {
if (num == null || num === 0) return '0';
if (num == null || num === 0)
return '0';
if (num >= 100000000) {
return `${(num / 100000000).toFixed(2).replace(/\.?0+$/, '')} 亿`;
}
@@ -248,14 +263,17 @@ function formatQuota(num: number | null | undefined): string {
// 计算配额使用百分比
function getQuotaPercentage(used: number | null | undefined, limit: number | null | undefined) {
if (limit == null || limit === 0 || used == null) return 0;
if (limit == null || limit === 0 || used == null)
return 0;
return Math.min((used / limit) * 100, 100);
}
// 获取配额状态颜色
function getQuotaColor(percentage: number) {
if (percentage >= 90) return '#f56c6c';
if (percentage >= 70) return '#e6a23c';
if (percentage >= 90)
return '#f56c6c';
if (percentage >= 70)
return '#e6a23c';
return '#67c23a';
}
@@ -359,7 +377,9 @@ onMounted(async () => {
<template #default="{ row }">
<div class="key-cell">
<div class="key-content">
<el-icon class="key-icon"><i-ep-key /></el-icon>
<el-icon class="key-icon">
<i-ep-key />
</el-icon>
<span class="key-text">
{{ row.showKey ? row.apiKey : '••••••••••••••••••••••••••••••••' }}
</span>
@@ -426,7 +446,9 @@ onMounted(async () => {
>
<template #default="{ row }">
<div v-if="row.expireTime" class="time-cell">
<el-icon class="time-icon"><i-ep-timer /></el-icon>
<el-icon class="time-icon">
<i-ep-timer />
</el-icon>
<span>{{ formatDateTime(row.expireTime) }}</span>
</div>
<el-tag v-else type="success" size="default" effect="light" class="never-expire-tag">
@@ -472,7 +494,9 @@ onMounted(async () => {
>
<template #default="{ row }">
<div class="time-cell">
<el-icon class="time-icon"><i-ep-clock /></el-icon>
<el-icon class="time-icon">
<i-ep-clock />
</el-icon>
<span>{{ formatDateTime(row.creationTime) }}</span>
</div>
</template>

View File

@@ -1,7 +1,27 @@
<script lang="ts" setup>
import { Clock, Coin, TrophyBase, WarningFilled } from '@element-plus/icons-vue';
import { PieChart as EPieChart } from 'echarts/charts';
import {
GraphicComponent,
LegendComponent,
TitleComponent,
TooltipComponent,
} from 'echarts/components';
import * as echarts from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { getPremiumPackageTokenUsage } from '@/api';
import { showProductPackage } from '@/utils/product-package.ts';
// 注册必要的组件
echarts.use([
EPieChart,
TitleComponent,
TooltipComponent,
LegendComponent,
GraphicComponent,
CanvasRenderer,
]);
// Props
interface Props {
packageData: {
@@ -24,6 +44,12 @@ const emit = defineEmits<{
refresh: [];
}>();
// 饼图相关
const tokenPieChart = ref(null);
let tokenPieChartInstance: any = null;
const tokenUsageData = ref<any[]>([]);
const tokenUsageLoading = ref(false);
// 计算属性
const usagePercent = computed(() => {
if (props.packageData.totalQuota === 0)
@@ -64,6 +90,193 @@ function formatRawNumber(num: number): string {
function onProductPackage() {
showProductPackage();
}
// 获取Token用量数据
async function fetchTokenUsageData() {
try {
tokenUsageLoading.value = true;
const res = await getPremiumPackageTokenUsage();
if (res.data) {
tokenUsageData.value = res.data;
updateTokenPieChart();
}
}
catch (error) {
console.error('获取Token用量数据失败:', error);
}
finally {
tokenUsageLoading.value = false;
}
}
// 初始化Token饼图
function initTokenPieChart() {
if (tokenPieChart.value) {
tokenPieChartInstance = echarts.init(tokenPieChart.value);
}
window.addEventListener('resize', resizeTokenPieChart);
}
// 更新Token饼图
function updateTokenPieChart() {
if (!tokenPieChartInstance)
return;
// 空数据状态
if (tokenUsageData.value.length === 0) {
const emptyOption = {
graphic: [
{
type: 'group',
left: 'center',
top: 'center',
children: [
{
type: 'circle',
shape: {
r: 80,
},
style: {
fill: '#f5f7fa',
stroke: '#e9ecef',
lineWidth: 2,
},
},
{
type: 'text',
style: {
text: '📊',
fontSize: 48,
x: -24,
y: -40,
},
},
{
type: 'text',
style: {
text: '暂无数据',
fontSize: 18,
fontWeight: 'bold',
fill: '#909399',
x: -36,
y: 20,
},
},
{
type: 'text',
style: {
text: '还没有Token使用记录',
fontSize: 14,
fill: '#c0c4cc',
x: -70,
y: 50,
},
},
],
},
],
};
tokenPieChartInstance.setOption(emptyOption, true);
return;
}
const data = tokenUsageData.value.map(item => ({
name: item.tokenName,
value: item.tokens,
}));
const option = {
graphic: [],
tooltip: {
trigger: 'item',
formatter: '{a} <br/>{b}: {c} tokens ({d}%)',
},
legend: {
show: false, // 隐藏图例,使用标签线代替
},
series: [
{
name: 'Token用量',
type: 'pie',
radius: ['50%', '70%'],
center: ['50%', '50%'],
avoidLabelOverlap: true,
itemStyle: {
borderRadius: 10,
borderColor: '#fff',
borderWidth: 2,
},
label: {
show: true,
position: 'outside',
formatter: (params: any) => {
const item = tokenUsageData.value.find(d => d.tokenName === params.name);
const percentage = item?.percentage || 0;
return `${params.name}: ${percentage.toFixed(1)}%`;
},
fontSize: 13,
fontWeight: 600,
color: '#333',
},
emphasis: {
label: {
show: true,
fontSize: 16,
fontWeight: 'bold',
},
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.3)',
},
},
labelLine: {
show: true,
length: 15,
length2: 10,
lineStyle: {
width: 1.5,
},
},
data,
},
],
};
tokenPieChartInstance.setOption(option, true);
}
// 调整饼图大小
function resizeTokenPieChart() {
tokenPieChartInstance?.resize();
}
// 根据索引获取Token颜色
function getTokenColor(index: number) {
const colors = [
'#667eea',
'#764ba2',
'#f093fb',
'#f5576c',
'#4facfe',
'#00f2fe',
'#43e97b',
'#38f9d7',
'#fa709a',
'#fee140',
];
return colors[index % colors.length];
}
onMounted(() => {
initTokenPieChart();
fetchTokenUsageData();
});
onBeforeUnmount(() => {
window.removeEventListener('resize', resizeTokenPieChart);
tokenPieChartInstance?.dispose();
});
</script>
<template>
@@ -231,6 +444,92 @@ function onProductPackage() {
</el-alert>
</div>
</el-card>
<!-- Token用量占比卡片 -->
<el-card v-loading="tokenUsageLoading" class="package-card token-usage-card" shadow="hover">
<template #header>
<div class="card-header">
<div class="card-header-left">
<el-icon class="header-icon token-icon">
<i-ep-pie-chart />
</el-icon>
<div class="header-text">
<span class="header-title">各Token用量占比</span>
<span class="header-subtitle">Premium Token Usage Distribution</span>
</div>
</div>
</div>
</template>
<div class="token-usage-content">
<div class="chart-container-wrapper">
<div ref="tokenPieChart" class="token-pie-chart" />
</div>
<!-- Token统计列表 -->
<div v-if="tokenUsageData.length > 0" class="token-stats-list">
<div
v-for="(item, index) in tokenUsageData"
:key="item.tokenId"
class="token-stat-item"
>
<div class="token-stat-header">
<div class="token-rank">
<span class="rank-badge" :class="`rank-${index + 1}`">#{{ index + 1 }}</span>
</div>
<div class="token-name">
<el-icon><i-ep-key /></el-icon>
<span>{{ item.tokenName }}</span>
</div>
</div>
<div class="token-stat-data">
<div class="stat-tokens">
<span class="label">用量:</span>
<span class="value">{{ item.tokens.toLocaleString() }}</span>
<span class="unit">tokens</span>
</div>
<div class="stat-percentage">
<el-progress
:percentage="item.percentage"
:color="getTokenColor(index)"
:stroke-width="8"
:show-text="true"
/>
</div>
</div>
</div>
</div>
<!-- 空状态 -->
<el-empty
v-else
description="暂无Token使用数据"
class="token-empty-state"
:image-size="120"
>
<template #image>
<div class="custom-empty-image">
<el-icon class="empty-main-icon"><i-ep-pie-chart /></el-icon>
<div class="empty-decoration">
<div class="decoration-circle" />
<div class="decoration-circle" />
<div class="decoration-circle" />
</div>
</div>
</template>
<template #description>
<div class="empty-description">
<h3 class="empty-title">暂无Token使用数据</h3>
<p class="empty-text">当您开始使用Token后这里将展示各Token的用量占比统计</p>
<div class="empty-tips">
<el-icon><i-ep-info-filled /></el-icon>
<span>创建并使用Token后即可查看详细的用量分析</span>
</div>
</div>
</template>
</el-empty>
</div>
</el-card>
</div>
</template>
@@ -495,6 +794,270 @@ function onProductPackage() {
font-size: 13px;
}
/* Token用量占比卡片 */
.token-usage-card {
margin-top: 24px;
}
.token-icon {
background: linear-gradient(135deg, #e0f2fe 0%, #bae6fd 100%);
color: #0284c7;
}
.token-usage-content {
display: flex;
flex-direction: column;
gap: 24px;
}
.chart-container-wrapper {
width: 100%;
background: linear-gradient(135deg, #fafbfc 0%, #f5f6f8 100%);
border-radius: 12px;
padding: 20px;
}
.token-pie-chart {
width: 100%;
height: 400px;
}
/* Token统计列表 */
.token-stats-list {
display: flex;
flex-direction: column;
gap: 16px;
}
.token-stat-item {
padding: 16px;
background: linear-gradient(135deg, #fafbfc 0%, #ffffff 100%);
border-radius: 12px;
border: 1px solid #f0f2f5;
transition: all 0.3s;
&:hover {
border-color: #667eea;
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.1);
transform: translateY(-2px);
}
}
.token-stat-header {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 12px;
}
.token-rank {
flex-shrink: 0;
}
.rank-badge {
display: inline-flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
border-radius: 8px;
font-size: 14px;
font-weight: 700;
color: white;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
&.rank-1 {
background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
}
&.rank-2 {
background: linear-gradient(135deg, #94a3b8 0%, #64748b 100%);
}
&.rank-3 {
background: linear-gradient(135deg, #fb923c 0%, #ea580c 100%);
}
}
.token-name {
display: flex;
align-items: center;
gap: 8px;
flex: 1;
font-size: 16px;
font-weight: 600;
color: #1a1a1a;
.el-icon {
color: #667eea;
font-size: 18px;
}
}
.token-stat-data {
display: flex;
flex-direction: column;
gap: 12px;
}
.stat-tokens {
display: flex;
align-items: baseline;
gap: 6px;
font-size: 14px;
.label {
color: #909399;
}
.value {
font-size: 20px;
font-weight: 700;
color: #667eea;
}
.unit {
color: #909399;
font-size: 12px;
}
}
.stat-percentage {
:deep(.el-progress__text) {
font-size: 14px !important;
font-weight: 700;
}
}
/* 空状态 */
.token-empty-state {
padding: 60px 20px;
:deep(.el-empty__image) {
width: auto;
}
}
.custom-empty-image {
position: relative;
display: flex;
align-items: center;
justify-content: center;
width: 140px;
height: 140px;
margin: 0 auto;
}
.empty-main-icon {
font-size: 80px;
color: #667eea;
position: relative;
z-index: 2;
animation: float 3s ease-in-out infinite;
}
.empty-decoration {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
}
.decoration-circle {
position: absolute;
border-radius: 50%;
background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
&:nth-child(1) {
width: 60px;
height: 60px;
top: 10%;
left: 10%;
animation: pulse 2s ease-in-out infinite;
}
&:nth-child(2) {
width: 40px;
height: 40px;
bottom: 20%;
right: 15%;
animation: pulse 2s ease-in-out infinite 0.5s;
}
&:nth-child(3) {
width: 30px;
height: 30px;
top: 60%;
right: 5%;
animation: pulse 2s ease-in-out infinite 1s;
}
}
@keyframes float {
0%, 100% {
transform: translateY(0);
}
50% {
transform: translateY(-10px);
}
}
@keyframes pulse {
0%, 100% {
transform: scale(1);
opacity: 0.6;
}
50% {
transform: scale(1.2);
opacity: 0.3;
}
}
.empty-description {
display: flex;
flex-direction: column;
align-items: center;
gap: 12px;
margin-top: 20px;
}
.empty-title {
margin: 0;
font-size: 18px;
font-weight: 600;
color: #303133;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.empty-text {
margin: 0;
font-size: 14px;
color: #606266;
line-height: 1.6;
max-width: 360px;
}
.empty-tips {
display: flex;
align-items: center;
gap: 6px;
padding: 10px 16px;
background: linear-gradient(135deg, #f0f4ff 0%, #e8f0fe 100%);
border-radius: 8px;
font-size: 13px;
color: #667eea;
margin-top: 8px;
.el-icon {
font-size: 16px;
flex-shrink: 0;
}
}
/* 警告卡片 */
.warning-card {
border-radius: 12px;

View File

@@ -11,7 +11,7 @@ import {
} from 'echarts/components';
import * as echarts from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { getLast7DaysTokenUsage, getModelTokenUsage } from '@/api';
import { getLast7DaysTokenUsage, getModelTokenUsage, getSelectableTokenInfo } from '@/api';
// 注册必要的组件
echarts.use([
@@ -48,16 +48,53 @@ const totalTokens = ref(0);
const usageData = ref<any[]>([]);
const modelUsageData = ref<any[]>([]);
// Token选择相关
const selectedTokenId = ref<string>(''); // 空字符串表示查询全部
const tokenOptions = ref<any[]>([]);
const tokenOptionsLoading = ref(false);
// 计算属性:是否有模型数据
const hasModelData = computed(() => modelUsageData.value.length > 0);
// 计算属性当前选择的token名称
const selectedTokenName = computed(() => {
if (!selectedTokenId.value) return '全部Token';
const token = tokenOptions.value.find(t => t.tokenId === selectedTokenId.value);
return token?.name || '未知Token';
});
// 获取可选择的Token列表
async function fetchTokenOptions() {
try {
tokenOptionsLoading.value = true;
const res = await getSelectableTokenInfo();
if (res.data) {
// 不再过滤禁用的token全部显示
tokenOptions.value = res.data;
}
}
catch (error) {
console.error('获取Token列表失败:', error);
ElMessage.error('获取Token列表失败');
}
finally {
tokenOptionsLoading.value = false;
}
}
// Token选择变化
function handleTokenChange() {
fetchUsageData();
}
// 获取用量数据
async function fetchUsageData() {
loading.value = true;
try {
const tokenId = selectedTokenId.value || undefined;
const [res, res2] = await Promise.all([
getLast7DaysTokenUsage(),
getModelTokenUsage(),
getLast7DaysTokenUsage(tokenId),
getModelTokenUsage(tokenId),
]);
usageData.value = res.data || [];
@@ -235,49 +272,47 @@ function updatePieChart() {
formatter: '{a} <br/>{b}: {c} tokens ({d}%)',
},
legend: {
orient: isManyItems ? 'vertical' : 'horizontal',
right: isManyItems ? 10 : 'auto',
bottom: isManyItems ? 0 : 10,
type: isManyItems ? 'scroll' : 'plain',
pageIconColor: '#3a4de9',
pageIconInactiveColor: '#ccc',
pageTextStyle: { color: '#333' },
itemGap: isSmallContainer ? 5 : 10,
itemWidth: isSmallContainer ? 15 : 25,
itemHeight: isSmallContainer ? 10 : 14,
textStyle: {
fontSize: isSmallContainer ? 10 : 12,
},
formatter(name: string) {
return name.length > 15 ? `${name.substring(0, 12)}...` : name;
},
data: data.map(item => item.name),
show: false, // 隐藏图例,使用标签线代替
},
series: [
{
name: '模型用量',
type: 'pie',
radius: ['50%', '70%'],
center: isManyItems ? ['40%', '50%'] : ['50%', '50%'],
avoidLabelOverlap: false,
center: ['50%', '50%'],
avoidLabelOverlap: true,
itemStyle: {
borderRadius: 10,
borderColor: '#fff',
borderWidth: 2,
},
label: {
show: false,
position: 'center',
show: true,
position: 'outside',
formatter: '{b}: {d}%',
fontSize: 13,
fontWeight: 600,
color: '#333',
},
emphasis: {
label: {
show: true,
fontSize: '18',
fontSize: 16,
fontWeight: 'bold',
},
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.3)',
},
},
labelLine: {
show: false,
show: true,
length: 15,
length2: 10,
lineStyle: {
width: 1.5,
},
},
data,
},
@@ -453,6 +488,7 @@ watch([pieContainerSize.width, barContainerSize.width], () => {
onMounted(() => {
initCharts();
fetchTokenOptions();
fetchUsageData();
});
@@ -475,19 +511,54 @@ onBeforeUnmount(() => {
<el-icon><PieChart /></el-icon>
Token用量统计
</h2>
<el-button
:icon="FullScreen"
circle
plain
size="small"
@click="toggleFullscreen"
/>
<div class="header-actions">
<el-select
v-model="selectedTokenId"
placeholder="选择Token"
clearable
filterable
:loading="tokenOptionsLoading"
class="token-selector"
@change="handleTokenChange"
>
<el-option label="全部Token" value="">
<div class="token-option">
<el-icon class="option-icon all-icon"><i-ep-folder-opened /></el-icon>
<span class="option-label">全部Token</span>
</div>
</el-option>
<el-option
v-for="token in tokenOptions"
:key="token.tokenId"
:label="token.name"
:value="token.tokenId"
:disabled="token.isDisabled"
>
<div class="token-option" :class="{ 'disabled-token': token.isDisabled }">
<el-icon class="option-icon" :class="{ 'disabled-icon': token.isDisabled }">
<i-ep-key />
</el-icon>
<span class="option-label">{{ token.name }}</span>
<el-tag v-if="token.isDisabled" type="info" size="small" effect="plain" class="disabled-tag">
已禁用
</el-tag>
</div>
</el-option>
</el-select>
<el-button
:icon="FullScreen"
circle
plain
size="small"
@click="toggleFullscreen"
/>
</div>
</div>
<el-card v-loading="loading" class="chart-card">
<template #header>
<div class="card-header">
<span class="card-title">📊 近七天每日Token消耗量</span>
<span class="card-title">📊 近七天每日Token消耗量{{ selectedTokenId ? ` (${selectedTokenName})` : '' }}</span>
<el-tag type="primary" size="large" effect="dark">
近七日总计: {{ totalTokens }} tokens
</el-tag>
@@ -501,7 +572,7 @@ onBeforeUnmount(() => {
<el-card v-loading="loading" class="chart-card">
<template #header>
<div class="card-header">
<span class="card-title">🥧 各模型Token消耗占比</span>
<span class="card-title">🥧 各模型Token消耗占比{{ selectedTokenId ? ` (${selectedTokenName})` : '' }}</span>
</div>
</template>
<div class="chart-container">
@@ -512,7 +583,7 @@ onBeforeUnmount(() => {
<el-card v-loading="loading" class="chart-card">
<template #header>
<div class="card-header">
<span class="card-title">📈 各模型总Token消耗量</span>
<span class="card-title">📈 各模型总Token消耗量{{ selectedTokenId ? ` (${selectedTokenName})` : '' }}</span>
</div>
</template>
<div class="chart-container">
@@ -560,6 +631,62 @@ onBeforeUnmount(() => {
border-bottom: 2px solid #e9ecef;
}
.header-actions {
display: flex;
align-items: center;
gap: 12px;
}
.token-selector {
width: 240px;
}
.token-option {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
&.disabled-token {
opacity: 0.6;
.option-label {
text-decoration: line-through;
color: #909399;
}
}
}
.option-icon {
color: #667eea;
font-size: 16px;
flex-shrink: 0;
&.all-icon {
color: #409eff;
}
&.disabled-icon {
color: #c0c4cc;
}
}
.option-label {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.disabled-tag {
margin-left: auto;
flex-shrink: 0;
font-size: 11px;
padding: 0 6px;
height: 18px;
line-height: 18px;
}
.header h2 {
display: flex;
align-items: center;