代码
// 全部使用 JSAPI 4.0 内置覆盖物与图层;视角固定,只按时间轴回放数据。
// 站点位置与驾车路线为真实服务结果,桩数、占用、排队与故障为确定性演示模型。
const $ = (id) => document.getElementById(id);
const esc = (value) =>
  String(value ?? '').replace(
    /[&<>"']/g,
    (char) => ({'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'})[char],
  );
// 站点坐标由 BMap.LocalSearch 在国贸—三里屯检索“充电站”导出,按 260 米去重并剔除换电站与目的地慢充。
// 每项为 [编号, 名称, 经度, 纬度]。
// prettier-ignore
const stations = [
    ['s00', '朝阳宾馆', 116.47725, 39.92322], ['s01', '瑰丽酒店', 116.46727, 39.92629], ['s02', '千禧公寓', 116.46501, 39.92351],
    ['s03', '复星国际中心', 116.46281, 39.93018], ['s04', '朝外SOHO', 116.46142, 39.92606], ['s05', '恒祥大厦', 116.47245, 39.92985],
    ['s06', '尚都SOHO', 116.45858, 39.92405], ['s07', '国贸北区停车场', 116.4668, 39.91837], ['s08', '京广中心', 116.45856, 39.92835],
    ['s09', '阳光100', 116.48234, 39.91916], ['s10', '中期大厦', 116.47168, 39.92467], ['s11', '人民日报社', 116.4774, 39.926],
    ['s12', '康莱德酒店', 116.46666, 39.93271], ['s13', '东三环北路', 116.46689, 39.93506], ['s14', '光华路SOHO2', 116.45813, 39.92002],
    ['s15', '三里屯4号院', 116.46423, 39.93631], ['s16', '团结新里', 116.47709, 39.93429], ['s17', '朝阳医院', 116.45916, 39.93168],
    ['s18', '中信大厦', 116.47222, 39.91868], ['s19', '中海广场', 116.46322, 39.91665], ['s20', 'CBD万达广场', 116.47959, 39.91535],
    ['s21', '国贸商场', 116.46699, 39.91572], ['s22', '秀水国潮', 116.45669, 39.91583], ['s23', '赛特停车场', 116.44714, 39.91269],
    ['s24', '国际俱乐部', 116.44556, 39.91616], ['s25', '朝阳万邦兴旺', 116.44344, 39.92303], ['s26', '侨福芳草地', 116.45436, 39.92475],
    ['s27', '东城荷华明城', 116.44037, 39.91062], ['s28', '英皇集团中心', 116.45081, 39.91319], ['s29', '国雅大厦', 116.44685, 39.92199],
    ['s30', '通用国际中心', 116.45695, 39.91086], ['s31', '日坛国际贸易中心', 116.44987, 39.92614], ['s32', '悠唐购物中心', 116.44549, 39.92746],
    ['s33', '贡院', 116.44058, 39.91633], ['s34', '华声国际大厦', 116.44252, 39.91992], ['s35', '高级人民法院', 116.44516, 39.90938],
    ['s36', '丽舍公寓', 116.45014, 39.91035], ['s37', '八王坟', 116.48511, 39.90857], ['s38', '华贸中心', 116.48878, 39.91526],
    ['s39', '华商大厦', 116.48898, 39.92261], ['s40', '佳兆业广场', 116.48484, 39.91274], ['s41', '蓝堡国际中心南区', 116.48344, 39.91612],
    ['s42', '凯泰大厦', 116.49456, 39.92445], ['s43', '东区国际', 116.4928, 39.91905], ['s44', '国贸SKP', 116.48565, 39.91926],
    ['s45', '世茂大厦', 116.47726, 39.91316], ['s46', '国家广告产业园', 116.47849, 39.90932], ['s47', '东方梅地亚中心', 116.47964, 39.91789],
    ['s48', '首创大厦', 116.44284, 39.93769], ['s49', '华普国际大厦', 116.4444, 39.9308], ['s50', '永利国际', 116.4505, 39.9412],
    ['s51', '工人体育场', 116.45213, 39.93448], ['s52', '朝阳工体', 116.4506, 39.9367], ['s53', '世茂工三', 116.45588, 39.94103],
    ['s54', '工体东路', 116.45665, 39.93755], ['s55', '巨石大厦', 116.44536, 39.93949], ['s56', '中国石油工体西门', 116.44656, 39.93731],
    ['s57', '中央歌剧院', 116.4432, 39.93529], ['s58', '佳汇中心', 116.4476, 39.93317], ['s59', '三里屯SOHO', 116.45981, 39.93957],
    ['s60', '骏豪中央公园广场', 116.48456, 39.93835], ['s61', '甜水园北里', 116.4902, 39.93451], ['s62', '佳隆国际', 116.47872, 39.94031],
    ['s63', '万科公园五号', 116.48344, 39.93261], ['s64', '东枫国际体育园', 116.47462, 39.93995], ['s65', '银泰中心', 116.46474, 39.91325],
].map(([id, name, lng, lat]) => ({id, name, lng, lat}));

// 分流与运维路线由 BMap.DrivingRoute 预先计算后抽稀;秒数、米数为接口原值,path 为空格分隔的“经度,纬度”。
const parse = (text) => text.split(' ').map((pair) => pair.split(',').map(Number));
// prettier-ignore
const routes = {
    's22>s57': {seconds: 675, distance: 4125, path: parse(
        '116.4567,39.91582 116.45673,39.91435 116.45373,39.91439 116.45041,39.91447 ' +
        '116.45039,39.91502 116.4504,39.91757 116.44339,39.91762 116.44332,39.91768 ' +
        '116.44328,39.91781 116.44331,39.91912 116.44335,39.91917 116.44238,39.91919 ' +
        '116.44192,39.91918 116.44181,39.91965 116.44173,39.92031 116.44167,39.92132 ' +
        '116.4415,39.92511 116.44151,39.92571 116.44143,39.92661 116.44139,39.92791 ' +
        '116.44132,39.92844 116.44118,39.93089 116.44115,39.93218 116.44118,39.93292 ' +
        '116.44102,39.93616 116.44192,39.93614 116.44332,39.93615 116.44352,39.93554 ' +
        '116.44315,39.9355')},
    's52>s28': {seconds: 1147, distance: 3626, path: parse(
        '116.45059,39.93676 116.45029,39.93676 116.45027,39.93289 116.45032,39.93276 ' +
        '116.45269,39.9327 116.45268,39.93001 116.4527,39.92944 116.45274,39.92915 ' +
        '116.45267,39.92906 116.45256,39.92802 116.4523,39.92806 116.45228,39.92788 ' +
        '116.4523,39.92756 116.45249,39.92616 116.45249,39.92348 116.45314,39.92347 ' +
        '116.45316,39.92277 116.45317,39.92049 116.45315,39.91759 116.4504,39.91757 ' +
        '116.45039,39.91502 116.45041,39.91447 116.45034,39.91435 116.4503,39.91387 ' +
        '116.45031,39.91124 116.45042,39.91124 116.45043,39.91302 116.45084,39.91301 ' +
        '116.45084,39.91304 116.4508,39.91304')},
    's05>s21': {seconds: 735, distance: 2752, path: parse(
        '116.47248,39.92985 116.47249,39.9298 116.47257,39.92975 116.47283,39.92976 ' +
        '116.47293,39.93003 116.47297,39.93038 116.47351,39.93039 116.47351,39.93013 ' +
        '116.47362,39.93013 116.47361,39.92889 116.47614,39.92881 116.47614,39.92837 ' +
        '116.47616,39.92812 116.47616,39.92685 116.47612,39.92368 116.47613,39.91929 ' +
        '116.47403,39.91924 116.47281,39.91925 116.47215,39.91922 116.46898,39.91921 ' +
        '116.4682,39.91918 116.46814,39.91717 116.4681,39.91637 116.46803,39.91614 ' +
        '116.46782,39.91619 116.46778,39.91622 116.46768,39.91622 116.46764,39.9162 ' +
        '116.46752,39.91629 116.46737,39.91629 116.46737,39.91611 116.46729,39.91574')},
    'depot>s20': {seconds: 374, distance: 1447, path: parse(
        '116.472,39.92357 116.47209,39.9234 116.47217,39.92337 116.4751,39.92235 ' +
        '116.47612,39.92211 116.47613,39.91922 116.47611,39.91843 116.47614,39.9177 ' +
        '116.47613,39.91545 116.47961,39.91549 116.47962,39.91539')},
    's20>s52': {seconds: 980, distance: 4842, path: parse(
        '116.47962,39.91539 116.47961,39.91549 116.48,39.91549 116.47998,39.91606 ' +
        '116.48001,39.91746 116.4802,39.91811 116.48054,39.91914 116.48059,39.91938 ' +
        '116.47963,39.91938 116.47841,39.91933 116.47621,39.91929 116.47623,39.92223 ' +
        '116.47564,39.92235 116.47495,39.92255 116.47241,39.92342 116.46846,39.92485 ' +
        '116.46843,39.92583 116.46845,39.92903 116.46455,39.92906 116.45968,39.92914 ' +
        '116.45916,39.92906 116.45901,39.92899 116.45876,39.92895 116.4581,39.92868 ' +
        '116.45778,39.92862 116.4573,39.92862 116.457,39.92865 116.45702,39.93268 ' +
        '116.4542,39.93272 116.45269,39.9327 116.45032,39.93276 116.45036,39.93289 ' +
        '116.45034,39.93446 116.45034,39.93669 116.45058,39.93666')},
    's52>s61': {seconds: 813, distance: 4356, path: parse(
        '116.45034,39.93677 116.45037,39.93945 116.45517,39.93941 116.45777,39.93936 ' +
        '116.4604,39.93936 116.46206,39.93933 116.46661,39.93935 116.46861,39.93933 ' +
        '116.47154,39.93932 116.47715,39.93936 116.48487,39.93946 116.48478,39.93612 ' +
        '116.48475,39.93403 116.48487,39.934 116.48583,39.93401 116.48629,39.93404 ' +
        '116.48839,39.93403 116.48837,39.93429 116.49003,39.93432 116.49012,39.93448')},
};

function distanceMeters(a, b) {
  const radians = Math.PI / 180;
  const lat = (b.lat - a.lat) * radians;
  const lng = (b.lng - a.lng) * radians;
  const haversine =
    Math.sin(lat / 2) ** 2 +
    Math.cos(a.lat * radians) * Math.cos(b.lat * radians) * Math.sin(lng / 2) ** 2;
  return 12742000 * Math.asin(Math.min(1, Math.sqrt(haversine)));
}

// 站点坐标为真实检索结果;桩数、占用、排队与故障均为演示模型,确定性生成,便于回放复现。
const START_HOUR = 17;
const STEP_MINUTES = 10;
const FRAME_COUNT = 37;
const zones = [
  {
    id: 'cbd',
    name: '国贸 CBD',
    lng: 116.462,
    lat: 39.915,
    radius: 1300,
    peak: 18.5,
    width: 0.8,
    amp: 1.05,
  },
  {
    id: 'night',
    name: '三里屯 · 工体',
    lng: 116.452,
    lat: 39.935,
    radius: 1100,
    peak: 21.3,
    width: 0.9,
    amp: 1,
  },
  {
    id: 'home',
    name: '团结湖 · 甜水园',
    lng: 116.482,
    lat: 39.932,
    radius: 1200,
    peak: 22.5,
    width: 0.9,
    amp: 1.05,
  },
];
const depot = {name: '运维驻点', lng: 116.4717, lat: 39.9247};
const faults = [
  {station: 's20', frame: 4, piles: 2},
  {station: 's52', frame: 15, piles: 1},
  {station: 's61', frame: 25, piles: 2},
];
const TRIP_FRAMES = 3;
const REPAIR_FRAMES = 1;
const SHIFT_FRAMES = 6;
const pileOptions = [4, 6, 8, 10, 12, 16];

const frameTime = (frame) => {
  const minutes = START_HOUR * 60 + Math.round(frame) * STEP_MINUTES;
  return `${String(Math.floor(minutes / 60)).padStart(2, '0')}:${String(minutes % 60).padStart(2, '0')}`;
};
// 稳定的整数散列,保证每次打开页面看到同一套演示数据。
function hash(text) {
  let value = 2166136261;
  for (const char of text) value = Math.imul(value ^ char.charCodeAt(0), 16777619);
  return (value >>> 0) / 4294967296;
}
const piles = (station) => pileOptions[Math.floor(hash(station.id) * pileOptions.length)];

function demand(station, frame) {
  const hour = START_HOUR + (frame * STEP_MINUTES) / 60;
  let value =
    0.48 +
    0.14 * Math.sin(((hour - 17) / 6) * Math.PI) +
    (hash(`${station.id}:bias`) - 0.5) * 0.3 +
    (hash(`${station.id}:${frame}`) - 0.5) * 0.12;
  for (const zone of zones) {
    const near = Math.exp(-((distanceMeters(station, zone) / zone.radius) ** 2));
    value += zone.amp * near * Math.exp(-(((hour - zone.peak) / zone.width) ** 2));
  }
  return Math.max(0.05, value);
}

// 故障从出现到运维车到达并修复的帧区间;运维车依次前往各故障站。
function maintenance() {
  let from = depot;
  return faults.map((fault) => {
    const station = stations.find((item) => item.id === fault.station);
    const trip = {
      ...fault,
      to: {lng: station.lng, lat: station.lat},
      fromId: from.id || 'depot',
      arrive: fault.frame + TRIP_FRAMES,
      fixed: fault.frame + TRIP_FRAMES + REPAIR_FRAMES,
    };
    from = station;
    return trip;
  });
}

function baseState(frame) {
  const trips = maintenance();
  return stations.map((station) => {
    const total = piles(station);
    const broken = trips
      .filter((trip) => trip.station === station.id && frame >= trip.frame && frame < trip.fixed)
      .reduce((sum, trip) => sum + trip.piles, 0);
    const available = Math.max(1, total - broken);
    const value = demand(station, frame);
    const occupied = Math.min(available, Math.round(value * available));
    const queue = value > 1 ? Math.round((value - 1) * available * 2) : 0;
    return {...station, piles: total, faulty: broken, available, occupied, queue};
  });
}

// 每个片区高峰时刻,为排队最多的站推荐 3 公里内“距离近、空桩多”的站分流。
function planDiversions() {
  return zones
    .map((zone) => {
      const frame = Math.round(((zone.peak - START_HOUR) * 60) / STEP_MINUTES);
      const state = baseState(frame);
      const source = [...state].sort((a, b) => b.queue - a.queue || b.occupied - a.occupied)[0];
      const target = state
        .filter(
          (item) =>
            item !== source &&
            distanceMeters(item, source) <= 3000 &&
            item.available - item.occupied >= 5,
        )
        .map((item) => ({
          item,
          score: (distanceMeters(item, source) / 1000) * 1.5 - (item.available - item.occupied),
        }))
        .sort((a, b) => a.score - b.score)[0]?.item;
      if (!source?.queue || !target) return null;
      const moved = Math.min(Math.ceil(source.queue * 0.6), target.available - target.occupied - 1);
      return {frame, source: source.id, target: target.id, moved, queue: source.queue};
    })
    .filter(Boolean);
}

const levelOf = (item) =>
  item.available - item.occupied <= 0 && item.queue > 0
    ? 'jam'
    : item.occupied / item.available >= 0.8
      ? 'busy'
      : 'idle';

function buildSnapshot(index, events) {
  const state = baseState(index);
  // 分流生效后逐步转移车辆:源站排队下降,目标站占用上升。
  for (const event of events) {
    const passed = index - event.frame;
    if (passed < 1 || passed > SHIFT_FRAMES) continue;
    const shift = Math.round(
      event.moved * Math.min(1, passed / 2) * (1 - ((passed - 1) / SHIFT_FRAMES) * 0.5),
    );
    const source = state.find((item) => item.id === event.source),
      target = state.find((item) => item.id === event.target);
    source.queue = Math.max(0, source.queue - shift);
    target.occupied = Math.min(target.available, target.occupied + shift);
  }
  const list = state.map((item) => ({
    ...item,
    free: item.available - item.occupied,
    occupancy: item.occupied / item.available,
    level: levelOf(item),
  }));
  return {
    time: frameTime(index),
    stations: list,
    totals: {
      queue: list.reduce((sum, item) => sum + item.queue, 0),
      free: list.reduce((sum, item) => sum + item.free, 0),
      faulty: list.reduce((sum, item) => sum + item.faulty, 0),
      jam: list.filter((item) => item.level === 'jam').length,
    },
  };
}

// 整晚 37 帧在模块加载时一次算好,回放只读缓存。
const events = planDiversions();
const frames = Array.from({length: FRAME_COUNT}, (_, index) => buildSnapshot(index, events));
const diversions = () => events;
const snapshot = (frame) => frames[Math.max(0, Math.min(FRAME_COUNT - 1, Math.round(frame)))];
const series = () => frames.map((item) => item.totals.queue);

// 沿路径按长度插值,返回位置。
function alongPath(path, fraction) {
  if (!path?.length) return null;
  const lengths = path
    .slice(1)
    .map((value, i) =>
      distanceMeters({lng: path[i][0], lat: path[i][1]}, {lng: value[0], lat: value[1]}),
    );
  const total = lengths.reduce((sum, value) => sum + value, 0);
  let remaining = total * Math.max(0, Math.min(1, fraction));
  for (let i = 0; i < lengths.length; i++) {
    if ((remaining <= lengths[i] && lengths[i] > 0) || i === lengths.length - 1) {
      const ratio = lengths[i] ? Math.min(1, remaining / lengths[i]) : 0;
      const [a, b] = [path[i], path[i + 1]];
      return {lng: a[0] + (b[0] - a[0]) * ratio, lat: a[1] + (b[1] - a[1]) * ratio};
    }
    remaining -= lengths[i];
  }
  return {lng: path[0][0], lat: path[0][1]};
}

const COLORS = {
  idle: '#34e3b0',
  busy: '#ffc24b',
  jam: '#ff4f6a',
  fault: '#c58bff',
  divert: '#4fc3ff',
};
const SIDE = {idle: '#0f6b58', busy: '#8a5f12', jam: '#8b1d33'};
const LEVEL_TEXT = {idle: '空闲', busy: '繁忙', jam: '满载排队'};
const FRAME_MS = 1500,
  TWEEN_MS = 600,
  TICK_MS = 50,
  TILT = 55,
  HEADING = -20;
const reducedMotion = matchMedia('(prefers-reduced-motion: reduce)');
const collection = (features) => ({type: 'FeatureCollection', features});
const feature = (type, coordinates, properties = {}) => ({
  type: 'Feature',
  geometry: {type, coordinates},
  properties,
});
const P = (lng, lat) => new BMap.Point(lng, lat);
const trips = maintenance();
const queueSeries = series();
const stationOf = (id) => stations.find((item) => item.id === id);
const routeOf = (event) => routes[`${event.source}>${event.target}`];
const tripRoute = (trip) => routes[`${trip.fromId}>${trip.station}`];
const activeDiversion = (i) => events.find((event) => i >= event.frame && i <= event.frame + 6);
const activeTrip = (value) => trips.find((trip) => value >= trip.frame && value < trip.fixed);
const altitudeOf = (item) => 40 + item.occupancy * 200 + Math.min(item.queue, 15) * 22;
// 墨卡托长度约为地面米数 / cos(纬度),LineLayer 的 traceControl 按该单位计算。
const traceUnits = (path) =>
  path
    .slice(1)
    .reduce(
      (sum, value, i) =>
        sum +
        Math.hypot(
          (value[0] - path[i][0]) * 111320 * Math.cos((value[1] * Math.PI) / 180),
          (value[1] - path[i][1]) * 110540,
        ),
      0,
    ) / Math.cos((path[0][1] * Math.PI) / 180);

let map,
  alive = true,
  raf = 0,
  last = performance.now(),
  lastStyle = 0,
  tweenStart = 0;
let frame = reducedMotion.matches ? 26 : 0,
  index = -1,
  playing = !reducedMotion.matches;
let current = snapshot(Math.round(frame));
let van = null,
  opsTrace = 0,
  faultCount = 0;
const layers = {},
  prisms = new Map(),
  labels = [];

function periodOf(time) {
  const minutes = Number(time.slice(0, 2)) * 60 + Number(time.slice(3));
  if (minutes < 19 * 60 + 30) return '下班高峰';
  if (minutes < 20 * 60 + 30) return '晚间平峰';
  if (minutes < 22 * 60 + 30) return '夜间补电高峰';
  return '谷电前夕';
}
function hexagon(item, radius = 42) {
  const dLat = radius / 110540,
    dLng = radius / (111320 * Math.cos((item.lat * Math.PI) / 180));
  return Array.from({length: 6}, (_, i) =>
    P(
      item.lng + Math.cos((i * Math.PI) / 3 + Math.PI / 6) * dLng,
      item.lat + Math.sin((i * Math.PI) / 3 + Math.PI / 6) * dLat,
    ),
  );
}
function addLayer(name, layer) {
  map.addLayer(layer);
  layers[name] = layer;
  return layer;
}
function styleMap() {
  map.setDisplayOptions({
    poi: false,
    poiText: false,
    poiIcon: false,
    skyColors: ['rgba(6, 14, 24, 0)', 'rgba(14, 28, 48, 1)'],
  });
  map.setMapStyle({
    styleJson: [
      {featureType: 'land', elementType: 'geometry', stylers: {color: '#0d1a2aff'}},
      {featureType: 'water', elementType: 'geometry', stylers: {color: '#0b2a40ff'}},
      {featureType: 'green', elementType: 'geometry', stylers: {color: '#11303aff'}},
      {featureType: 'manmade', elementType: 'geometry', stylers: {color: '#13243aff'}},
      {featureType: 'building', elementType: 'geometry', stylers: {color: '#1f3854ff'}},
      {featureType: 'road', elementType: 'geometry.fill', stylers: {color: '#2a4562ff'}},
      {featureType: 'road', elementType: 'geometry.stroke', stylers: {color: '#0d1a2aff'}},
      ...['highway', 'nationalway', 'provincialway', 'cityhighway', 'arterial'].map(
        (featureType) => ({
          featureType,
          elementType: 'geometry.fill',
          stylers: {color: '#3b6288ff'},
        }),
      ),
      {featureType: 'railway', elementType: 'all', stylers: {visibility: 'off'}},
      {featureType: 'all', elementType: 'labels.text.fill', stylers: {color: '#8ea9c4ff'}},
      {featureType: 'all', elementType: 'labels.text.stroke', stylers: {color: '#0d1a2aff'}},
      {featureType: 'poi', elementType: 'all', stylers: {visibility: 'off'}},
    ],
  });
}
// 调度服务片区,用虚线边界标出。
function serviceArea() {
  const [w, e, s, n] = [116.4355, 116.4985, 39.9055, 39.9445];
  return [P(w, s), P(e, s), P(e, n), P(w, n)];
}
function fixView() {
  const narrow = innerWidth <= 720;
  const lngs = stations.map((item) => item.lng);
  const lats = stations.map((item) => item.lat);
  // 66 座站点外包框的中心,约 116.4675, 39.9249。
  const center = P(
    (Math.min(...lngs) + Math.max(...lngs)) / 2,
    (Math.min(...lats) + Math.max(...lats)) / 2,
  );
  // 只借 getViewport 算出随屏幕尺寸变化的基准级别,中心不用它的结果。
  const {zoom} = map.getViewport(serviceArea(), {margins: [20, 20, 20, 20]});
  map.centerAndZoom(center, zoom + (narrow ? 0.2 : 0.3));
  map.setTilt(TILT);
  map.setHeading(HEADING);
}

// 分流路线箭头纹理(16×64 PNG)。
const ARROW =
  'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAABACAYAAAATffeWAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAWNJREFUeNpiMZyqyQAE/0HEM507DBwsrAw87OxgzMXKxsDCxMzw599fhm+/fzF8+fkTjIUuyDNAASMTA4Vg1IBRA0YNGDVg1IBRA4azARb8tgxT1BYxCLKIYCgUYBFmmKi8mMFOwAVFnAWZU6nQyGDOb8Mgx6nAkPcwFCjyF6KIkZWhVWYmgzG3NYMAszBDKkMSdhf8+PcDTOtxGzM0y04HSjIzMAJhmUQPWDMIfPv7DcUFjMjtA24zFoaN+vsYhFghXtj0YTHDt/9fGSIEM8D893/eMARecmL4dOIP9vbB7W83GJJuhABd8h3M9xOIhWv+/f83Q9G9JIYHP+7ij4ULn08zlN5PYfj3/y9c7D8QtjwtYDj9+Qhx0bj/w3aG1qdFYI0gMOd1F8POD+uwRiMLrvjd+mEVgxyHAgMPMx/D8nfTcKYDFnyJZOHbCeBG1mhmGjVg1IBRA0YNGDVg6BgAEGAAcp1mEhywMvYAAAAASUVORK5CYII=';
function initLayers() {
  const area = serviceArea();
  const ring = [...area, area[0]].map((value) => [value.lng, value.lat]);
  addLayer(
    'edge',
    new BMap.LineLayer({
      crs: 'BD09LL',
      style: {
        strokeColor: '#7fd6ff',
        strokeWeight: 1.5,
        strokeOpacity: 0.5,
        strokeStyle: 'dashed',
        dashArray: [10, 6],
      },
    }),
  ).setData(collection([feature('LineString', ring)]));
  addLayer(
    'heat',
    new BMap.Heatmap({
      size: 520,
      unit: 'm',
      weightField: 'weight',
      max: 16,
      min: 0,
      opacity: 0.5,
      maxOpacity: 0.62,
      gradient: {
        0: 'rgba(10,20,40,0)',
        0.3: '#1c3d7a',
        0.55: '#6a3ab0',
        0.78: '#e0457b',
        1: '#ffb15c',
      },
    }),
  );
  // 运维路线:traceControl 把已行驶部分染成紫色,未走部分保持暗色。
  addLayer(
    'opsRoute',
    new BMap.LineLayer({
      crs: 'BD09LL',
      style: {
        strokeColor: '#5a4d78',
        strokeWeight: 4,
        strokeOpacity: 0.8,
        strokeLineCap: 'round',
        strokeLineJoin: 'round',
        traceColor: [197, 139, 255],
        traceStart: true,
        traceControl: (indexes) => indexes.map(() => opsTrace),
      },
    }),
  );
  addLayer(
    'divertGlow',
    new BMap.LineLayer({
      crs: 'BD09LL',
      style: {
        strokeColor: COLORS.divert,
        strokeWeight: 18,
        strokeOpacity: 0.14,
        strokeLineCap: 'round',
      },
    }),
  );
  // 分流路线:sequence 间隔箭头纹理表示行驶方向。
  addLayer(
    'divert',
    new BMap.LineLayer({
      crs: 'BD09LL',
      style: {
        strokeColor: COLORS.divert,
        strokeWeight: 9,
        strokeOpacity: 1,
        strokeLineCap: 'round',
        strokeLineJoin: 'round',
        sequence: true,
        marginLength: 26,
        strokeTextureUrl: ARROW,
        strokeTextureWidth: 16,
        strokeTextureHeight: 64,
        arrowColor: 'rgba(255,255,255,1)',
      },
    }),
  );
  addLayer(
    'cars',
    new BMap.PointShapeLayer({
      crs: 'BD09LL',
      isFlat: false,
      style: {
        shapeType: 0,
        size: 9,
        color: '#e8f8ff',
        strokeColor: COLORS.divert,
        strokeWeight: 3,
      },
    }),
  );
  addLayer(
    'fault',
    new BMap.PointShapeLayer({
      crs: 'BD09LL',
      isFlat: false,
      style: {
        shapeType: 0,
        size: 50,
        color: COLORS.fault,
        opacity: 0.15,
        strokeColor: COLORS.fault,
        strokeWeight: 3,
      },
    }),
  );
  addLayer(
    'bases',
    new BMap.PointShapeLayer({
      crs: 'BD09LL',
      isFlat: true,
      enablePicked: true,
      style: {
        shapeType: 0,
        size: ['get', 'size'],
        color: ['get', 'color'],
        opacity: 0.22,
        strokeColor: ['get', 'color'],
        strokeWeight: 1.5,
      },
    }),
  ).addEventListener('click', (event) => {
    const id = event.value?.dataItem?.properties?.id;
    if (id) showStation(id);
  });
  stations.forEach((station) => {
    const item = current.stations.find((value) => value.id === station.id);
    const altitude = altitudeOf(item);
    const prism = new BMap.Prism(hexagon(station), altitude, {
      topFillColor: COLORS[item.level],
      topFillOpacity: 0.95,
      sideFillColor: SIDE[item.level],
      sideFillOpacity: 0.78,
      enableClicking: false,
    });
    map.addOverlay(prism);
    prisms.set(station.id, {
      prism,
      level: item.level,
      from: altitude,
      to: altitude,
      shown: altitude,
    });
  });
  const svg =
    '<svg xmlns="http://www.w3.org/2000/svg" width="34" height="34"><circle cx="17" cy="17" r="15" fill="#2a1747" stroke="#c58bff" stroke-width="2"/><path d="M10 20h14v-4l-3-4h-8l-3 4zM12 20v2m10-2v2" fill="none" stroke="#f3e8ff" stroke-width="1.8" stroke-linejoin="round"/></svg>';
  van = new BMap.Marker(P(depot.lng, depot.lat), {
    icon: new BMap.Icon(
      `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`,
      new BMap.Size(28, 28),
    ),
  });
  map.addOverlay(van);
  van.hide();
}
function showStation(id) {
  const item = current.stations.find((value) => value.id === id);
  if (!item) return;
  const html = `<div class="info"><strong>${esc(item.name)}</strong><span class="${item.level}">${LEVEL_TEXT[item.level]}</span><p>占用 ${item.occupied}/${item.available} · 排队 ${item.queue} · 故障 ${item.faulty}</p><small>${current.time}</small></div>`;
  map.openInfoWindow(new BMap.InfoWindow(html, {width: 230}), P(item.lng, item.lat));
}
function addLabel(html, position, offset) {
  const label = new BMap.Label(html, {position, offset});
  label.setStyle({background: 'transparent', border: '0', padding: '0'});
  map.addOverlay(label);
  labels.push(label);
}
function applyFrame(i) {
  current = snapshot(i);
  const list = current.stations;
  layers.heat.setData(
    collection(
      list.map((item) =>
        feature('Point', [item.lng, item.lat], {weight: item.occupied + item.queue * 2}),
      ),
    ),
  );
  layers.bases.setData(
    collection(
      list.map((item) =>
        feature('Point', [item.lng, item.lat], {
          id: item.id,
          color: COLORS[item.level],
          size: item.level === 'jam' ? 30 : item.level === 'busy' ? 24 : 18,
        }),
      ),
    ),
  );
  const faulty = list.filter((item) => item.faulty > 0);
  faultCount = faulty.length;
  layers.fault.setData(collection(faulty.map((item) => feature('Point', [item.lng, item.lat]))));
  list.forEach((item) => {
    const entry = prisms.get(item.id);
    entry.from = entry.shown;
    entry.to = altitudeOf(item);
    if (entry.level !== item.level) {
      entry.level = item.level;
      entry.prism.setTopFillColor(COLORS[item.level]);
      entry.prism.setSideFillColor(SIDE[item.level]);
    }
  });
  tweenStart = performance.now();
  const divert = activeDiversion(i);
  const divertData = collection(divert ? [feature('LineString', routeOf(divert).path)] : []);
  layers.divert.setData(divertData);
  layers.divertGlow.setData(divertData);
  if (!divert) layers.cars.setData(collection([]));
  const trip = activeTrip(i);
  layers.opsRoute.setData(collection(trip ? [feature('LineString', tripRoute(trip).path)] : []));
  renderLabels(divert, trip);
  renderPanel(i, divert, trip);
}
function renderLabels(divert, trip) {
  labels.forEach((label) => map.removeOverlay(label));
  labels.length = 0;
  const skip = new Set(divert ? [divert.source, divert.target] : []);
  current.stations
    .filter((item) => item.queue > 0 && !skip.has(item.id))
    .sort((a, b) => b.queue - a.queue)
    .slice(0, divert ? 0 : 3)
    .forEach((item) => {
      addLabel(
        `<span class="tag jam"><b>${item.queue}</b> 辆排队<i>${esc(item.name)}</i></span>`,
        P(item.lng, item.lat),
        new BMap.Size(14, -34),
      );
    });
  if (divert) {
    // 源站排队随分流逐帧下降,标签取当前帧数值。
    const source = current.stations.find((item) => item.id === divert.source),
      target = stationOf(divert.target);
    if (source.queue)
      addLabel(
        `<span class="tag jam"><b>${source.queue}</b> 辆排队<i>${esc(source.name)}</i></span>`,
        P(source.lng, source.lat),
        new BMap.Size(14, -34),
      );
    addLabel(
      `<span class="tag divert">接收分流 · ${esc(target.name)}</span>`,
      P(target.lng, target.lat),
      new BMap.Size(14, -30),
    );
  }
  if (trip)
    addLabel(
      `<span class="tag fault">故障 ${trip.piles} 桩 · ${esc(stationOf(trip.station).name)}</span>`,
      P(trip.to.lng, trip.to.lat),
      new BMap.Size(14, 8),
    );
}
// 整晚排队曲线只画一次,回放时只移动游标。
function drawSpark() {
  const max = Math.max(...queueSeries, 1);
  const points = queueSeries
    .map(
      (value, n) =>
        `${((n / (FRAME_COUNT - 1)) * 240).toFixed(1)},${(27 - (value / max) * 24).toFixed(1)}`,
    )
    .join(' ');
  $('spark').innerHTML =
    `<polygon points="0,28 ${points} 240,28" fill="#ff4f6a33"/><polyline points="${points}" fill="none" stroke="#ff7a8c" stroke-width="1.2" vector-effect="non-scaling-stroke"/>` +
    '<line x1="0" x2="0" y1="0" y2="28" stroke="#e8f8ff" stroke-width="1" vector-effect="non-scaling-stroke"/>';
  return $('spark').querySelector('line');
}
const cursor = drawSpark();
// 面板只保留时刻、三项总量和当前一条调度事件。
function renderPanel(i, divert, trip) {
  const {totals} = current;
  $('clock').textContent = current.time;
  $('period').textContent = periodOf(current.time);
  $('kpi-queue').textContent = totals.queue;
  $('kpi-free').textContent = totals.free;
  $('kpi-fault').textContent = totals.faulty;
  const event = $('event');
  if (divert) {
    event.className = 'event divert';
    event.innerHTML = `<b>分流</b>${esc(stationOf(divert.source).name)} → ${esc(stationOf(divert.target).name)} · ${divert.moved} 辆`;
  } else if (trip) {
    event.className = 'event fault';
    event.innerHTML = `<b>运维</b>${esc(stationOf(trip.station).name)} ${trip.piles} 桩故障 · ${i >= trip.arrive ? '维修中' : '运维车前往'}`;
  } else {
    event.className = 'event';
    event.textContent = totals.queue ? `${totals.jam} 个站满载排队` : '运行平稳';
  }
  const x = ((i / (FRAME_COUNT - 1)) * 240).toFixed(1);
  cursor.setAttribute('x1', x);
  cursor.setAttribute('x2', x);
  $('scrub').value = i;
}
function animate(now) {
  if (!alive) return;
  raf = requestAnimationFrame(animate);
  const dt = Math.min(100, now - last);
  last = now;
  if (document.hidden) return;
  if (playing) {
    frame += dt / FRAME_MS;
    if (frame >= FRAME_COUNT + 1.2) frame = 0;
  }
  const next = Math.min(FRAME_COUNT - 1, Math.floor(frame));
  if (next !== index) {
    index = next;
    applyFrame(index);
  }
  if (now - lastStyle < TICK_MS) return;
  lastStyle = now;
  // 立柱高度在帧间缓动;每次 setAltitude 都会重建棱柱几何,变化不足 2 米时跳过。
  const ease = Math.min(1, (now - tweenStart) / TWEEN_MS),
    smooth = 1 - (1 - ease) ** 3;
  prisms.forEach((entry) => {
    if (entry.shown === entry.to) return;
    const value = ease === 1 ? entry.to : entry.from + (entry.to - entry.from) * smooth;
    if (ease < 1 && Math.abs(value - entry.shown) < 2) return;
    entry.shown = value;
    entry.prism.setAltitude(value);
  });
  // setStyleOptions 会重新解析图层数据,没有故障站时不更新。
  if (faultCount)
    layers.fault.setStyleOptions({
      opacity: 0.1 + 0.25 * (Math.sin(now / 160) * 0.5 + 0.5),
      size: 40 + 10 * Math.sin(now / 320),
    });
  const divert = activeDiversion(index);
  if (divert) {
    const path = routeOf(divert).path;
    layers.cars.setData(
      collection(
        [0, 0.2, 0.4, 0.6, 0.8].map((offset) => {
          const at = alongPath(path, (now / 7000 + offset) % 1);
          return feature('Point', [at.lng, at.lat]);
        }),
      ),
    );
  }
  const trip = activeTrip(frame);
  if (trip) {
    const path = tripRoute(trip).path;
    const progress = Math.max(0, Math.min(1, (frame - trip.frame) / (trip.arrive - trip.frame)));
    const at = alongPath(path, progress);
    opsTrace = traceUnits(path) * progress;
    layers.opsRoute.doOnceDraw();
    van.setPosition(P(at.lng, at.lat));
    van.show();
  } else van?.hide();
}
$('scrub').oninput = (event) => {
  frame = Number(event.target.value);
};
let resizeTimer;
const onResize = () => {
  clearTimeout(resizeTimer);
  resizeTimer = setTimeout(() => {
    if (map) fixView();
  }, 200);
};
window.addEventListener('resize', onResize);
// 页面关闭时停止回放;map.destroy 一并释放覆盖物与图层。
window.addEventListener(
  'pagehide',
  () => {
    alive = false;
    cancelAnimationFrame(raf);
    clearTimeout(resizeTimer);
    map?.destroy();
  },
  {once: true},
);

// 底图样式与瓦片加载完成后再开始回放,避免前几帧只有图层没有地图。
function start() {
  clearTimeout(startTimer);
  map.removeEventListener('tilesloaded', start);
  if (!alive || raf) return;
  $('map-sub').textContent = '国贸—三里屯';
  last = performance.now();
  raf = requestAnimationFrame(animate);
}
map = new BMap.Map('map', {enableAdaptiveMinZoom: false});
map.enableScrollWheelZoom(true);
map.addControl(new BMap.ScaleControl());
map.addControl(new BMap.ZoomControl());
fixView();
styleMap();
initLayers();
$('map-sub').textContent = '正在加载底图…';
const startTimer = setTimeout(start, 15000);
map.addEventListener('tilesloaded', start);
预览