StatsPanel.tsx 48 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
import { Panel, StatTile, StatGrid } from '@hm/ui';
import { useHeatmapStore } from '@/store/useHeatmapStore';
import { SpotlightEntry } from '@/features/heatmap/spotlight/SpotlightEntry';
import { UnresolvedRow } from './shared/UnresolvedRow';
import { SPOTLIGHT_TOP_N } from '@/features/heatmap/spotlight/spotlightView';
import { densityCellFill, densityCellInk, RANK_COLORS } from '@/features/heatmap/map/palette';
import {
  UNRESOLVED_LABEL,
  type MetaFile,
  type StatsResult,
} from '@/features/heatmap/aggregate/types';
import {
  TIME_BANDS,
  bandOfHour,
  hoursOfBandIdx,
  nightCountOf,
  sumTop,
} from '@/features/heatmap/aggregate/dims';
import {
  fmtCompact,
  fmtDate,
  fmtInt,
  fmtMs,
  fmtPercent,
  hourLabel,
  newEnergyNameOf,
  placeLabelOf,
  streetNameOf,
} from '@/utils/format';
import {
  AimOutlined,
  ArrowRightOutlined,
  BranchesOutlined,
  CarOutlined,
  FieldTimeOutlined,
  GlobalOutlined,
  HistoryOutlined,
  NodeIndexOutlined,
} from '@ant-design/icons';
import type { CSSProperties, ReactNode } from 'react';
import { Skeleton, Tabs } from 'antd';
import { VehicleDonut, type DonutSegment } from './VehicleCharts';
import { TimeBoard } from './TimeBoard';
import { OperatingWidget } from './OperatingWidget';
import { DimStaleNote } from './DimStaleNote';
import { HelpDot } from './HelpDot';

/** 两个下标集合是否完全一致(顺序无关)—— 用于判断某个 TopN 卡片 / 区行是否正被选中 */
function sameIds(a?: number[], b?: number[]): boolean {
  if (!a || !b || a.length !== b.length) return false;
  const sa = [...a].sort((x, y) => x - y);
  const sb = [...b].sort((x, y) => x - y);
  return sa.every((v, i) => v === sb[i]);
}

/**
 * 风险概览面板(右侧操作区第二个页签)。
 *
 * 数据全部来自 Worker 的 stats 入口(视口无关,只跟筛选有关),不依赖地图瓦片。
 * 视角按「决策者会怎么问」排,而不是按数据有什么排:
 *   一共多少 → 案子有多扎堆(集中程度与覆盖)→ 哪儿多(区)→ 那儿什么时候多(区 × 时段)
 *   → 哪条街道、哪一段路(街道 / 道路)→ 哪个位置反复出事(点位)→ 全市的时间形状。
 * 前三问是「该不该动手」,后三问是「动手先动哪儿」。
 *
 * 每一档都是入口:读数块、榜单每一行、榜末那几档、时段矩阵每一格、点位每一行,点下去
 * 都拉到右边那张清单抽屉,看的就是这一档背后的记录。榜单只给「哪一档多」的答案,
 * 而看到榜的第一反应是「那这一档里到底是什么」—— 少这一步,人只能自己拿筛选去凑。
 * 行本身整条可点(不是只让名字那一小块),用 button 而不是给 div 挂 onClick:
 * 键盘 Tab + Enter 也进得去。
 *
 * 「半数案件来自 N 处」那两个读数也点得开:切的是案件最集中的那 N 个地理方格内的全部案件。
 * 那批格子由 Worker 现算(见 coverCells),和榜上那个 N 出自同一次归格与同一个累计判据 ——
 * 界面若自己照数字挑格子,榜上的 N 处和清单里的起数就会各说各的。
 */
type DimKey = 'ownNature' | 'newEnergy' | 'vehicleClass';

/**
 * 车辆属性三维的展示顺序:所属性质 → 是否新能源 → 车种大类(概览构成行与环图页签同一顺序)。
 *
 * 原来第一维是「使用性质」(营业 / 非营业)。营运区分上线之后它完全被那一块覆盖了 ——
 * 同一句话在两块地方各说一遍,还各画一张环图,读的人要在两张图之间确认「这两个数是不是同一个」。
 * 换成「所属性质」(企业 / 私人 / 机关)之后这一维才有了独立价值:营运细分的判定依据就是
 * 企业 = 出租租赁、私人 = 网约车,光看营运区分看不出底下的结构。
 */
const VEHICLE_DIMS: Array<{ key: DimKey; name: string }> = [
  { key: 'ownNature', name: '所属性质' },
  { key: 'newEnergy', name: '是否新能源' },
  { key: 'vehicleClass', name: '车种大类' },
];

/**
 * 三个维度在 stats / dict 上取的字段名各不相同,其余处理一模一样,
 * 所以把「从哪儿取」收成一张表,取数逻辑只写一份 —— 否则加一维就要改四处,
 * 迟早有一处漏改(榜单、环图、构成条的口径必须同源)。
 * 返回 [榜单各档起数(已按数量倒序), 未填起数, 字典]。
 */
const DIM_SOURCE: Record<
  DimKey,
  (meta: MetaFile, stats: StatsResult | null) => [Array<[number, number]>, number, string[]]
