HeaderBar.tsx 20 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
import { type CSSProperties, type ReactNode } from 'react';
import { useNavigate } from 'react-router-dom';
import { Avatar, Button, Dropdown, Popover, Switch, Tooltip } from 'antd';
import { BrandMark } from '@hm/ui';
import { LAYERS, useHeatmapStore, useHiddenLayers } from '@/store/useHeatmapStore';
import { useAuthStore } from '@/store/useAuthStore';
import { useFullscreen } from '@/layout/useFullscreen';
import { ImportControl } from '@/layout/ImportControl';
import type { MetaFile } from '@/features/heatmap/aggregate/types';
import type { ImportManifest } from '@/features/heatmap/data/importedDb';
import { fmtCompact, fmtDateTime, fmtInt, fmtPercent, spanDays } from '@/utils/format';
import {
  AppstoreOutlined,
  CalendarOutlined,
  CompressOutlined,
  DatabaseOutlined,
  ExpandOutlined,
  FundProjectionScreenOutlined,
  FullscreenExitOutlined,
  FullscreenOutlined,
  LayoutOutlined,
  LogoutOutlined,
  UserOutlined,
} from '@ant-design/icons';

function Pill({
  icon,
  label,
  value,
  tip,
}: {
  icon: ReactNode;
  label: string;
  value: string;
  /** 悬浮说明:这个数字是从哪儿来的、精确到个位是多少 */
  tip?: ReactNode;
}) {
  const body = (
    <div className="hm-map__stat-chip" style={{ borderRadius: 8 }}>
      <span style={{ color: 'var(--hm-primary)', display: 'inline-flex' }}>{icon}</span>
      {label}
      <b>{value}</b>
    </div>
  );
  // 压缩过的数字(4.1 万)必然对不上精确值,所以精确值与来源都写在悬浮里:
  // 拿顶栏的 4.3 万去对导入表格的行数,本来就对不上(表里有被拒收的行),不说清就成了「数据丢了」
  return tip ? (
    <Tooltip title={tip} styles={{ root: { maxWidth: 'none' } }}>
      {body}
    </Tooltip>
  ) : (
    body
  );
}

/** 导入时间那串 ISO 字符折成北京时间;缺字段或写坏时宁可不说,也不给一个「NaN」 */
function fmtImportedAt(iso: string): string | null {
  const ms = Date.parse(iso);
  return Number.isFinite(ms) ? fmtDateTime(Math.floor(ms / 1000)) : null;
}

/** tooltip 容器:antd Tooltip 默认深底白字,这里限定宽度并允许换行,长清单才不会被挤成一行 */
const TIP_STYLE: CSSProperties = {
  display: 'flex',
  flexDirection: 'column',
  maxWidth: 340,
  whiteSpace: 'normal',
  wordBreak: 'break-word',
  fontSize: 12,
  lineHeight: 1.5,
};
/** tooltip 里的分隔线(复用在深底上) */
const TIP_SEP: CSSProperties = {
  height: 1,
  background: 'rgba(255,255,255,0.2)',
  margin: '6px 0',
};
/** tooltip 里的脚注行:压缩口径的说明 */
const TIP_NOTE: CSSProperties = {
  marginTop: 4,
  color: 'rgba(255,255,255,0.6)',
  fontSize: 11,
  lineHeight: 1.5,
};

/**
 * 每类清洗剔除的判定条件,与 cleanRules.ts 的判定逻辑一一对应。
 * key 取自 `meta.rejectedReasons` 里「清洗剔除 · 」之后的那截 label。
 * 只在顶栏悬浮里把「凭什么剔」讲清,不参与任何计算。
 */
