import { I18N_TECHNICAL_TEXT } from '../../../i18n/technicalText.js';
import React, { useMemo, useState } from 'react';
import { Progress, Radio, RadioGroup, Tag } from '@/components/ui';
import { VChart } from '@visactor/react-vchart';
import {
BarChart3,
Cpu,
Crown,
GitCompareArrows,
LineChart,
Users,
} from 'lucide-react';
import { ChangeText, EmptyBlock, SectionCard } from './shared';
import {
formatCny,
orgDisplayName,
pct,
quotaToCny,
SEGMENTS,
TIERS,
} from './utils';
// VChart 配色必须是具体色值(图表在 canvas 上绘制,读取不到 CSS 变量);
// 与看板其余图表共用同一组色:个人蓝、企业紫、增长绿、下降红
const COLOR_PERSONAL = '#3b82f6';
const COLOR_ORG = '#8b5cf6';
const COLOR_ORG_MA = '#c4b5fd';
const COLOR_UP = '#10b981';
const COLOR_DOWN = '#ef4444';
const truncateLabel = (v, n = 14) =>
v && v.length > n ? `${v.slice(0, n - 1)}…` : v;
// ─── 变化归因:谁拉动了增长 / 下滑 ─────────────────────────────────
export const ChangeAttribution = ({ report, cny, t }) => {
const { chartSpec, segmentRows, netDelta } = useMemo(() => {
const orgs = (report.orgs || []).map((o) => ({
name: orgDisplayName(o, t),
delta: (o.quota || 0) - (o.prev_quota || 0),
}));
const up = orgs
.filter((o) => o.delta > 0)
.sort((a, b) => b.delta - a.delta)
.slice(0, 8);
const down = orgs
.filter((o) => o.delta < 0)
.sort((a, b) => a.delta - b.delta)
.slice(0, 8);
const values = [...up, ...down.reverse()]
.map((o, i) => ({
// 名称可能重复,用序号保证类目唯一,标签里再去掉
key: `${i} ${o.name}`,
value: Number(quotaToCny(o.delta, cny).toFixed(2)),
sign: o.delta > 0 ? 'up' : 'down',
}))
.reverse();
const spec = values.length
? {
type: 'bar',
direction: 'horizontal',
data: [{ id: 'attr', values }],
xField: 'value',
yField: 'key',
seriesField: 'sign',
color: {
type: 'ordinal',
domain: ['up', 'down'],
range: [COLOR_UP, COLOR_DOWN],
},
legends: { visible: false },
bar: { style: { cornerRadius: 3 } },
label: {
visible: true,
position: 'outside',
formatMethod: (v) => `${v > 0 ? '+' : ''}¥${v}`,
},
tooltip: {
mark: {
title: { value: (d) => d?.key?.split(' ')[1] },
content: [
{
key: t('消耗变化'),
value: (d) => `${d?.value > 0 ? '+' : ''}¥${d?.value}`,
},
],
},
},
axes: [
{ orient: 'bottom', label: { formatMethod: (v) => `¥${v}` } },
{
orient: 'left',
label: {
formatMethod: (v) => truncateLabel(String(v).split(' ')[1]),
},
},
],
}
: null;
const bySeg = {};
(report.segments || []).forEach((s) => {
bySeg[s.key] = (s.quota || 0) - (s.prev_quota || 0);
});
const rows = Object.entries(bySeg)
.filter(([, d]) => d !== 0)
.sort((a, b) => Math.abs(b[1]) - Math.abs(a[1]));
const net = Object.values(bySeg).reduce((s, d) => s + d, 0);
return { chartSpec: spec, segmentRows: rows, netDelta: net };
}, [report, cny, t]);
return (
}
extra={
= 0
? 'var(--ui-color-success)'
: 'var(--ui-color-danger)',
}}
>
{t('净变化')} {netDelta >= 0 ? '+' : '-'}
{formatCny(Math.abs(netDelta), cny)}
}
>
{t('增长 / 下滑贡献最大的企业(本期 − 对比期)')}
{chartSpec ? (
) : (
)}
{t('按健康分群拆解')}
{segmentRows.length === 0 ? (
) : (
{segmentRows.map(([key, d]) => {
const meta = SEGMENTS[key] || { label: key, color: 'grey' };
const maxAbs = Math.max(
...segmentRows.map(([, x]) => Math.abs(x)),
1,
);
return (
{t(meta.label)}
0
? 'var(--ui-color-success)'
: 'var(--ui-color-danger)',
}}
>
{d > 0 ? '+' : '-'}
{formatCny(Math.abs(d), cny)}
);
})}
)}
);
};
// ─── 价值分层 + 排行 ──────────────────────────────────────────────
const RankList = ({ items, valueOf, render, max }) => (
{items.map((o, i) => (
))}
);
export const TiersAndRankings = ({ report, cny, onSelectTier, t }) => {
const k = report.kpi || {};
const consumers = (report.orgs || []).filter((o) => o.quota > 0).slice(0, 10);
const byActive = [...(report.orgs || [])]
.filter((o) => o.active_members > 0)
.sort((a, b) => b.active_members - a.active_members || b.quota - a.quota)
.slice(0, 10);
return (
}
>
{(report.tiers || []).map((tier) => {
const meta = TIERS[tier.key];
const share = pct(tier.quota, k.org_quota);
return (
);
})}
{t('Top5 集中度')}
{(k.top5_share || 0).toFixed(1)}%
{t('Top10 集中度')}
{(k.top10_share || 0).toFixed(1)}%
}
>
{consumers.length === 0 ? (
) : (
o.quota}
max={consumers[0].quota}
render={(o) => (
<>
{orgDisplayName(o, t)}
{formatCny(o.quota, cny)}
{(o.share || 0).toFixed(1)}
{I18N_TECHNICAL_TEXT.PERCENT_SEPARATOR} {o.active_members}/
{o.member_count} {t('人活跃')}
>
)}
/>
)}
}
>
{byActive.length === 0 ? (
) : (
o.active_members}
max={byActive[0].active_members}
render={(o) => (
<>
{orgDisplayName(o, t)}
{o.active_members} {t('人')}
{t('活跃率')}{' '}
{o.member_count > 0
? `${Math.min(100, pct(o.active_members, o.member_count)).toFixed(0)}%`
: '—'}
{t('人均')}{' '}
{formatCny(
o.active_members > 0 ? o.quota / o.active_members : 0,
cny,
)}
>
)}
/>
)}
);
};
// ─── 趋势 ─────────────────────────────────────────────────────────
const TREND_MODES = {
quota: {
label: '消耗金额',
fields: ['personal_quota', 'org_quota'],
money: true,
},
requests: {
label: '请求次数',
fields: ['personal_requests', 'org_requests'],
},
users: { label: '活跃人数', fields: ['personal_active', 'org_active'] },
orgs: { label: '活跃企业', fields: [null, 'active_orgs'] },
};
export const TrendChart = ({ report, cny, t }) => {
const [mode, setMode] = useState('quota');
const spec = useMemo(() => {
const data = report.trend || [];
if (!data.length) return null;
const cfg = TREND_MODES[mode];
const personalKey = t('个人');
const orgKey = t('企业');
const maKey = t('企业 7 日均线');
const conv = (v) =>
cfg.money ? Number(quotaToCny(v || 0, cny).toFixed(2)) : v || 0;
const values = [];
const colors = [];
const series = [];
if (cfg.fields[0]) {
series.push(personalKey);
colors.push(COLOR_PERSONAL);
}
series.push(orgKey);
colors.push(COLOR_ORG);
const withMa = mode === 'quota' && data.length >= 7;
if (withMa) {
series.push(maKey);
colors.push(COLOR_ORG_MA);
}
data.forEach((p, i) => {
if (cfg.fields[0])
values.push({
date: p.date,
type: personalKey,
value: conv(p[cfg.fields[0]]),
});
values.push({
date: p.date,
type: orgKey,
value: conv(p[cfg.fields[1]]),
});
if (withMa && i >= 6) {
const win = data.slice(i - 6, i + 1);
const avg = win.reduce((s, x) => s + (x[cfg.fields[1]] || 0), 0) / 7;
values.push({ date: p.date, type: maKey, value: conv(avg) });
}
});
const fmt = (v) => (cfg.money ? `¥${v}` : Number(v).toLocaleString());
return {
type: 'line',
data: [{ id: 'trend', values }],
xField: 'date',
yField: 'value',
seriesField: 'type',
color: { type: 'ordinal', domain: series, range: colors },
point: { visible: data.length <= 31, style: { size: 4 } },
line: {
style: {
lineWidth: 2,
lineDash: (d) => (d.type === maKey ? [4, 4] : [0]),
},
},
legends: { visible: true, orient: 'top', position: 'end' },
tooltip: {
dimension: {
content: [{ key: (d) => d?.type, value: (d) => fmt(d?.value) }],
},
},
crosshair: { xField: { visible: true } },
axes: [
{
orient: 'bottom',
label: { style: { angle: data.length > 14 ? -45 : 0 } },
},
{ orient: 'left', label: { formatMethod: fmt } },
],
};
}, [report, mode, cny, t]);
return (
}
extra={
setMode(e.target.value)}
className='ml-auto'
>
{Object.entries(TREND_MODES).map(([k, v]) => (
{t(v.label)}
))}
}
>
{spec ? (
) : (
)}
);
};
// ─── 企业热门模型 ─────────────────────────────────────────────────
export const TopModels = ({ report, cny, t }) => {
const spec = useMemo(() => {
const data = report.top_models || [];
if (!data.length) return null;
const values = data
.map((m) => ({
model: m.model_name || '-',
value: Number(quotaToCny(m.quota, cny).toFixed(2)),
requests: m.requests,
orgs: m.org_count,
share: m.share,
}))
.reverse();
return {
type: 'bar',
direction: 'horizontal',
data: [{ id: 'models', values }],
xField: 'value',
yField: 'model',
color: [COLOR_ORG],
bar: { style: { cornerRadius: [0, 4, 4, 0] } },
label: {
visible: true,
position: 'outside',
formatMethod: (v, d) => `¥${v} · ${(d?.share || 0).toFixed(1)}%`,
},
tooltip: {
mark: {
title: { value: (d) => d?.model },
content: [
{ key: t('消耗金额'), value: (d) => `¥${d?.value}` },
{
key: t('占企业消耗'),
value: (d) => `${(d?.share || 0).toFixed(1)}%`,
},
{
key: t('请求次数'),
value: (d) => (d?.requests || 0).toLocaleString(),
},
{ key: t('使用企业数'), value: (d) => d?.orgs },
],
},
},
axes: [
{ orient: 'bottom', label: { formatMethod: (v) => `¥${v}` } },
{
orient: 'left',
label: { formatMethod: (v) => truncateLabel(v, 22) },
},
],
};
}, [report, cny, t]);
return (
}>
{spec ? (
) : (
)}
);
};