> = {
  ownNature: (meta, stats) => [
    stats?.ownNatureCounts ?? [],
    stats?.ownNatureUnresolved ?? 0,
    meta.dict.ownNatures ?? [],
  ],
  newEnergy: (meta, stats) => [
    stats?.newEnergyCounts ?? [],
    stats?.newEnergyUnresolved ?? 0,
    meta.dict.newEnergy,
  ],
  vehicleClass: (meta, stats) => [
    stats?.vehicleClassCounts ?? [],
    stats?.vehicleClassUnresolved ?? 0,
    meta.dict.vehicleClasses,
  ],
};

export function StatsPanel() {
  const meta = useHeatmapStore((s) => s.meta);
  const stats = useHeatmapStore((s) => s.stats);
  const statsLoading = useHeatmapStore((s) => s.statsLoading);
  const detailReady = useHeatmapStore((s) => s.detailReady);
  const openStatsBoard = useHeatmapStore((s) => s.openStatsBoard);
  const openRoster = useHeatmapStore((s) => s.openRoster);
  const setMapScope = useHeatmapStore((s) => s.setMapScope);
  const mapScope = useHeatmapStore((s) => s.mapScope);
  const setRailTab = useHeatmapStore((s) => s.setRailTab);

  /**
   * 右栏那三块的「收起」收的是整条操作区:这一栏本身就是靠右缘竖着的一条,
   * 只把面板滑走、把手还留着,屏幕右缘照样被占着 —— 而用户要的正是「别挡地图」。
   * 复开走右缘常驻的页签把手,所以这里不另留把手。
   */
  const collapse = {
    onCollapse: () => setRailTab(null),
    collapseDir: 'right' as const,
    collapseHint: '收起右侧这条操作区,地图铺满整屏;点屏幕右缘的「风险概览」把手重新展开',
  };

  if (!meta) {
    return (
      <Panel title="风险概览" className="hm-panel--fluid" {...collapse}>
        <Skeleton active paragraph={{ rows: 6 }} />
      </Panel>
    );
  }

  const matched = stats?.matched ?? 0;
  const districtList = stats?.districtCounts ?? [];
  const streetList = stats?.topStreets ?? [];
  const districtUnresolved = stats?.districtUnresolved ?? 0;
  const road = stats?.road ?? null;
  const place = stats?.place ?? null;
  const districtHour = stats?.districtHour ?? null;
  const maxDistrict = districtList.length ? districtList[0][1] : 0;
  const maxStreet = streetList.length ? streetList[0][1] : 0;
  const maxRoad = road && road.counts.length ? road.counts[0][1] : 0;
  // 条形长度只按「本榜自己排出的名次」归一:榜首 = 100%。
  // 「未标注」那一档不进来参与这把尺子(它不在榜上),也不画条形 —— 它的大小由地址填写
  // 质量决定,和单个行政区不是一个量级的比法,一旦同框,确认项的条形就全被压扁了。
  // 街道与道路两榜干脆连那一行都不列(读不出名字的就不计数,见下面两条榜的注释)。

  // 「未识别」在字典里就是一个下标,所以区域榜末那一档照样切得出一份名单
  const unresolvedDistrictIdx = meta.dict.districts.indexOf(UNRESOLVED_LABEL);

  /* --------------------------- 集中程度与覆盖账 --------------------------- */

  const districtCounts = districtList.map(([, n]) => n);
  const streetCounts = streetList.map(([, n]) => n);
  const top3District = sumTop(districtCounts, 3);
  const top5Street = sumTop(streetCounts, 5);
  // 前 3 / 前 5 是「头部有多重」,两处 / 八处是「要动多少手」。
  // 前者只读榜单第一行,后者才说得出资源配置,所以两块并排放。
  const top3DistrictIdx = districtList.slice(0, 3).map(([idx]) => idx);
  const top5StreetIdx = streetList.slice(0, 5).map(([idx]) => idx);
  /**
   * 这两块收窄的名字要把区名 / 街道名写进去。
   *
   * 它们是「点一下在地图上看这几个区」的入口,而地图上那块名牌念的就是这句 label ——
   * 只写「案件最多的 3 个区」,屏上一圈范围框里还是不知道是哪三个。名字多时只取前两个,
   * 其余折算成「等 N 个」,牌子不会被撑成一行字墙。
   */
  const topLabel = (prefix: string, names: string[], unit: string) => {
    const shown = names.filter(Boolean).slice(0, 2).join('、');
    if (!shown) return `${prefix} · ${names.length} ${unit}`;
    return names.length > 2
      ? `${prefix} · ${shown} 等 ${names.length} ${unit}`
      : `${prefix} · ${shown}`;
  };

  /* ------------------------------ 区 × 时段 ------------------------------ */

  // 面板只画前 6 个区(按案件数):11 个区全铺开会把这张表拉成屏幕高度的三分之一,
  // 而尾部那几个区的时段形状本来就不该在第一屏抢话 —— 完整矩阵在抽屉里。
  const crossRows = districtList.slice(0, 6).map(([idx, n]) => {
    const bands = TIME_BANDS.map(() => 0);
    const hours: number[] = [];
    for (let h = 0; h < 24; h += 1) {
      const c = districtHour?.[idx * 24 + h] ?? 0;
      hours[h] = c;
      bands[bandOfHour(h)] += c;
    }
    const rowMax = Math.max(...bands, 1);
    // 夜间那一列按 NIGHT_HOURS 的白名单算,不用「凌晨档 + 深夜档」相加:
    // 现在是同一批小时纯属巧合,档位一改这两处就会分家(见 dims.nightCountOf)
    return {
      idx,
      total: n,
      name: meta.dict.districts[idx] ?? '—',
      bands,
      rowMax,
      night: nightCountOf(hours),
    };
  });

  /* ---------------------------- 反复出险的点位 ---------------------------- */

  const placeRows = (place?.top ?? []).slice(0, 5);
  const cellM = place?.cellM ?? 0;
  // 「近 N 天」的 N 由 Worker 报出来(上限 30,统计期短于 30 天时等于统计期):
  // 写死 30 的话,筛到「近 7 天」时这一行念的是统计期里根本不存在的一段日子
  const placeRecentDays = place?.recentDays ?? 30;

  /**
   * 一处点位:与街道 / 道路的单项点击口径一致 —— 在地图上只看这一处(按地理方框收窄),
   * 保留热力图 + 聚合点;再点地图上的聚合点 / 热力才打开明细抽屉。
   */
  const openPlaceRoster = (p: (typeof placeRows)[number]) => {
    setMapScope({
      label: `反复出险位置 · ${placeLabelOf(meta.dict, p) || '这一处'}`,
      bboxes: [{ minLng: p.minLng, minLat: p.minLat, maxLng: p.maxLng, maxLat: p.maxLat }],
    });
  };

  /**
   * 车辆属性三维:维度名、字典、榜单数、未填数,四处(面板构成行 / 环图页签 / 抽屉)共用一份。
   *
   * 字典下标 0 固定是「未填」——源表没这一列、或者这一行没写值。它不是一档属性,
   * 而是一个「这一维取不到值」的记号:不参与名次(所以构成行的「榜首」要跳过 idx 0),
   * 但要计入分母与占比,否则各档占比加起来不到 100%,读起来像统计漏了。
   */
  const dimSegments = (key: DimKey): { segs: DonutSegment[]; total: number } => {
    const [counts, unresolved, dict] = DIM_SOURCE[key](meta, stats);
    const segs: DonutSegment[] = counts.map(([idx, n], i) => ({
      // 「是否新能源」那一维念全(是 → 新能源),理由见 newEnergyNameOf
      label: key === 'newEnergy' ? newEnergyNameOf(dict?.[idx] ?? '—') : (dict?.[idx] ?? '—'),
      value: n,
      color: RANK_COLORS[i % RANK_COLORS.length],
      idx,
    }));
    if (unresolved > 0) {
      segs.push({ label: '未填', value: unresolved, color: 'var(--hm-text-3)', idx: 0 });
    }
    const total = segs.reduce((a, s) => a + s.value, 0);
    return { segs, total };
  };

  /**
   * 这一维是「统计没算出数」还是「业务上真没有」。
   *
   * 有字典、有命中记录,榜上却一个格子都没有 —— 那就是统计没产出这一维,
   * 而不是这一维全是 0。画成空环会读成后者(见 DimStaleNote 的说明)。
   */
  const dimStale = (key: DimKey): boolean => {
    const [counts, unresolved, dict] = DIM_SOURCE[key](meta, stats);
    return (dict?.length ?? 0) > 0 && matched > 0 && counts.length === 0 && unresolved === 0;
  };

  /**
   * 车辆属性三处(构成条、环图弧、环图图例)点出来的都是同一件事:把地图上画的那批点
   * 收窄到这一类车 —— 落在地图而不是直接开清单,是因为「这一类占多少」已经由条和环回答过了,
   * 接着要问的必然是「那这些案子出在哪儿」;收窄之后点屏上任意一格,出的就是这一类的清单。
   *
   * 用 mapScope 而不是 spotlight(聚焦屏)的理由:聚焦会把热力、方格数字、黑点盘一起收起、
   * 换一整套画法,那是「单独比一屏深浅」时才要付的代价;这里要的只是「同类里少画一批点」,
   * 热力图与聚合点照旧在场,深浅与数字一起按收窄后的那批重算 —— 也就是页面初始化时那套画法。
   *
   * 这一类在当前筛选里 0 起时不做反应:一条 0 起的段本身就不可见(宽度 0),
   * 收窄出一个空屏再弹一句「没有数据」,只会让人去找那一段在哪。
   */
  const scopeVehicle = (key: DimKey, idx: number) => {
    const dim = VEHICLE_DIMS.find((d) => d.key === key);
    const dict = DIM_SOURCE[key](meta, stats)[2];
    const raw = dict?.[idx] ?? '—';
    const label = idx === 0 ? '未填' : key === 'newEnergy' ? newEnergyNameOf(raw) : raw;
    const n =
      idx === 0
        ? DIM_SOURCE[key](meta, stats)[1]
        : (DIM_SOURCE[key](meta, stats)[0].find(([i]) => i === idx)?.[1] ?? 0);
    if (n <= 0) return;
    setMapScope({
      label: `车辆属性 · ${dim?.name ?? ''} · ${label}`,
      ownNatures: key === 'ownNature' ? [idx] : undefined,
      newEnergy: key === 'newEnergy' ? [idx] : undefined,
      vehicleClasses: key === 'vehicleClass' ? [idx] : undefined,
    });
  };

  /**
   * 那张榜的口径行。拼成字符串再交给 JSX:写在标签里换行会被折成一个空格,
   * 中文句子中间就多出缝来了,而这一段是给人照着念的。
   */
  const placeHint = [
    `按出险天数排序:同一处约 ${cellM} 米见方的位置,在统计期里有多少个自然日出过案。`,
    '天数长、跨度大而案件总数不突出的位置,在这张表上才看得见 —— 案件最多的位置与黑点清单的排序另有依据(超出正常水平的程度)。',
    '点一行看这一处的案件。',
  ].join(' ');

  /**
   * 车辆属性页签的内容(页签第一位,见本文件顶部那段说明)。
   *
   * 三个维度各一张自绘 SVG 环图:使用性质、是否新能源、车种大类。环上每一段、图例每一行
   * 都点得开,落点是地图:把这一类车的出险地铺出来,再点屏上任意一处就是这一类的案件清单。
   * 未填(字典下标 0)是数据里没写这一项的记录,不参与名次、单独列在环图末段,但一样算进分母。
   *
   * 之所以放第一页签:车辆属性是这次新增的三维,决策者最先要看的正是「新能源车占比多少、
   * 哪些使用性质出事多、车种大类怎么分布」;原先这些数根本不在界面上,现在把它们顶到最前。
   */
  const VehicleTabContent = () => {
    return (
      <div className="hm-sectcard" style={{ marginTop: 4 }}>
        <SectionTitle icon={<CarOutlined />} style={{ marginBottom: 6 }}>
          车辆属性构成
        </SectionTitle>
        {VEHICLE_DIMS.map((d) => {
          if (dimStale(d.key)) return <DimStaleNote key={d.key} dim={d.name} />;
          const { segs, total } = dimSegments(d.key);
          return (
            <VehicleDonut
              key={d.key}
              title={d.name}
              segments={segs}
              total={total}
              onPick={(idx) => scopeVehicle(d.key, idx)}
              pickTitle={(s) =>
                `${s.label}:${fmtInt(s.value)} 起,占 ${fmtPercent(s.value, total)}|点开在地图上看这一类的出险地`
              }
            />
          );
        })}
        {matched > 0 && (
          <div className="hm-board__more">
            <button
              type="button"
              className="hm-more"
              onClick={() => openStatsBoard('vehicles')}
              title="展开车辆属性三个维度的完整榜单"
            >
              查看全部 <ArrowRightOutlined />
            </button>
          </div>
        )}
      </div>
    );
  };

  return (
    <Panel title="风险概览" className="hm-panel--fluid" {...collapse}>
      {/* 命中案件:标准 KPI 数据卡。两行说清「命中多少 / 占全量多少」,
          右端「查看清单」是唯一的操作出口;不加渐变、阴影、位移或装饰性图标。 */}
      <button
        type="button"
        className="hm-hero"
        onClick={() => openRoster({ source: '命中案件 · 当前筛选' })}
        title="点开看这些案件的清单"
      >
        <span className="hm-hero__top">
          <span className="hm-hero__k">命中案件</span>
          <span className="hm-hero__meta">
            {statsLoading ? '计算中…' : `占全量 ${fmtPercent(matched, meta.count)}`}
          </span>
        </span>
        <span className="hm-hero__row">
          <span className="hm-hero__v">
            {fmtInt(matched)}
            <span className="hm-hero__unit">起</span>
          </span>
          <span className="hm-hero__more">查看清单</span>
        </span>
      </button>

      {/* 营运区分:命中这批案子「是不是营运车」是本次要看的第一件事,所以紧跟命中案件之后。
          一级比例条讲营运占全量多少,二级领地卡讲营运内部各占多少(五类始终铺满,与报表同口径)。
          条上点一截、榜上点一行,都是把地图收窄到这一类。 */}
      <div className="hm-sectcard">
        <SectionTitle
          icon={<CarOutlined />}
          style={{ marginBottom: 12 }}
          extra={
            <HelpDot
              label="营运区分说明"
              text="点营运 / 非营运,把地图收窄到这一类查看出险位置。"
            />
          }
        >
          营运区分
        </SectionTitle>
        <OperatingWidget
          meta={meta}
          stats={stats}
          variant="panel"
          onScope={(idxs, label) => {
            if (idxs.length === 0) return;
            setMapScope({ label, operatingSegments: idxs });
          }}
        />
        {matched > 0 && (
          <div className="hm-board__more">
            <button
              type="button"
              className="hm-more"
              onClick={() => openStatsBoard('operating')}
              title="展开营运区分的完整榜单:五类营运车逐类列出车辆数、占营运比、新能源车辆数与新能源占比"
            >
              查看全部 <ArrowRightOutlined />
            </button>
          </div>
        )}
      </div>

      <div className="hm-sectcard">
        <SectionTitle
          icon={<AimOutlined />}
          style={{ marginBottom: 12 }}
          extra={
            <HelpDot
              label="集中程度说明"
              text="头部几个区、几条街占多大比重;命中的案子在车辆属性三个维度上怎么分布。"
            />
          }
        >
          集中程度与构成
        </SectionTitle>
        <StatGrid columns={2}>
          <StatTile
            label="前 3 个区"
            value={fmtPercent(top3District, matched)}
            hint={`${fmtCompact(top3District)} 起`}
            tone="primary"
            className={sameIds(mapScope?.districts, top3DistrictIdx) ? 'hm-stat--active' : undefined}
            onClick={
              top3DistrictIdx.length > 0
                ? () => {
                    if (sameIds(mapScope?.districts, top3DistrictIdx)) setMapScope(null);
                    else
                      setMapScope({
                        label: topLabel(
                          '集中程度',
                          top3DistrictIdx.map((i) => meta.dict.districts[i] ?? ''),
                          '个区',
                        ),
                        districts: top3DistrictIdx,
                      });
                  }
                : undefined
            }
            tip="在地图上只看这 3 个区的事故热力与聚合点。再点一次恢复全市"
          />
          <StatTile
            label="前 5 条街道"
            value={fmtPercent(top5Street, matched)}
            hint={`${fmtCompact(top5Street)} 起`}
            tone="primary"
            className={sameIds(mapScope?.streets, top5StreetIdx) ? 'hm-stat--active' : undefined}
            onClick={
              top5StreetIdx.length > 0
                ? () => {
                    if (sameIds(mapScope?.streets, top5StreetIdx)) setMapScope(null);
                    else
                      setMapScope({
                        label: topLabel(
                          '集中程度',
                          top5StreetIdx.map((i) => meta.dict.streets[i] ?? ''),
                          '条街道',
                        ),
                        streets: top5StreetIdx,
                      });
                  }
                : undefined
            }
            tip="在地图上只看这 5 条街道的事故热力与聚合点。再点一次恢复全市"
          />
        </StatGrid>

        {/* 车辆属性构成:替换原来的「半数案件来自 N 处 / 八成案件来自 N 处」。
            那两块说的是「要动多少手才覆盖大半」,读的人多半停在数字上不知道拿它干什么;
            换成按维度铺一根条之后,同一块地方回答的是「这批案子都是什么车」。

            一个维度只画一根 100% 横向堆叠条:条内按各档起数分段、一段一色,段宽就是
            这一档在本维里的占比;条下面把所有类别逐项列成图例,色块与条上分段一一对应,
            窄到点不着的段也能从图例点。段和图例的落点与环图完全一致,都是收窄地图。

            这一块与上面「前 3 区 / 前 5 街道」两张卡片不是同一维度(那边讲空间集中程度、
            这边讲车辆属性结构),所以单独用 .hm-subhead 隔开、再框成一张浅底卡片。 */}
        <div className="hm-subhead">
          <span className="hm-subhead__k">车辆属性构成</span>
          <HelpDot
            label="车辆属性构成说明"
            style={{ marginLeft: 'auto' }}
            text="每一维按各档起数分段、一段一色,段宽就是这一档在本维里的占比;点任意一段或图例,把地图收窄到这一类查看出险位置。"
          />
        </div>
        <div className="hm-comp">
          {VEHICLE_DIMS.map((d) => {
            const { segs, total: dimTotal } = dimSegments(d.key);
            const titleOf = (s: DonutSegment) =>
              `${s.label}:${fmtInt(s.value)} 起,占 ${fmtPercent(s.value, dimTotal)}`;
            return (
              <div className="hm-comp__row" key={d.key}>
                <span className="hm-comp__name">{d.name}</span>
                {/* 一个维度一根条:flex-grow 按各档起数分配,段宽就是占比,不必自己算百分比 */}
                <div className="hm-comp__bar">
                  {segs.map((s) => (
                    <button
                      type="button"
                      key={s.idx}
                      className="hm-comp__seg"
                      style={{ flex: `${s.value} 1 0`, background: s.color }}
                      onClick={() => scopeVehicle(d.key, s.idx)}
                      title={titleOf(s)}
                      aria-label={titleOf(s)}
                    />
                  ))}
                </div>
                {/* 图例:本维所有类别逐项列出,色块与条上分段一一对应,窄段也能从这里点 */}
                <div className="hm-comp__legend">
                  {segs.map((s) => (
                    <button
                      type="button"
                      key={s.idx}
                      className="hm-comp__lg"
                      onClick={() => scopeVehicle(d.key, s.idx)}
                      title={titleOf(s)}
                    >
                      <i className="hm-comp__dot" style={{ background: s.color }} />
                      <span className="hm-comp__lgName">{s.label}</span>
                      <span className="hm-comp__lgVal">{fmtCompact(s.value)}</span>
                    </button>
                  ))}
                </div>
              </div>
            );
          })}
        </div>
      </div>

      <Tabs
        className="hm-stat-tabs"
        defaultActiveKey="vehicles"
        items={[
          {
            key: 'vehicles',
            label: '车辆属性',
            children: <VehicleTabContent />,
          },
          {
            key: 'space',
            label: '空间分布',
            // 空间分布:区域 / 时段×区域 / 街道 / 道路 / 点位
            children: (
              <>
                <div className="hm-sectcard">
                    <SectionTitle
                      icon={<GlobalOutlined />}
                      style={{ marginBottom: 12 }}
                      extra={<SpotlightEntry kind="districts" />}
                    >
                      区域分布(TOP {Math.min(districtList.length, 8)})
                  </SectionTitle>
                  {districtUnresolved > 0 && (
                    <div className="hm-field__tip" style={{ marginBottom: 8 }}>
                      地址未标注行政区的记录单列于榜末,不参与名次
                    </div>
                  )}
                  <div className="hm-splitbar">
                    {districtList.slice(0, 8).map(([idx, n], i) => {
                      const active =
                        !!mapScope?.districts && mapScope.districts.length === 1 && mapScope.districts[0] === idx;
                      return (
                        <RankRow
                          key={idx}
                          label={meta.dict.districts[idx]}
                          count={n}
                          matched={matched}
                          max={maxDistrict}
                          color={RANK_COLORS[i % RANK_COLORS.length]}
                          active={active}
                          title={
                            active
                              ? `取消只看${meta.dict.districts[idx]}(恢复全市)`
                              : `在地图上只看${meta.dict.districts[idx]}的事故热力与聚合点`
                          }
                          onClick={() => {
                            if (active) setMapScope(null);
                            else
                              setMapScope({
                                label: `区域分布 · ${meta.dict.districts[idx]}`,
                                districts: [idx],
                              });
                          }}
                        />
                      );
                    })}

                    {districtUnresolved > 0 && unresolvedDistrictIdx >= 0 && (
                      <UnresolvedRow
                        label="未标注行政区"
                        count={districtUnresolved}
                        tip="这些记录的地址里读不出行政区,没法归到某个区,所以不排进上面这张榜。这里只交代一共有多少起,不画条形:读不出来的量取决于地址怎么写,和单个区不是一种比法。"
                        // 这一档点得开:它不是一个区名,而是「区下标 = 未识别」的那批记录,
                        // 藏起来不给看,就等于把「地址读不出来」这件事的量只留在一个数字上
                        active={
                          !!mapScope?.districts &&
                          mapScope.districts.length === 1 &&
                          mapScope.districts[0] === unresolvedDistrictIdx
                        }
                        onClick={() => {
                          const active =
                            !!mapScope?.districts &&
                            mapScope.districts.length === 1 &&
                            mapScope.districts[0] === unresolvedDistrictIdx;
                          if (active) setMapScope(null);
                          else
                            setMapScope({
                              label: '区域分布 · 未标注行政区',
                              districts: [unresolvedDistrictIdx],
                            });
                        }}
                      />
                    )}

                    {districtList.length === 0 && districtUnresolved === 0 && (
                      <div className="hm-splitbar__empty">当前筛选无数据</div>
                    )}
                  </div>

                  {/* 榜上只贴前几名,剩下的不能变成「看不见就没有」。点开是右缘那张抽屉,
            与点聚合圆圈看案件明细同一个动线,所以入口也叫「查看全部」。 */}
                  {districtList.length > 0 && (
                    <div className="hm-board__more">
                      <button
                        type="button"
                        className="hm-more"
                        onClick={() => openStatsBoard('districts')}
                        title={`展开全部 ${fmtInt(districtList.length)} 个区的案件数与占比`}
                      >
                        查看全部 <ArrowRightOutlined />
                      </button>
                    </div>
                  )}
                </div>

                {crossRows.length > 0 && (
                  <div className="hm-sectcard">
                    <SectionTitle
                      icon={<FieldTimeOutlined />}
                      style={{ marginBottom: 12 }}
                      extra={
                        <HelpDot
                          label="时段分布说明"
                          text="格子里的数字是这一段占本区全天案件的比重;最后一列是夜间(晚 10 点到次日早 6 点)占本区的比重。没有案子的格子不涂色。读不出行政区的那些记录不在表内,起数在上一张榜末单列。点一格看这一区这一时段的清单。"
                        />
                      }
                    >
                      各区的时段形状(案件最多的 {crossRows.length} 个区)
                    </SectionTitle>
                    <div className="hm-cross">
                      <div className="hm-cross__head">
                        <span className="hm-cross__name" />
                        {TIME_BANDS.map((b) => (
                          <span className="hm-cross__band" key={b.label}>
                            {b.label}
                          </span>
                        ))}
                        <span className="hm-cross__night">夜间</span>
                      </div>
                      {crossRows.map((r) => {
                        const night = r.night;
                        return (
                          <div className="hm-cross__row" key={r.idx}>
                            <span className="hm-cross__name" title={r.name}>
                              {r.name}
                            </span>
                            {r.bands.map((n, bi) => {
                              const share = r.total > 0 ? n / r.total : 0;
                              const rel = r.rowMax > 0 ? n / r.rowMax : 0;
                              return (
                                <button
                                  type="button"
                                  className={`hm-cross__cell${n === 0 ? ' is-empty' : ''}`}
                                  key={bi}
                                  style={{
                                    // 底色走地图上那条「案件密度」色阶:越挤越往红端(取色与字色的
                                    // 规矩见 palette.densityCellFill / densityCellInk,抽屉那张 24 格
                                    // 矩阵用同两个函数,两处必然同色)。
                                    // 0 起那一格不进去比:色阶的冷端本身就是「有案但少」,涂上去就成
                                    // 了「有一点点案」,而它其实是零。用中性分隔色,两套编码分开。
                                    ...(n === 0
                                      ? { background: 'var(--hm-divider)' }
                                      : {
                                          background: densityCellFill(rel),
                                          color: densityCellInk(rel),
                                        }),
                                  }}
                                  title={`${r.name} · ${TIME_BANDS[bi].label}(${hourLabel(TIME_BANDS[bi].from)}—${hourLabel(TIME_BANDS[bi].to)})${fmtInt(n)} 起,占本区 ${fmtPercent(n, r.total)}${n > 0 ? ',点击查看这一档的案件清单' : ''}`}
                                  disabled={n === 0}
                                  onClick={() =>
                                    openRoster({
                                      source: `时段 × 区域 · ${r.name} ${TIME_BANDS[bi].label}`,
                                      pick: { districts: [r.idx] },
                                      mapScope: { districts: [r.idx] },
                                      where: { hours: hoursOfBandIdx(bi) },
                                    })
                                  }
                                >
                                  {Math.round(share * 100)}
                                </button>
                              );
                            })}
                            <span
                              className="hm-cross__night"
                              title={`夜间(晚 10 点到次日早 6 点)${fmtInt(night)} 起,占本区 ${fmtPercent(night, r.total)}`}
                            >
                              {fmtPercent(night, r.total)}
                            </span>
                          </div>
                        );
                      })}
                    </div>
                    {matched > 0 && (
                      <div className="hm-board__more">
                        <button
                          type="button"
                          className="hm-more"
                          onClick={() => openStatsBoard('cross')}
                          title="展开全部行政区与 24 小时的完整矩阵"
                        >
                          查看全部 <ArrowRightOutlined />
                        </button>
                      </div>
                    )}
                  </div>
                )}

                <div className="hm-sectcard">
                    <SectionTitle
                      icon={<NodeIndexOutlined />}
                      style={{ marginBottom: 12 }}
                      extra={
                        <>
                          <SpotlightEntry kind="streets" />
                          <HelpDot
                            label="高频街道榜单说明"
                            text="读不出街道名的记录不计入本榜:地址里没写出街道名的记录不是一条街,混进名次会被读成「有一条叫未识别的街道最危险」。这一屏只答哪条街案子多,点一行把地图收窄到这一条街。"
                          />
                        </>
                      }
                    >
                      高频街道(TOP {Math.min(streetList.length, SPOTLIGHT_TOP_N.streets)})
                    </SectionTitle>
                  {/* 读不出街道名的那些记录不进这张榜,也不在榜末另起一行交代 ——
            它们不是一个街道名,量级只取决于地址写得全不全,混进名次会被读成
            「有一条叫未识别的街道最危险」。不计数即不列,这一屏只答「哪条街案子多」。
            抽屉的口径行里写了一句「不计入本榜」(那里是逐行核数的地方)。 */}
                  <div className="hm-splitbar">
                    {streetList.slice(0, SPOTLIGHT_TOP_N.streets).map(([idx, n], i) => {
                      const name = streetNameOf(meta.dict.streets[idx]);
                      return (
                        <RankRow
                          key={idx}
                          label={name}
                          count={n}
                          matched={matched}
                          max={maxStreet}
                          // 街道榜的配色向右挪两档:与上面区榜错开,同一屏幕里两张榜不会看着像同一组
                          color={RANK_COLORS[(i + 2) % RANK_COLORS.length]}
                          // 点一条街 = 把地图上画的那批点收窄到这一条街:热力图与聚合点照旧在场,
                          // 深浅与数字按这一条街重算。与「点车辆属性某一类」同一条动线 ——
                          // 榜上那一行给的是名次,接着要问的必然是「那这些案子出在哪儿」;
                          // 再点屏上任意一格,出来的就是这一条街的案件清单。
                          title={`把地图收窄到${name}`}
                          onClick={() =>
                            setMapScope({ label: `高频街道 · ${name}`, streets: [idx] })
                          }
                        />
                      );
                    })}

                    {streetList.length === 0 && (
                      <div className="hm-splitbar__empty">当前筛选无数据</div>
                    )}
                  </div>

                  {streetList.length > 0 && (
                    <div className="hm-board__more">
                      <button
                        type="button"
                        className="hm-more"
                        onClick={() => openStatsBoard('streets')}
                        title={`展开全部 ${fmtInt(streetList.length)} 条街道的案件数与占比`}
                      >
                        查看全部 <ArrowRightOutlined />
                      </button>
                    </div>
                  )}
                </div>

                {road === null ? (
                  !detailReady &&
                  stats && (
                    <div className="hm-field__tip" style={{ marginTop: 18 }}>
                      道路与路段榜要逐条读详细地址,地址列载入后自动补上
                    </div>
                  )
                ) : (
                  <div className="hm-sectcard">
                    <SectionTitle
                      icon={<BranchesOutlined />}
                      style={{ marginBottom: 12 }}
                      extra={
                        <>
                          <SpotlightEntry kind="roads" />
                          <HelpDot
                            label="高频道路榜单说明"
                            text="路名取自地址里明写的道路字样,一段地址只认第一个;它不是行政边界,同一条路被不同写法拆开时会被分成两档。"
                          />
                        </>
                      }
                    >
                      高频道路(TOP {Math.min(road.counts.length, SPOTLIGHT_TOP_N.roads)})
                    </SectionTitle>
                    <div className="hm-splitbar">
                      {road.counts.slice(0, SPOTLIGHT_TOP_N.roads).map(([idx, n], i) => (
                        <RankRow
                          key={idx}
                          label={road.names[idx]}
                          count={n}
                          matched={matched}
                          max={maxRoad}
                          color={RANK_COLORS[(i + 4) % RANK_COLORS.length]}
                          title={`把地图收窄到${road.names[idx]}`}
                          onClick={() =>
                            setMapScope({ label: `高频道路 · ${road.names[idx]}`, roads: [idx] })
                          }
                        />
                      ))}

                      {road.counts.length === 0 && (
                        <div className="hm-splitbar__empty">当前筛选无数据</div>
                      )}
                    </div>

                    {road.counts.length > 0 && (
                      <div className="hm-board__more">
                        <button
                          type="button"
                          className="hm-more"
                          onClick={() => openStatsBoard('roads')}
                          title={`展开全部 ${fmtInt(road.counts.length)} 条道路的案件数与占比`}
                        >
                          查看全部 <ArrowRightOutlined />
                        </button>
                      </div>
                    )}
                  </div>
                )}

                {placeRows.length > 0 && (
                  <div className="hm-sectcard">
                    <SectionTitle
                      icon={<HistoryOutlined />}
                      style={{ marginBottom: 12 }}
                      extra={
                        <>
                          <SpotlightEntry kind="places" />
                          <HelpDot text={placeHint} label="反复出险位置榜单说明" />
                        </>
                      }
                    >
                      反复出险的位置(TOP {placeRows.length})
                    </SectionTitle>
                    <div className="hm-place">
                      {placeRows.map((p, i) => {
                        // 三段里能读出几段就读几段:详情列还没到位时自然退回「区 · 街道」,
                        // 全读不出(连区都没有)才退回坐标 —— 「未识别」不是地名。
                        const name = placeLabelOf(meta.dict, p);
                        return (
                          <button
                            type="button"
                            key={`${p.minLng}:${p.minLat}`}
                            className="hm-place__row"
                            title={`查看这一处约 ${cellM} 米见方位置内的案件清单`}
                            onClick={() => openPlaceRoster(p)}
                          >
                            <span className="hm-place__rank">{i + 1}</span>
                            <span className="hm-place__main">
                              <span className="hm-place__name" title={name}>
                                {name || `${p.lat.toFixed(4)}, ${p.lng.toFixed(4)}`}
                              </span>
                              <span className="hm-place__meta">
                                <b>{fmtInt(p.days)} 天有案</b>
                                <em>{fmtCompact(p.count)} 起</em>
                                <em>跨度 {fmtInt(p.spanDays)} 天</em>
                                <em title={`统计期最后 ${placeRecentDays} 天内这一处的案件数`}>
                                  近 {placeRecentDays} 天 {fmtCompact(p.recentCases)} 起
                                </em>
                              </span>
                            </span>
                            <span className="hm-place__last">
                              {fmtDate(p.lastTs)}
                              <em>
                                {p.idleDays === 0
                                  ? '期末仍在出案'
                                  : `末案之后 ${fmtInt(p.idleDays)} 天未出案`}
                              </em>
                            </span>
                          </button>
                        );
                      })}
                    </div>
                    <div className="hm-board__more">
                      <button
                        type="button"
                        className="hm-more"
                        onClick={() => openStatsBoard('places')}
                        title="展开反复出险位置清单(按出险天数排序)"
                      >
                        查看全部 <ArrowRightOutlined />
                      </button>
                    </div>
                  </div>
                )}
              </>
            ),
          },
          {
            key: 'time',
            label: '时间规律',
            children: <TimeBoard compact />,
          },
        ]}
      />

      <PerfFootlines />
    </Panel>
  );
}