const CLEAN_CONDITION: Record<string, string> = {
  字段缺失: '行政区 / 街道 / 道路三列都为空,且出险地址文本也解析不出',
  海域与人工岛: '出险地址写明在深圳市辖区,但坐标在区界之外且距边界 ≥ 200m(跨海通道、港区这类)',
  边界外缘: '出险地址写明在深圳市辖区,但坐标在区界之外且距边界 < 200m(边界抽稀误差或定位微偏)',
  邻市: '出险地址与行政区列都读不出深圳市辖区,坐标也在区界之外',
  '孤立 · 200m 内无邻居': '半径 200m 内没有同批次的其他案件',
  '孤立 · 500m 内无邻居': '半径 500m 内没有同批次的其他案件(山路 / 公园 / 海边等偏远散点)',
  '孤立 · 1km 内无邻居': '半径 1km 内没有同批次的其他案件',
  道路低频: '同一条道路本批次案件数 ≤ 阈值(默认 1),对风险聚集无贡献',
  街道低频: '同一个街道本批次案件数 ≤ 阈值(默认 1),多半抓到「区 + 街道」错配的地址',
  小热点: '该点周围半径内(默认 1000m)案件数(含自身)≤ 阈值(默认 10),大视角下孤立小数字',
};
/** A 类结构化拒收的共同条件:源文件字段即非法,解析阶段直接拒收,根本没进清洗列 */
const STRUCTURAL_CONDITION = '源文件字段非法,解析阶段直接拒收,未进入清洗列';

/** tooltip 里单条「剔除数 + 条件」:数字与条件分两行,条件灰字退后 */
const COND_STYLE: CSSProperties = {
  margin: '1px 0 5px',
  paddingLeft: 16,
  color: 'rgba(255,255,255,0.6)',
  fontSize: 11,
  lineHeight: 1.45,
};
function ExcludeItem({ title, count, condition }: { title: string; count: number; condition: string }) {
  return (
    <>
      <li style={{ lineHeight: 1.6 }}>
        — {title}:<b>{fmtInt(count)}</b>
      </li>
      <li style={COND_STYLE}>原因:{condition}</li>
    </>
  );
}

/**
 * 顶栏「导入 n万」悬浮说明:把这次导入的来龙去脉讲清。
 *
 * 重点是用户要的两件事 ——
 *   1) 本次导入总数据(原始读入多少行);
 *   2) 剔除了哪些数据(按原因逐类列出,有理有据)。
 *
 * 数据全部来自 `meta`:count 是剔除后入库的条数、rejected 是累计剔除量(A 类结构化拒收
 * + 用户在报告里勾选的清洗剔除),二者相加即原始读入行数;rejectedReasons 则把每一类
 * 剔了多少逐条记着。三者刷新后都从 IndexedDB 回灌,悬浮一次就能自己核对。
 */
function buildImportTip(
  meta: MetaFile,
  importInfo: ImportManifest | null,
): ReactNode {
  const when = importInfo ? fmtImportedAt(importInfo.importedAt) : null;
  const total = meta.count + meta.rejected; // 原始读入行数 = 入库有效 + 已剔除
  const reasons = Object.entries(meta.rejectedReasons ?? {}).filter(([, n]) => n > 0);
  const CLEAN = '清洗剔除 · ';
  // A 类结构化拒收(坐标 / 时间 / 案件号非法等)与用户在报告里勾选的清洗剔除分两栏列
  const structural = reasons.filter(([k]) => !k.startsWith(CLEAN));
  const cleaned = reasons
    .filter(([k]) => k.startsWith(CLEAN))
    .map(([k, n]) => [k.slice(CLEAN.length), n] as const);

  return (
    <div style={TIP_STYLE}>
      <div>
        <b>导入自</b> {importInfo?.fileName ?? '(未知文件)'}
      </div>
      {when && <div style={{ marginTop: 2 }}>导入于 {when}(北京时间)</div>}
      <div style={TIP_SEP} />
      <div>
        本次导入 <b>{fmtInt(total)}</b> 条原始记录
      </div>
      <div style={{ marginLeft: 12, lineHeight: 1.7 }}>
        <div>· 入库有效 {fmtInt(meta.count)} 条</div>
        <div>
          · 已剔除 {fmtInt(meta.rejected)} 条(约占 {fmtPercent(meta.rejected, total)})
        </div>
      </div>
      {meta.rejected > 0 && (
        <ul style={{ margin: '4px 0 0 12px', padding: 0, listStyle: 'none' }}>
          {structural.map(([k, n]) => (
            <ExcludeItem key={k} title={`结构化拒收 · ${k}`} count={n} condition={STRUCTURAL_CONDITION} />
          ))}
          {cleaned.map(([k, n]) => (
            <ExcludeItem
              key={k}
              title={`清洗剔除 · ${k}`}
              count={n}
              condition={CLEAN_CONDITION[k] ?? '符合条件即剔除'}
            />
          ))}
        </ul>
      )}
      <div style={TIP_NOTE}>
        顶栏「{fmtCompact(meta.count)}」按「万」压缩,与表格行数、页面别处命中数不必逐位相同
      </div>
    </div>
  );
}

