import * as vscode from 'vscode'; import { QuotaResponse, QuotaDisplay } from './types'; export class StatusBarManager { private statusBarItem: vscode.StatusBarItem; private currentPanel: vscode.WebviewPanel | undefined; private onRefresh: () => Promise<{ data: QuotaDisplay | null; lastRefreshAt: Date | null; error: string | null; }>; constructor(onRefresh: () => Promise<{ data: QuotaDisplay | null; lastRefreshAt: Date | null; error: string | null; }>) { this.onRefresh = onRefresh; this.statusBarItem = vscode.window.createStatusBarItem( vscode.StatusBarAlignment.Right, 100 ); this.statusBarItem.command = 'getdeepin-quota.showPopup'; this.statusBarItem.text = '$(cloud) AI用量'; this.statusBarItem.show(); } updateNotLoggedIn(): void { this.statusBarItem.text = '$(cloud) 未设置Token'; this.statusBarItem.tooltip = new vscode.MarkdownString('**点击设置 GetDeepin AI Token**'); } updateWithError(): void { this.statusBarItem.text = '$(cloud) 获取失败'; this.statusBarItem.tooltip = new vscode.MarkdownString('**获取数据失败**\n\n点击重试或重新设置 Token'); } updateWithQuota(data: QuotaDisplay): void { const domesticUsed = (100 - data.domestic.remainingDailyPercent).toFixed(0); const globalUsed = (100 - data.global.remainingMonthlyPercent).toFixed(0); this.statusBarItem.text = `$(cloud) 国内 ${domesticUsed}% | 国外 ${globalUsed}%`; this.statusBarItem.tooltip = this.generateTooltipMarkdown(data); } private generateTooltipMarkdown(data: QuotaDisplay): vscode.MarkdownString { const md = new vscode.MarkdownString(); md.supportHtml = true; const formatPercent = (n: number) => n.toFixed(1); const formatTokens = (n: number) => n.toLocaleString('zh-CN'); const getProgressBar = (usedPercent: number) => { const filled = Math.round(usedPercent / 5); const empty = 20 - filled; return '█'.repeat(filled) + '░'.repeat(empty); }; md.appendMarkdown(`### AI 模型用量统计\n\n`); md.appendMarkdown(`**${data.user.display_name}** (${data.user.job_id}) \n`); md.appendMarkdown(`${data.user.email}\n\n`); md.appendMarkdown('---\n\n'); const domesticDailyUsed = 100 - data.domestic.remainingDailyPercent; const domesticDailyWarning = domesticDailyUsed > 80 ? '⚠️ ' : ''; md.appendMarkdown(`#### ${domesticDailyWarning}${data.domestic.label}\n\n`); md.appendMarkdown(`日额度: \`${getProgressBar(domesticDailyUsed)}\` 已用 \`${formatPercent(domesticDailyUsed)}%\`\n\n`); const domesticMonthlyUsed = 100 - data.domestic.remainingMonthlyPercent; md.appendMarkdown(`月额度: \`${getProgressBar(domesticMonthlyUsed)}\` 已用 \`${formatPercent(domesticMonthlyUsed)}%\`\n\n`); md.appendMarkdown(`累计消耗: ${formatTokens(data.domestic.totalTokens)} tokens\n\n`); md.appendMarkdown(`支持模型: ${data.domestic.models.map(m => `\`${m}\``).join(' ')}\n\n`); const globalMonthlyUsed = 100 - data.global.remainingMonthlyPercent; const globalWarning = globalMonthlyUsed > 80 ? '⚠️ ' : ''; md.appendMarkdown(`#### ${globalWarning}${data.global.label}\n\n`); if (data.global.hasDailyLimit && data.global.remainingDailyPercent !== null) { const globalDailyUsed = 100 - data.global.remainingDailyPercent; md.appendMarkdown(`日额度: \`${getProgressBar(globalDailyUsed)}\` 已用 \`${formatPercent(globalDailyUsed)}%\`\n\n`); } md.appendMarkdown(`月额度: \`${getProgressBar(globalMonthlyUsed)}\` 已用 \`${formatPercent(globalMonthlyUsed)}%\`\n\n`); md.appendMarkdown(`累计消耗: ${formatTokens(data.global.totalTokens)} tokens\n\n`); md.appendMarkdown(`支持模型: ${data.global.models.map(m => `\`${m}\``).join(' ')}\n\n`); md.appendMarkdown('---\n\n'); md.appendMarkdown('*点击查看详情*'); return md; } showPopup( data: QuotaDisplay | null, isLoggedIn: boolean, lastRefreshAt: Date | null, lastRefreshError: string | null ): void { if (!isLoggedIn) { this.showLoginPrompt(); return; } if (!data) { this.showErrorPrompt(lastRefreshAt, lastRefreshError); return; } this.showQuotaPanel(data, lastRefreshAt, lastRefreshError); } private showLoginPrompt(): void { vscode.window.showQuickPick( [{ label: '$(key) 设置 Token', id: 'login' }], { placeHolder: '请先设置 GetDeepin AI Token' } ).then(selection => { if ((selection as any)?.id === 'login') { vscode.commands.executeCommand('getdeepin-quota.login'); } }); } private showErrorPrompt(lastRefreshAt: Date | null, lastRefreshError: string | null): void { vscode.window.showQuickPick( [ { label: '$(refresh) 重试', id: 'refresh' }, { label: '$(preview) 查看详情', id: 'details' }, { label: '$(key) 重新设置 Token', id: 'login' } ], { placeHolder: lastRefreshError ? `获取用量数据失败: ${lastRefreshError}` : '获取用量数据失败' } ).then(selection => { const item = selection as any; if (item?.id === 'refresh') { vscode.commands.executeCommand('getdeepin-quota.refresh'); } else if (item?.id === 'details') { this.showQuotaPanel(null, lastRefreshAt, lastRefreshError); } else if (item?.id === 'login') { vscode.commands.executeCommand('getdeepin-quota.login'); } }); } private showQuotaPanel( data: QuotaDisplay | null, lastRefreshAt: Date | null, lastRefreshError: string | null ): void { if (this.currentPanel) { this.currentPanel.reveal(vscode.ViewColumn.Active); this.currentPanel.webview.html = this.generatePanelHtml(data, lastRefreshAt, lastRefreshError); return; } const panel = vscode.window.createWebviewPanel( 'getdeepin-quota', 'AI 模型用量详情', vscode.ViewColumn.Active, { enableScripts: true } ); this.currentPanel = panel; panel.webview.html = this.generatePanelHtml(data, lastRefreshAt, lastRefreshError); panel.webview.onDidReceiveMessage(async (message) => { if (message.command === 'refresh') { try { const result = await this.onRefresh(); if (this.currentPanel === panel) { this.currentPanel.webview.html = this.generatePanelHtml( result.data, result.lastRefreshAt, result.error ); return; } } finally { if (this.currentPanel === panel) { void this.currentPanel.webview.postMessage({ command: 'refreshFinished' }); } } } }); panel.onDidDispose(() => { this.currentPanel = undefined; }); } private generatePanelHtml( data: QuotaDisplay | null, lastRefreshAt: Date | null, lastRefreshError: string | null ): string { const formatTokens = (n: number) => n.toLocaleString('zh-CN'); const formatPercent = (n: number) => n.toFixed(1); const formatTime = (time: Date | null) => time ? time.toLocaleString('zh-CN', { hour12: false }) : '暂无'; const renderQuotaSection = ( label: string, remainingDailyPercent: number | null, remainingMonthlyPercent: number, hasDailyLimit: boolean, totalTokens: number, models: string[] ) => { const dailyUsed = remainingDailyPercent !== null ? 100 - remainingDailyPercent : null; const monthlyUsed = 100 - remainingMonthlyPercent; let html = `

${label}

`; if (hasDailyLimit && dailyUsed !== null) { html += `
日额度 ${formatPercent(dailyUsed)}% 已使用
`; } html += `
月额度 ${formatPercent(monthlyUsed)}% 已使用
累计消耗 ${formatTokens(totalTokens)} tokens
${models.map(m => `${m}`).join('')}
`; return html; }; const refreshMetaHtml = `
最后刷新 ${formatTime(lastRefreshAt)}
${lastRefreshError ? `
刷新失败
${lastRefreshError}
` : ''}`; const quotaContentHtml = data ? ` ${renderQuotaSection( data.domestic.label, data.domestic.remainingDailyPercent, data.domestic.remainingMonthlyPercent, data.domestic.hasDailyLimit, data.domestic.totalTokens, data.domestic.models )} ${renderQuotaSection( data.global.label, data.global.remainingDailyPercent, data.global.remainingMonthlyPercent, data.global.hasDailyLimit, data.global.totalTokens, data.global.models )}` : `
当前没有可展示的额度数据,请检查 Token 或稍后重试。
`; return `

AI 模型用量统计

${data ? `
${data.user.display_name} (${data.user.job_id}) · ${data.user.email}
` : ''}
${refreshMetaHtml} ${quotaContentHtml}
`; } dispose(): void { this.statusBarItem.dispose(); } } export function parseQuotaResponse(response: QuotaResponse): QuotaDisplay { const domestic = response.groups.find(g => g.key === 'domestic')!; const global = response.groups.find(g => g.key === 'global')!; return { user: response.user, domestic: { label: domestic.label, models: domestic.models, hasDailyLimit: domestic.remaining_daily_percent !== null, remainingDailyPercent: domestic.remaining_daily_percent ?? 100, remainingMonthlyPercent: domestic.remaining_monthly_percent, totalTokens: domestic.usage.total_tokens }, global: { label: global.label, models: global.models, hasDailyLimit: global.remaining_daily_percent !== null, remainingDailyPercent: global.remaining_daily_percent, remainingMonthlyPercent: global.remaining_monthly_percent, totalTokens: global.usage.total_tokens } }; }