/**
 * 底部那两行耗时。
 *
 * 与上面同一套理由:重算耗时跟着聚合走,统计耗时跟着筛选走,两样都不该拖着整屏榜重画。
 */
function PerfFootlines() {
  const aggregateMs = useHeatmapStore((s) => s.perf.aggregateMs);
  const statsMs = useHeatmapStore((s) => s.perf.statsMs);

  return (
    <>
      <div className="hm-kv" style={{ marginTop: 16 }}>
        <span className="hm-kv__k">重算耗时</span>
        <span className="hm-kv__v">{fmtMs(aggregateMs)}</span>
      </div>
      <div className="hm-kv">
        <span className="hm-kv__k">统计耗时</span>
        <span className="hm-kv__v">{fmtMs(statsMs)}</span>
      </div>
    </>
  );
}

/**
 * 分类标题:一个小图标 + 标题文字。
 *
 * 右栏堆到七块榜之后,一样大小的灰字标题已经分不开「这是哪一类」了,所以每块前面钉一个
 * 固定图标:形状各不相同,扫视时先认形状再认字,比逐条读完标题快。
 * 图标不承载读数也不跟色阶走(口径见 design.css 的 .hm-sect__ico)—— 这些榜里能比的只有
 * 案件数和占比,图标一显眼就会变成第二套排名。
 *
 * 字号、字重仍然用 `.hm-field__text` 那一份:只是让标题排成一行,不因加了图标而变粗变大。
 *
 * `extra` 是这一行右端那颗入口(「在地图上看」),必须是本行的直接子节点:
 * `.hm-spot-entry-wrap--section` 靠 `margin-left: auto` 贴右,塞进标题那个 `<span>` 里
 * 就跟着文字走了,会贴在标题后面而不是行末 —— 抽屉标题右侧那颗与它同一套对齐规矩。
 */