/**
 * 区块显示设置:屏上五个可收区块的总开关 + 一键全收 / 全展。
 * 注意左栏现在是栅格里的一列(不是浮层),收起它 = 该列宽度归零,
 * 另外四个仍是浮在地图上的层。两种机制共用这一张表,是因为对使用者来说
 * 它们都只回答一个问题:「这块能不能从屏上拿掉」。
 *
 * 为什么这五层要收在同一处:
 *   · **投屏讲话时**按一下「全部收起」,屏幕只剩地图和顶栏,讲的是态势不是控件;
 *   · **回到细节**再按一下「全部展开」,五层一起回来 —— 不必回想刚才分别关了几块。
 *
 * 为什么每行都要带一句 note 而不是只写名字:这五层里有三层的名字(地图读数 / 密度图例 /
 * 黑点清单)不点开就猜不到是哪块地。名字 + 一句位置说明,才构成「不用试就知道」。
 *
 * 单项开关的语义是**真实偏好**,不是临时隐藏:关掉之后刷新仍在关着吗?—— 不持久化。
 * 它跟「一次性视图状态」同命,因为大屏是多人在用的,持久化会让下一个人接手时
 * 面对一个「少了一块」的界面而查不到原因。这一条与概览卡片的位置偏好刻意区别对待:
 * 位置是「这块放哪」,收纳是「这块在不在」,后者更该每次从全开起步。
 */
function LayerPanel() {
  const hidden = useHiddenLayers();
  const setLayerHidden = useHeatmapStore((s) => s.setLayerHidden);
  const toggleCollapseAll = useHeatmapStore((s) => s.toggleCollapseAll);
  const collapsedFrom = useHeatmapStore((s) => s.collapsedFrom);
  const analysisOn = useHeatmapStore((s) => s.analysisOn);

  const allCollapsed = LAYERS.every((l) => hidden[l.id]);
  const shownCount = LAYERS.filter((l) => !hidden[l.id]).length;
  // 还原会回到几块:快照里没被收的那几块。收起态下第 4 级用词要说准,
  // 因为「还原」与「全部展开」在默认态下差着一块(图例起步是收成小牌的)
  const restoreCount = collapsedFrom
    ? LAYERS.filter((l) => !collapsedFrom[l.id]).length
    : LAYERS.length;

  return (
    <div className="hm-layers">
      <div className="hm-layers__head">
        <span className="hm-layers__title">屏上区块</span>
        <span className="hm-layers__stat">
          {shownCount} / {LAYERS.length} 显示中
        </span>
      </div>

      <ul className="hm-layers__list">
        {LAYERS.map((l) => {
          /* 黑点清单只有开了降噪才有东西可列。这一行的开关此时点了也不会有反应,
             与其让它变成一个「假的」控件,不如直接说明为什么现在没内容。
             其余四层不需要这个判断 —— 它们与数据无关,永远存在。

             降噪开关本身也住在左栏读数块的第 2 页。若左栏恰好被收起,这里就成了一句
             指向屏外开关的废提示,所以要把出口一并写出来:「先展开左栏读数」。 */
          const dormant = l.id === 'dock' && !analysisOn;
          const dormantTag = !dormant
            ? null
            : hidden.overview
              ? '未开启降噪 · 先展开「左栏读数」第 2 页'
              : '未开启降噪';
          return (
            <li key={l.id} className={`hm-layers__row${dormant ? ' is-dormant' : ''}`}>
              <span className="hm-layers__meta">
                <span className="hm-layers__label">
                  {l.label}
                  {dormantTag && <em className="hm-layers__tag">{dormantTag}</em>}
                </span>
                <span className="hm-layers__note">{l.note}</span>
              </span>
              <Switch
                size="small"
                checked={!hidden[l.id]}
                disabled={dormant}
                onChange={(v) => setLayerHidden(l.id, !v)}
                aria-label={`显示${l.label}`}
              />
            </li>
          );
        })}
      </ul>

      {/* 两颗按钮同一个位置:收起与展开是成对操作,位置相同、形式相同、用词相对,
          闭着眼也知道下一句该点哪儿(对称性交互)。
          注意这里第二颗叫「还原」而不是「全部展开」:收起是一次临时让位,
          还原必须精确回到收起前那一屏 —— 把图例这种本来收着的东西一起摊开,
          就不叫还原了。真要全摊开,逐个开关往上拨即可。 */}
      <div className="hm-layers__foot">
        {allCollapsed ? (
          <Button size="small" type="primary" block onClick={toggleCollapseAll}>
            还原到收起前({restoreCount} 块)
          </Button>
        ) : (
          <Button size="small" block onClick={toggleCollapseAll}>
            全部收起(只留地图)
          </Button>
        )}
        <div className="hm-layers__hint">
          收起只是不显示,筛选、降噪参数与深潜里的东西一件都不会丢。
        </div>
      </div>
    </div>
  );
}

