import { createContext, useContext, useState } from 'react' import type { ReactNode, Ref } from 'react' import { dashboardStatisticsHelp } from './qaDashboardStatistics' import type { QADashboardData, DashboardCount, DashboardRegion } from './qaDashboardData' import type { QualityRate } from './qaQuality' import { currentQAWeek } from './qaWeeks' import { historicalTrend } from './qaHistoricalTrend' import type { HistoricalPlotPoint } from './qaHistoricalTrend' interface Box { x: number y: number w: number h: number } interface StatisticsTip { id: string box: Box baseline: number } const StatisticsContext = createContext<{ definitions: Record show: (tip: StatisticsTip) => void hide: (id: string) => void active: string | null } | null>(null) const blue = '#3274e6', ink = '#23344d', muted = '#7a8799', line = '#eaf0f7' const colors = [blue, '#59a9f3', '#69c6bc', '#f3c25a', '#f39b6c', '#9b8ade', '#86b8a1', '#d6a3cf', '#8aacc9', '#c4cb76'] const number = (n: number) => new Intl.NumberFormat('zh-CN').format(n) const pct = (n: number | null) => (n === null ? '—' : `${n.toFixed(1)}%`) function wrap(value: string, width: number, size = 12): string[] { const max = Math.max(2, width / size), out: string[] = [] let row = '', units = 0 for (const c of Array.from(value)) { const next = c.charCodeAt(0) < 128 ? 0.57 : 1 if (row && units + next > max) { out.push(row) row = '' units = 0 } row += c units += next } if (row || !out.length) out.push(row) return out } function Text({ value, x, y, width, size = 12, fill = ink, weight = 400, anchor = 'start', }: { value: string x: number y: number width: number size?: number fill?: string weight?: number anchor?: 'start' | 'middle' | 'end' }) { return ( {wrap(value, width, size).map((row, i) => ( {row} ))} ) } function Panel({ box, title, en, id, children, tint = '#fff', }: { box: Box title: string en: string id: string children: ReactNode tint?: string }) { const statistics = useContext(StatisticsContext), hint = statistics?.definitions[id] ?? '', baseline = box.w < 140 ? 59 : 25 return ( {title} {en} {children} statistics?.show({ id, box, baseline })} onMouseLeave={() => statistics?.hide(id)} onFocus={() => statistics?.show({ id, box, baseline })} onBlur={() => statistics?.hide(id)} onClick={() => statistics?.show({ id, box, baseline })} onKeyDown={(e) => { if (e.key === 'Escape') statistics?.hide(id) if (e.key === 'Enter' || e.key === ' ') { e.preventDefault() statistics?.show({ id, box, baseline }) } }} > {hint} 统计口径 ) } function Metric({ box, value, title, en, id, tint, color, subtitle, }: { box: Box value: number title: string en: string id: string tint: string color: string subtitle: string }) { const text = number(value), size = Math.min(box.w < 220 ? 40 : 54, (box.w - 32) / (text.length * 0.62)) return ( {text} {subtitle} ) } function polar(cx: number, cy: number, r: number, degrees: number) { const a = (degrees * Math.PI) / 180 return { x: cx + r * Math.cos(a), y: cy + r * Math.sin(a) } } function arc(cx: number, cy: number, r: number, start: number, end: number) { const a = polar(cx, cy, r, start), b = polar(cx, cy, r, end) return `M ${a.x} ${a.y} A ${r} ${r} 0 ${end - start > 180 ? 1 : 0} 1 ${b.x} ${b.y}` } function Gauge({ box, rate, title, en, id }: { box: Box; rate: QualityRate; title: string; en: string; id: string }) { const r = Math.min(42, box.w * 0.27), cx = box.w / 2, cy = 94, d = arc(cx, cy, r, 135, 405) return ( {`${title}:${rate.numerator} / ${rate.denominator};分母为有效已评估记录`} {rate.percent !== null && rate.percent > 0 ? ( ) : null} {pct(rate.percent)} {rate.denominator ? `${number(rate.numerator)} / ${number(rate.denominator)}` : '暂无有效分母'} ) } function pieHeight(points: DashboardCount[], w: number) { const mobile = w < 500, legendW = mobile ? w - 60 : w * 0.45 return Math.max( mobile ? 270 : 300, (mobile ? 225 : 65) + points.reduce((n, p) => n + Math.max(24, wrap(p.label, legendW - 85).length * 16 + 9), 0) ) } function Pie({ box, points }: { box: Box; points: DashboardCount[] }) { const mobile = box.w < 500, total = points.reduce((n, p) => n + p.count, 0), legendW = mobile ? box.w - 32 : box.w * 0.47, cx = mobile ? box.w / 2 : box.w * 0.76, cy = mobile ? 135 : Math.max(155, box.h / 2), radius = Math.min(mobile ? 73 : 112, box.w * (mobile ? 0.25 : 0.21)) let angle = -90, legendY = mobile ? 236 : 76 return ( {!total ? ( 暂无分类记录 ) : null} {points.map((point, i) => { const start = angle angle += (point.count / total) * 360 const a = polar(cx, cy, radius, start), b = polar(cx, cy, radius, angle) const y = legendY legendY += Math.max(24, wrap(point.label, legendW - 85).length * 16 + 9) return ( {points.length === 1 ? ( ) : ( 180 ? 1 : 0} 1 ${b.x} ${b.y} Z`} fill={colors[i % colors.length]} stroke="#fff" strokeWidth={1} /> )} {`${point.label}:${point.count}(${((point.count / total) * 100).toFixed(1)}%)`} {number(point.count)} ) })} ) } function productRows(points: DashboardCount[], w: number) { return points.map((p) => ({ point: p, lines: wrap(p.label, Math.max(70, w * 0.3), 11) })) } function productHeight(points: DashboardCount[], w: number) { return Math.max(300, 75 + productRows(points, w).reduce((n, r) => n + Math.max(30, r.lines.length * 15 + 10), 0)) } function Products({ box, points }: { box: Box; points: DashboardCount[] }) { const left = Math.max(85, box.w * 0.32), right = box.w - 58, max = Math.max(1, ...points.map((p) => p.count)) let y = 78 return ( {points.length ? ( productRows(points, box.w).map(({ point, lines }) => { const at = y y += Math.max(30, lines.length * 15 + 10) return ( {`${point.label}:${point.count}`} {number(point.count)} ) }) ) : ( 暂无分类记录 )} ) } type PlotPoint = HistoricalPlotPoint function Plot({ box, title, en, id, points, percent = false, monthly = false, }: { box: Box title: string en: string id: string points: PlotPoint[] percent?: boolean monthly?: boolean }) { const left = 44, right = box.w - 22, top = 74, bottom = box.h - 47, max = percent ? 100 : Math.max(4, Math.ceil(Math.max(0, ...points.map((p) => p.value ?? 0)) / 4) * 4), x = (i: number) => points.length === 1 ? (left + right) / 2 : left + (i * (right - left)) / Math.max(1, points.length - 1), y = (n: number) => bottom - (n / max) * (bottom - top) const color = (source: PlotPoint['source']) => source === 'master_live_cumulative_v1' || source === 'master_live_calendar_month_v1' ? '#249c86' : source === 'system_frozen' ? '#8b68c7' : blue const paths = [...new Set(points.map((p) => p.source))].map((source) => { let path = '', open = false for (let i = 0; i < points.length; i++) { const point = points[i] if (point.value === null || point.source !== source) { open = false continue } path += `${open ? 'L' : 'M'} ${x(i)} ${y(point.value)} ` open = true } return { source, path } }) const every = Math.max(1, Math.ceil(points.length / (box.w < 420 ? 5 : 8))) const labelled = new Set() const label = (i: number) => { if ((monthly || points[i]?.value !== null) && points[i] && [...labelled].every((k) => Math.abs(x(k) - x(i)) >= 52)) labelled.add(i) } label(0) label(points.length - 1) // Keep the first point of a new policy readable instead of forcing two adjacent labels at a boundary. points.forEach((point, i) => { if (i && points[i - 1]?.source !== point.source) label(i) }) points.forEach((point, i) => { if (points[i + 1]?.source !== point.source) label(i) }) points.forEach((_, i) => { if (i % every === 0) label(i) }) return ( {Array.from({ length: 5 }, (_, i) => ( {(max * i) / 4} {percent ? '%' : ''} ))} {paths .filter((p) => p.path) .map((p, i) => ( ))} {points.map((point, i) => ( {point.hint} {point.value !== null ? ( <> {labelled.has(i) ? ( {percent ? `${point.value.toFixed(2)}%` : number(point.value)} ) : null} ) : null} {monthly && point.value === null ? ( — ) : null} {labelled.has(i) ? ( {point.label} ) : null} ))} {percent ? ( {monthly ? '自然月独立计算 · 当前有效结论 · 空分母留空' : points.some((p) => p.source === 'master_live_cumulative_v1') ? '蓝:历史上报;紫:系统冻结;绿:总表累计' : points.some((p) => p.source === 'user_provided_history') ? '蓝:用户提供(未提供分子/分母);紫:系统冻结' : '缺失周留空;系统冻结与当前实时结果分开'} ) : null} {!points.some((p) => p.value !== null) ? ( {percent ? '暂无冻结快照' : '暂无数据'} ) : null} ) } function regionalHeight(regions: DashboardRegion[], w: number) { return Math.max( 290, 130 + regions.reduce((n, r) => n + Math.max(34, wrap(r.name, Math.max(70, w - 125), 11.5).length * 16 + 12), 0) ) } function RegionTable({ box, regions, frequency, month, }: { box: Box regions: DashboardRegion[] frequency: boolean month: string }) { const rows = [...regions].sort((a, b) => { const av = frequency ? a.frequency : a.usage_coverage.percent, bv = frequency ? b.frequency : b.usage_coverage.percent return (bv ?? -1) - (av ?? -1) || a.name.localeCompare(b.name, 'zh-CN') }) let y = 104 return ( 排名 区域 {frequency ? '人均次数' : '使用覆盖率'} {rows.map((r, i) => { const at = y, value = frequency ? r.frequency : r.usage_coverage.percent const h = Math.max(34, wrap(r.name, Math.max(70, box.w - 125), 11.5).length * 16 + 12) y += h return ( {`${r.name};${month}月内提问 ${r.questions} 次;去重使用 ${r.users ?? '未知'} 人 / 通讯录归属 ${r.roster_people ?? '未知'} 人`} {i % 2 === 0 ? : null} {value !== null && i < 3 ? ( ) : null} {value === null ? '—' : i + 1} {value === null ? '—' : frequency ? value.toFixed(2) : `${value.toFixed(1)}%`} ) })} {month}月累计 ) } export function QADashboardDrawing({ data, width, svgRef, }: { data: QADashboardData width: number svgRef?: Ref }) { const [tip, setTip] = useState(null) const definitions = dashboardStatisticsHelp(data) const w = Math.max(240, Math.round(width)), pad = w < 700 ? 10 : 16, gap = w < 700 ? 12 : 18, inner = w - pad * 2, mobile = w < 900, unit = (inner - gap * 3) / 4, week = currentQAWeek(new Date(data.week_start)), filterLines = wrap(data.keyword ? `关键词:${data.keyword}` : '', inner - 16, 11), heading = `${data.week_start.slice(0, 10)} 起的自然周${data.quality_period ? ` · 质量 ${data.quality_period.month} 月内累计` : ''} · 区域统计 ${new Date(Date.parse(data.month_start) + 8 * 3600000).toISOString().slice(0, 7)} 月累计`, headingLines = (mobile ? [heading.split(' · ')[0], heading.split(' · ').slice(1).join(' · ')] : [heading]).flatMap( (row) => wrap(row, inner - 16, 10.5) ), filterY = 47 + headingLines.length * 14, header = filterY + (data.keyword ? filterLines.length * 15 : 0) + 4, metricH = mobile ? 154 : 166 const metrics: Box[] = Array.from({ length: 4 }, (_, i) => mobile ? { x: pad + ((i % 2) * (inner + gap)) / 2, y: header + Math.floor(i / 2) * (metricH + gap), w: (inner - gap) / 2, h: metricH, } : { x: pad + i * (unit + gap), y: header, w: unit, h: metricH } ) let cursor = header + (mobile ? 2 * metricH + gap : metricH) + gap const pieW = mobile ? inner : (inner - gap) * 0.54, productW = mobile ? inner : inner - gap - pieW, pieH = pieHeight(data.issue_types, pieW), productsH = productHeight(data.products, productW), row2H = Math.max(pieH, productsH) const pie: Box = { x: pad, y: cursor, w: pieW, h: mobile ? pieH : row2H }, products: Box = { x: mobile ? pad : pad + pieW + gap, y: mobile ? cursor + pieH + gap : cursor, w: productW, h: mobile ? productsH : row2H, } cursor += mobile ? pieH + productsH + gap * 2 : row2H + gap const trendW = mobile ? inner : unit * 2 + gap, regionW = mobile ? inner : unit, regionH = regionalHeight(data.regions, regionW), row3H = Math.max(290, regionH) const trend: Box = { x: pad, y: cursor, w: trendW, h: mobile ? 270 : row3H }, freq: Box = { x: mobile ? pad : pad + trendW + gap, y: mobile ? cursor + trend.h + gap : cursor, w: regionW, h: mobile ? regionH : row3H, }, usage: Box = { x: mobile ? pad : pad + trendW + regionW + gap * 2, y: mobile ? cursor + trend.h + regionH + gap * 2 : cursor, w: regionW, h: mobile ? regionH : row3H, } cursor += mobile ? trend.h + regionH * 2 + gap * 3 : row3H + gap const historyW = mobile ? inner : (inner - gap) / 2, coverage: Box = { x: pad, y: cursor, w: historyW, h: 270 }, accuracy: Box = { x: mobile ? pad : pad + historyW + gap, y: mobile ? cursor + 270 + gap : cursor, w: historyW, h: 270, }, height = mobile ? cursor + 540 + gap + pad : cursor + 270 + pad const frozen = (correctness: boolean): PlotPoint[] => historicalTrend(data, correctness) const month = new Date(Date.parse(data.month_start) + 8 * 3600000).toISOString().slice(0, 7) const tipWidth = Math.min(334, inner), tipLines = wrap(tip ? definitions[tip.id] : '', tipWidth - 26, 11.5), tipHeight = tipLines.length * 15.525 + 26, tipX = tip ? Math.max(pad, Math.min(w - pad - tipWidth, tip.box.x + tip.box.w - tipWidth - 10)) : 0, tipY = tip ? Math.max(pad, Math.min(height - pad - tipHeight, tip.box.y + tip.baseline + 10)) : 0 return ( setTip((current) => (current?.id === id ? null : current)), active: tip?.id ?? null, }} > {`问题统计看板 · ${week.year}年第${week.week}周`} 问题统计看板 {week.year} · W{String(week.week).padStart(2, '0')} {headingLines.map((row, index) => ( ))} {data.keyword ? ( ) : null} ({ label: p.date.slice(5), value: p.count, hint: `${p.date}:${p.count} 条` }))} /> {tip ? ( ) : null} ) }