function SectionTitle({
  icon,
  children,
  extra,
  style,
}: {
  icon: ReactNode;
  children: ReactNode;
  extra?: ReactNode;
  style?: CSSProperties;
}) {
  return (
    <div className="hm-field__text hm-sect" style={style}>
      <span className="hm-sect__ico" aria-hidden>
        {icon}
      </span>
      <span>{children}</span>
      {extra}
    </div>
  );
}

/**
 * 榜单上的一行:名称、案件数、占命中、按本榜榜首归一的条形。
 *
 * 区榜、街道榜、道路榜的形状完全一样,只在配色档位与点开的入口上有差别,
 * 所以收成一个组件 —— 三处各写一份的话,改一处口径就会漏掉另外两处
 * (榜末「未标注」那一档已经吃过一次这种亏)。
 */
function RankRow({
  label,
  count,
  matched,
  max,
  color,
  title,
  active,
  onClick,
}: {
  label: string;
  count: number;
  matched: number;
  max: number;
  color: string;
  title: string;
  active?: boolean;
  onClick: () => void;
}) {
  return (
    <button
      type="button"
      className={
        'hm-splitbar__row hm-splitbar__row--link' + (active ? ' hm-splitbar__row--active' : '')
      }
      title={title}
      onClick={onClick}
    >
      <div className="hm-splitbar__head">
        <span className="hm-splitbar__label">{label}</span>
        <span className="hm-splitbar__value">
          {fmtCompact(count)}
          <em>{fmtPercent(count, matched)}</em>
        </span>
      </div>
      <div className="hm-splitbar__track">
        <div
          className="hm-splitbar__fill"
          style={{
            width: `${max ? (count / max) * 100 : 0}%`,
            background: color,
          }}
        />
      </div>
    </button>
  );
}