HeaderBar.tsx 12.6 KB
import { type CSSProperties, type ReactNode } from 'react';
import { useNavigate } from 'react-router-dom';
import { Avatar, Button, Dropdown, Tooltip } from 'antd';
import { BrandMark } from '@hm/ui';
import { useHeatmapStore } 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,
  DatabaseOutlined,
  FullscreenExitOutlined,
  FullscreenOutlined,
  LogoutOutlined,
  UserOutlined,
} from '@ant-design/icons';

function Pill({
  icon,
  label,
  value,
  tip,
}: {
  icon: ReactNode;
  label: string;
  value: ReactNode;
  /** 悬浮说明:这个数字是从哪儿来的、精确到个位是多少 */
  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>
  );
}

/** 顶栏:品牌 + 项目语境 + 数据状态概览。纯展示,不持有状态 */
export function HeaderBar() {
  const meta = useHeatmapStore((s) => s.meta);
  const status = useHeatmapStore((s) => s.status);
  const dataOrigin = useHeatmapStore((s) => s.dataOrigin);
  const dataReady = useHeatmapStore((s) => s.dataReady);
  const importInfo = useHeatmapStore((s) => s.importInfo);
  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={
            dataReady ? (
              <span style={{ display: 'inline-flex', alignItems: 'center',  }}>
                <span
                  style={{
                    display: 'inline-block',
                    width: 8,
                    height: 8,
                    borderRadius: '50%',
                    background: '#52c41a',
                    marginRight: 6,
                    boxShadow: '0 0 0 3px rgba(82,196,26,0.22)',
                    color: '#52c41a'
                  }}
                />
                数据已就绪
              </span>
            ) : (
              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>
        )}
        <Tooltip title={isFs ? '退出全屏 (F / Esc)' : '一键全屏 (F)'}>
          <Button
            type="text"
            className="hm-header__icon-btn"
            icon={isFs ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
            onClick={toggleFs}
          />
        </Tooltip>
      </div>
    </header>
  );
}