/** 顶栏:品牌 + 项目语境 + 数据状态概览。纯展示,不持有状态 */
export function HeaderBar() {
  const meta = useHeatmapStore((s) => s.meta);
  const status = useHeatmapStore((s) => s.status);
  const dataOrigin = useHeatmapStore((s) => s.dataOrigin);
  const importInfo = useHeatmapStore((s) => s.importInfo);
  const deepDive = useHeatmapStore((s) => s.deepDive);
  const openDeepDive = useHeatmapStore((s) => s.openDeepDive);
  const hiddenLayers = useHiddenLayers();
  const hiddenCount = LAYERS.filter((l) => hiddenLayers[l.id]).length;
  const allCollapsed = hiddenCount === LAYERS.length;
  const toggleCollapseAll = useHeatmapStore((s) => s.toggleCollapseAll);
  const coverage = meta ? spanDays(meta.timeRange.min, meta.timeRange.max) : 0;
  const { active: isFs, toggle: toggleFs } = useFullscreen();
  const username = useAuthStore((s) => s.user?.username);
  const logout = useAuthStore((s) => s.logout);
  const navigate = useNavigate();

  /**
   * 数字是从哪份数据来的,写在悬浮里。
   *
   * 顶栏只有两格宽度,放不下「导入 43,182 条 · 来自 xxx.xlsx」这一长句,
   * 于是同一个位置在「导入」和「样本」之间换过来源时,看起来就像同一个数在跳。
   * 这里不改变显示的数字,只把来源、精确条数与口径差别说清 —— 悬浮一次就能自己核对。
   * 导入态额外讲清「本次导入总数据」与「剔除了哪些数据」(见 buildImportTip)。
   */
  const sourceTip: ReactNode = (() => {
    if (!meta) return null;
    const note = (
      <div style={TIP_NOTE}>
        顶栏「{fmtCompact(meta.count)}」按「万」压缩,与表格行数、页面别处命中数不必逐位相同
      </div>
    );
    if (dataOrigin === 'imported') {
      return buildImportTip(meta, importInfo);
    }
    // 空态时 meta 为 null(上面已提前 return),这里只兜一句「未导入」;
    // 不再有「本地静态产物(public/data)」这种已废弃的示例数据说法。
    return (
      <div style={TIP_STYLE}>
        <div>尚未导入数据</div>
        <div style={{ marginTop: 2, opacity: 0.75 }}>请通过顶栏「导入数据」选择本地 xlsx / csv</div>
        {note}
      </div>
    );
  })();

  const coverageTip = meta
    ? [
        `报案时间跨度 ${fmtDateTime(meta.timeRange.min)} — ${fmtDateTime(meta.timeRange.max)}`,
        '按北京时间自然日计天数',
      ].join(' · ')
    : null;

  const statusText =
    status === 'ready'
      ? '数据已就绪'
      : status === 'loading'
        ? '数据加载中'
        : status === 'empty'
          ? '无数据'
          : status === 'error'
            ? '加载失败'
            : '等待初始化';

  return (
    <header className="hm-header">
      <div className="hm-header__left">
        <BrandMark />
        <div className="hm-header__axis" aria-hidden />
        <div className="hm-header__context">
          <div className="hm-header__context-title">深圳车险出险位置-9月风险热力图</div>
          <div className="hm-header__context-sub">智能网联监管平台 · 事故出险点位分析</div>
        </div>
      </div>

      <div className="hm-header__right">
        <Pill
          icon={<DatabaseOutlined />}
          label={dataOrigin === 'imported' ? '导入' : '未导入'}
          value={meta ? fmtCompact(meta.count) : '—'}
          tip={sourceTip}
        />
        <Pill
          icon={<CalendarOutlined />}
          label="覆盖"
          value={coverage ? `${coverage}天` : '—'}
          tip={coverageTip}
        />
        <Pill icon={<AppstoreOutlined />} label="状态" value={statusText} />
        <ImportControl />
        {username && (
          <Dropdown
            menu={{
              items: [{ key: 'logout', icon: <LogoutOutlined />, label: '退出登录' }],
              onClick: async ({ key }) => {
                if (key === 'logout') {
                  // 退出后主动跳转,不依赖路由守卫的被动重定向(SPA 内被动 Navigate 在你的环境偶发不生效)
                  await logout();
                  navigate('/login', { replace: true });
                }
              },
            }}
          >
            <Button
              type="text"
              className="hm-header__icon-btn"
              style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}
            >
              <Avatar size="small" icon={<UserOutlined />} />
              {username}
            </Button>
          </Dropdown>
        )}
        {/* 浮层总入口:一颗按钮管住屏上全部五层(概览 / 维度条 / 地图读数 / 图例 / 黑点清单)。
            这里替换掉原来那颗「概览眼睛」—— 那颗只管五分之一,剩下四层各藏各的开关,
            于是「把屏幕收干净」要跑四个地方。现在一个词(浮层)只指向一个地方。 */}
        <Popover
          trigger="click"
          placement="bottomRight"
          arrow={false}
          rootClassName="hm-layers-pop"
          content={<LayerPanel />}
        >
          <Button
            type={hiddenCount > 0 ? 'primary' : 'text'}
            className="hm-header__icon-btn hm-header__layers-btn"
            icon={<LayoutOutlined />}
            aria-label="区块显示设置"
          >
            {/* 收起了几层要说出来:屏上少了一块,人得知道是自己收的还是丢了。
                0 层时不显示,省一个没信息的角标。 */}
            {hiddenCount > 0 && <span className="hm-header__layers-count">{hiddenCount}</span>}
          </Button>
        </Popover>
        {/* 一键收起 / 还原:**不进 Popover**,就摆在顶栏上。
            理由是「收起全部」多半发生在要开始讲话的那一秒 —— 让人先点开面板、再找底部那颗按钮、
            再点一次,等于把两次点击的成本压在最短的那个时刻上。
            收起之后同一颗按钮变成「还原」,位置与形状都不动(对称性交互):
            按下去了哪儿,就知道该回哪儿点。 */}
        <Tooltip
          title={
            allCollapsed
              ? '还原收起前的区块布局(回到上一屏的样子,不是全部摊开)'
              : `一键收起全部 ${LAYERS.length} 块(只留地图)`
          }
        >
          <Button
            type={allCollapsed ? 'primary' : 'text'}
            className="hm-header__icon-btn"
            icon={allCollapsed ? <ExpandOutlined /> : <CompressOutlined />}
            onClick={toggleCollapseAll}
            aria-label={allCollapsed ? '还原区块布局' : '收起全部区块'}
          />
        </Tooltip>
        {/* 深潜 + 驾驶舱:两者都是「临时压屏」,所以与全屏钮并排放在最右,
            退出键(Esc)与它们的层级关系见 useKeyboardShortcuts */}
        <Tooltip title="深潜分析:矩阵、品牌 TopN、完整榜单(占 70% 屏宽,默认关,Esc 退出)">
          <Button
            type={deepDive === null ? 'text' : 'primary'}
            className="hm-header__icon-btn"
            icon={<FundProjectionScreenOutlined />}
            onClick={() => openDeepDive(deepDive === null ? 'region' : null)}
          />
        </Tooltip>
        <Tooltip title={isFs ? '退出全屏 (F / Esc)' : '一键全屏 (F)'}>
          <Button
            type="text"
            className="hm-header__icon-btn"
            icon={isFs ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
            onClick={toggleFs}
          />
        </Tooltip>
      </div>
    </header>
  );
}