import {Fragment, GlassButton, html, useState, useToast} from 'vendor';
import {api, download, useApp, useFetch} from '../api.js';
import {BLUE_SCALE, CAUSE_COLOR, heatLabelColor, num} from '../format.js';
import {EChart} from '../components/EChart.js';
import {DataTable, Pager} from '../components/DataTable.js';
import {Cause, LevelTag, Loading, Section, Select, StatusTag} from '../components/ui.js';
const PAGE_SIZE = 15;
export default function RootCause() {
const {filters, isAdmin} = useApp();
const toast = useToast();
const {data: confusion} = useFetch('/api/confusion', filters);
const {data: stats} = useFetch('/api/stats', {...filters, dim: 'root_cause'});
const [lastRun, setLastRun] = useState(null);
const [running, setRunning] = useState(false);
const runAnalysis = async () => {
setRunning(true);
try {
const r = await api('/api/analyze', {method: 'POST'});
setLastRun(r);
toast({message: `全量分析完成:${num(r.n)} 条,耗时 ${r.elapsed}s,准确率 ${r.acc}%`, tone: 'success'});
} catch (e) {
toast({message: e.message, tone: 'error'});
}
setRunning(false);
};
if (!confusion || !stats) return html`<${Loading}/>`;
// 交叉矩阵:matrix[i][j] = 上报原因 i、系统判定 j 的条数;对角线 i === j 为判定一致
const {causes, matrix} = confusion;
const n = causes.length;
let total = 0;
let hit = 0;
let maxCount = 1;
for (const row of matrix) {
maxCount = Math.max(maxCount, ...row);
}
// 热力图数据 value = [列, 行, 条数];行号倒过来,让第一个原因显示在最上面;深色格子用白字
const cells = [];
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
const count = matrix[i][j];
total += count;
if (i === j) hit += count;
cells.push({value: [j, n - 1 - i, count], label: {color: heatLabelColor(count, maxCount)}});
}
}
const matrixChart = {
tooltip: {formatter: s => `上报:${causes[n - 1 - s.value[1]]}
判定:${causes[s.value[0]]}
${s.value[2]} 条`},
grid: {left: 12, right: 12, top: 10, bottom: 30, containLabel: true},
xAxis: {type: 'category', data: causes, name: '判定', nameLocation: 'center', nameGap: 26},
yAxis: {type: 'category', data: [...causes].reverse()},
visualMap: {show: false, min: 0, max: maxCount, inRange: {color: BLUE_SCALE}},
series: [{type: 'heatmap', data: cells, label: {show: true},
itemStyle: {borderColor: 'transparent', borderWidth: 2, borderRadius: 6}}],
};
const causeChart = {
tooltip: {trigger: 'axis', axisPointer: {type: 'shadow'}, formatter: ([s]) => {
const r = stats.rows[s.dataIndex];
return `${r.key}
次数 ${r.count}
平均时长 ${r.avg_min} min
超长占比 ${r.long_ratio}%`;
}},
xAxis: {type: 'category', data: stats.rows.map(r => r.key)},
yAxis: {type: 'value'},
series: [{type: 'bar', barMaxWidth: 40, label: {show: true, position: 'top'},
data: stats.rows.map(r => ({value: r.avg_min, itemStyle: {color: CAUSE_COLOR[r.key]}}))}],
};
const runButton = isAdmin && html`
<${GlassButton} variant="glassProminent" loading=${running} onClick=${runAnalysis}>全量重新分析${GlassButton}>`;
return html`