Files
gofly-platform-services/zlt-business/device-center/doc/景区地图仪表盘功能实现文档.md
T

32 KiB
Raw Blame History

景区地图仪表盘功能实现文档

一、项目概述

1.1 功能简介

景区地图仪表盘是一个基于地图的设备监控与管理系统,用于可视化展示当前租户及其子租户下所有景区的地理位置、设备分布和实时状态。通过三个独立页面实现地图 → 景区设备 → 设备详情的渐进式展示,提供清爽简洁的用户体验。支持2D/3D地图自由切换。

1.2 技术栈

  • 前端框架: React 17 + TypeScript + UmiJS 3.5
  • UI组件: Ant Design 4.20
  • 路由: UmiJS内置路由
  • 地图组件:
    • 2D地图: 高德地图 1.4.15
    • 3D地图: Mapbox GL JS 2.15+
  • 实时通信: WebSocket
  • 状态管理: React Hooks + UmiJS Model
  • 样式方案: Less/CSS-in-JS

1.3 核心功能

  1. 景区地图页面:全屏地图展示所有景区位置
  2. 景区设备页面:展示指定景区下的所有设备列表
  3. 设备详情页面:展示设备实时数据和控制面板
  4. 2D/3D地图无缝切换(高德2D ⇄ Mapbox 3D)
  5. WebSocket实时设备数据订阅
  6. 视频流播放与无人机远程控制

1.4 页面流程

┌─────────────────────────────────────────┐
│   景区地图页面(全屏地图)                  │
│   /device/mapDashboard                   │
│   - 显示所有景区标记                       │
│   - 2D/3D地图切换                         │
│   - 点击景区 → 跳转景区设备页面             │
└─────────────────────────────────────────┘
                    ↓ 点击景区
┌─────────────────────────────────────────┐
│   景区设备页面(设备列表)                  │
│   /device/tourismDevices/:tourismId      │
│   - 面包屑导航:地图 > 景区名称             │
│   - 设备卡片列表/表格                      │
│   - 点击设备 → 跳转设备详情页面             │
└─────────────────────────────────────────┘
                    ↓ 点击设备
┌─────────────────────────────────────────┐
│   设备详情页面(设备监控与控制)             │
│   /device/deviceDetail/:deviceSn         │
│   - 面包屑导航:地图 > 景区名称 > 设备名称   │
│   - 实时数据展示                          │
│   - 视频播放器                            │
│   - 控制面板                              │
└─────────────────────────────────────────┘

二、需求分析

2.1 业务需求

2.1.1 景区地图页面

  • 需求: 全屏地图展示当前租户及其子租户的所有景区
  • 数据来源: 景区表(tourism),包含景区名称、经纬度、租户ID等
  • 展示方式:
    • 全屏地图(无侧边栏)
    • 景区标记显示景区位置
    • 支持2D/3D地图切换
    • 顶部工具栏(刷新、全屏、地图切换)
  • 交互:
    • 点击景区标记 → 跳转到景区设备页面

2.1.2 景区设备页面

  • 需求: 展示指定景区下的所有设备
  • 数据来源: 设备表(device),根据景区ID筛选
  • 展示方式:
    • 面包屑导航(返回地图)
    • 设备卡片网格布局
    • 显示设备基本信息(名称、SN、状态、电量等)
  • 交互:
    • 点击设备卡片 → 跳转到设备详情页面

2.1.3 设备详情页面

  • 需求: 展示设备实时数据和控制面板
  • 数据来源: WebSocket实时数据推送
  • 展示方式:
    • 面包屑导航(返回景区/地图)
    • 设备基本信息卡片
    • 实时数据仪表盘
    • 视频播放器
    • 控制面板(无人机控制)
  • 交互:
    • 实时数据更新
    • 视频播放/停止
    • 发送控制指令

2.2 技术需求

2.2.1 前端技术需求

  1. 路由管理:

    • /device/mapDashboard - 景区地图页面
    • /device/tourismDevices/:tourismId - 景区设备页面
    • /device/deviceDetail/:deviceSn - 设备详情页面
  2. 地图加载:

    • 2D模式: 高德地图(国内稳定)
    • 3D模式: Mapbox GL JS(视觉效果好)
    • 支持2D/3D一键切换
  3. WebSocket通信:

    • Token获取:GET /api-device/token/query?expires=7200
    • WebSocket连接:ws://119.45.169.13:8848/messaging/{token}
    • 消息订阅机制:设备属性上报、设备事件、上线/离线状态
  4. 状态管理:

    • 使用UmiJS Model管理全局状态
    • 景区列表缓存
    • 设备数据缓存
    • WebSocket连接状态
  5. UI/UX:

    • 全屏沉浸式体验
    • 流畅的页面切换动画
    • 响应式布局
    • 基于现有主题风格

2.2.2 后端接口需求

  1. 景区接口:

    • 获取景区列表(包含租户过滤、子租户递归查询)
    • 接口:GET /api-order/tourism
    • 参数:tenantId, includeChildren
  2. 设备接口:

    • 根据景区ID获取设备列表(需要新开发)
    • 接口:GET /api-device/device/byTourism/:tourismId
    • 返回:设备列表(包含设备名称、SN、类型、经纬度等)
  3. 设备详情接口:

    • 根据设备SN获取设备详情
    • 接口:GET /api-device/device/:deviceSn
  4. WebSocket Token接口:

    • 已存在:GET /api-device/token/query?expires=7200
  5. 视频流接口:

    • 获取设备视频流地址
    • 接口:GET /api-device/stream/urls/:deviceSn

三、实现方案

3.1 项目结构

zlt-web/react-web-next/src/pages/device/mapDashboard/
  ├── index.tsx                    # 页面1:景区地图
  ├── index.less
  ├── TourismDevices.tsx           # 页面2:景区设备列表
  ├── TourismDevices.less
  ├── DeviceDetail.tsx             # 页面3:设备详情
  ├── DeviceDetail.less
  ├── components/                  # 所有组件
  │   ├── MapContainer/
  │   ├── DeviceCard/
  │   ├── VideoPlayer/
  │   └── DroneControl/
  └── models/                      # 局部模型
      └── websocketModel.ts

3.2 路由配置

// config/routes.ts
export default [
  {
    path: '/device',
    routes: [
      {
        path: '/device/mapDashboard',
        name: '景区地图',
        component: './device/mapDashboard',
      },
      {
        path: '/device/tourismDevices/:tourismId',
        name: '景区设备',
        component: './device/tourismDevices',
        hideInMenu: true,
      },
      {
        path: '/device/deviceDetail/:deviceSn',
        name: '设备详情',
        component: './device/deviceDetail',
        hideInMenu: true,
      },
    ],
  },
];

3.3 依赖安装

# 安装Mapbox GL JS
npm install mapbox-gl
npm install @types/mapbox-gl --save-dev

# 安装高德地图(通过CDN加载,无需npm安装)

3.4 前端实现

3.4.1 页面1:景区地图页面 (mapDashboard/index.tsx)

import React, { useState, useEffect } from 'react';
import { Button, Space, Badge, message, Radio } from 'antd';
import {
  ReloadOutlined,
  FullscreenOutlined,
  FullscreenExitOutlined,
  GlobalOutlined,
} from '@ant-design/icons';
import { history } from 'umi';
import MapContainer from './components/MapContainer';
import { ordersApi } from '@/services/orders';
import styles from './index.less';

type MapMode = '2d' | '3d';

const MapDashboard: React.FC = () => {
  const [tourismList, setTourismList] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [mapMode, setMapMode] = useState<MapMode>('2d');
  const [isFullscreen, setIsFullscreen] = useState(false);

  // 获取景区列表
  const fetchTourismList = async () => {
    setLoading(true);
    try {
      const response = await ordersApi.tourism({ current: 1, pageSize: 1000 });
      setTourismList(response.data || []);
    } catch (error) {
      message.error('获取景区列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 景区点击事件 - 跳转到景区设备页面
  const handleTourismClick = (tourism: any) => {
    history.push(`/device/tourismDevices/${tourism.id}`, {
      tourismName: tourism.tourismName,
      tourism: tourism,
    });
  };

  // 地图模式切换
  const handleMapModeChange = (mode: MapMode) => {
    setMapMode(mode);
    message.success(`已切换到${mode === '2d' ? '二维' : '三维'}地图`);
  };

  // 全屏切换
  const toggleFullscreen = () => {
    if (!document.fullscreenElement) {
      document.documentElement.requestFullscreen();
      setIsFullscreen(true);
    } else {
      document.exitFullscreen();
      setIsFullscreen(false);
    }
  };

  useEffect(() => {
    fetchTourismList();
  }, []);

  return (
    <div className={styles.mapDashboard}>
      {/* 顶部工具栏 */}
      <div className={styles.toolbar}>
        <div className={styles.left}>
          <span className={styles.title}>景区地图仪表盘</span>
          <Badge
            status="success"
            text={`共${tourismList.length}个景区`}
            style={{ marginLeft: 16 }}
          />
        </div>

        <Space size="middle">
          {/* 地图模式切换 */}
          <Radio.Group
            value={mapMode}
            onChange={(e) => handleMapModeChange(e.target.value)}
            buttonStyle="solid"
          >
            <Radio.Button value="2d">
              <GlobalOutlined /> 2D地图
            </Radio.Button>
            <Radio.Button value="3d">
              <GlobalOutlined /> 3D地图
            </Radio.Button>
          </Radio.Group>

          <Button
            icon={<ReloadOutlined />}
            onClick={fetchTourismList}
            loading={loading}
          >
            刷新
          </Button>

          <Button
            icon={isFullscreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
            onClick={toggleFullscreen}
          >
            {isFullscreen ? '退出全屏' : '全屏'}
          </Button>
        </Space>
      </div>

      {/* 全屏地图 */}
      <div className={styles.mapWrapper}>
        <MapContainer
          mode={mapMode}
          tourismList={tourismList}
          onTourismClick={handleTourismClick}
        />
      </div>
    </div>
  );
};

export default MapDashboard;

样式文件 (mapDashboard/index.less):

.mapDashboard {
  position: relative;
  width: 100%;
  height: 100vh;
  overflow: hidden;
  background: #000;

  .toolbar {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 64px;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 24px;
    z-index: 1000;

    .left {
      display: flex;
      align-items: center;

      .title {
        font-size: 18px;
        font-weight: 600;
        color: #000;
      }
    }
  }

  .mapWrapper {
    position: absolute;
    top: 64px;
    left: 0;
    right: 0;
    bottom: 0;
  }
}

3.4.2 页面2:景区设备页面 (tourismDevices/index.tsx)

import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Row, Col, Badge, Tag, Spin, Empty, message } from 'antd';
import { history, useParams, useLocation } from 'umi';
import {
  BatteryChargingOutlined,
  ThunderboltOutlined,
  EnvironmentOutlined
} from '@ant-design/icons';
import { deviceApi } from '@/services/device';
import styles from './index.less';

const TourismDevices: React.FC = () => {
  const { tourismId } = useParams<{ tourismId: string }>();
  const location = useLocation<{ tourismName?: string; tourism?: any }>();
  const [deviceList, setDeviceList] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);

  const tourismName = location.state?.tourismName || '景区';

  // 获取设备列表
  const fetchDevices = async () => {
    setLoading(true);
    try {
      const response = await deviceApi.deviceList({
        page: 1,
        limit: 1000,
        tourismId: Number(tourismId),
      });
      setDeviceList(response.data || []);
    } catch (error) {
      message.error('获取设备列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 设备点击事件 - 跳转到设备详情页面
  const handleDeviceClick = (device: any) => {
    history.push(`/device/deviceDetail/${device.deviceSn}`, {
      device: device,
      tourismName: tourismName,
      tourismId: tourismId,
    });
  };

  useEffect(() => {
    fetchDevices();
  }, [tourismId]);

  return (
    <PageContainer
      title={`${tourismName} - 设备列表`}
      breadcrumb={{
        routes: [
          { path: '/device/mapDashboard', breadcrumbName: '景区地图' },
          { path: '', breadcrumbName: tourismName },
        ],
      }}
      onBack={() => history.goBack()}
    >
      <Spin spinning={loading}>
        {deviceList.length === 0 ? (
          <Card>
            <Empty description="该景区暂无设备" />
          </Card>
        ) : (
          <Row gutter={[16, 16]}>
            {deviceList.map((device) => (
              <Col xs={24} sm={12} md={8} lg={6} xl={4} key={device.deviceSn}>
                <Card
                  hoverable
                  className={styles.deviceCard}
                  onClick={() => handleDeviceClick(device)}
                  cover={
                    <div className={styles.deviceCover}>
                      <EnvironmentOutlined style={{ fontSize: 48, color: '#1890ff' }} />
                    </div>
                  }
                >
                  <Card.Meta
                    title={
                      <div className={styles.deviceTitle}>
                        <span>{device.deviceName || device.deviceSn}</span>
                        <Badge
                          status={device.boundStatus === 1 ? 'success' : 'default'}
                        />
                      </div>
                    }
                    description={
                      <div className={styles.deviceInfo}>
                        <div className={styles.infoItem}>
                          <ThunderboltOutlined />
                          <span>SN: {device.deviceSn}</span>
                        </div>
                        <div className={styles.infoItem}>
                          <BatteryChargingOutlined />
                          <span>
                            {device.boundStatus === 1 ? (
                              <Tag color="success">已绑定</Tag>
                            ) : (
                              <Tag color="default">未绑定</Tag>
                            )}
                          </span>
                        </div>
                      </div>
                    }
                  />
                </Card>
              </Col>
            ))}
          </Row>
        )}
      </Spin>
    </PageContainer>
  );
};

export default TourismDevices;

样式文件 (tourismDevices/index.less):

.deviceCard {
  .deviceCover {
    height: 120px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  }

  .deviceTitle {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .deviceInfo {
    .infoItem {
      display: flex;
      align-items: center;
      margin-bottom: 8px;

      .anticon {
        margin-right: 8px;
        color: #1890ff;
      }
    }
  }

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    transform: translateY(-4px);
    transition: all 0.3s ease;
  }
}

3.4.3 页面3:设备详情页面 (deviceDetail/index.tsx)

import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Row, Col, Descriptions, Tag, Progress, Button, Space, Statistic } from 'antd';
import { history, useParams, useLocation } from 'umi';
import {
  VideoCameraOutlined,
  ControlOutlined,
  ThunderboltOutlined,
  EnvironmentOutlined,
} from '@ant-design/icons';
import { useModel } from 'umi';
import styles from './index.less';

const DeviceDetail: React.FC = () => {
  const { deviceSn } = useParams<{ deviceSn: string }>();
  const location = useLocation<{ device?: any; tourismName?: string; tourismId?: string }>();
  const [device, setDevice] = useState<any>(location.state?.device || {});

  // 使用WebSocket模型
  const { wsConnected, subscribeDevice, deviceData } = useModel('websocketModel');

  const tourismName = location.state?.tourismName || '景区';
  const tourismId = location.state?.tourismId;

  // 订阅设备数据
  useEffect(() => {
    if (deviceSn) {
      subscribeDevice(deviceSn);
    }
  }, [deviceSn]);

  // 更新设备数据
  useEffect(() => {
    if (deviceData[deviceSn]) {
      setDevice((prev: any) => ({
        ...prev,
        metrics: deviceData[deviceSn],
      }));
    }
  }, [deviceData, deviceSn]);

  return (
    <PageContainer
      title={`${device.deviceName || deviceSn}`}
      subTitle={
        <Space>
          <Tag color={wsConnected ? 'success' : 'error'}>
            {wsConnected ? '实时连接' : '连接断开'}
          </Tag>
        </Space>
      }
      breadcrumb={{
        routes: [
          { path: '/device/mapDashboard', breadcrumbName: '景区地图' },
          {
            path: `/device/tourismDevices/${tourismId}`,
            breadcrumbName: tourismName
          },
          { path: '', breadcrumbName: device.deviceName || deviceSn },
        ],
      }}
      onBack={() => history.goBack()}
    >
      <Row gutter={[16, 16]}>
        {/* 设备基本信息 */}
        <Col span={24}>
          <Card title="设备信息">
            <Descriptions column={3}>
              <Descriptions.Item label="设备名称">
                {device.deviceName}
              </Descriptions.Item>
              <Descriptions.Item label="设备编号">
                {device.deviceSn}
              </Descriptions.Item>
              <Descriptions.Item label="设备类型">
                {device.deviceType || '无人机'}
              </Descriptions.Item>
              <Descriptions.Item label="绑定状态">
                <Tag color={device.boundStatus === 1 ? 'success' : 'default'}>
                  {device.boundStatus === 1 ? '已绑定' : '未绑定'}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="创建时间">
                {device.createTime}
              </Descriptions.Item>
            </Descriptions>
          </Card>
        </Col>

        {/* 实时数据 */}
        <Col span={24}>
          <Card title="实时数据">
            <Row gutter={16}>
              <Col span={6}>
                <Card>
                  <Statistic
                    title="电量"
                    value={device.metrics?.batteryCapacity || 0}
                    suffix="%"
                    valueStyle={{ color: '#3f8600' }}
                    prefix={<ThunderboltOutlined />}
                  />
                  <Progress
                    percent={device.metrics?.batteryCapacity || 0}
                    strokeColor={{
                      '0%': '#108ee9',
                      '100%': '#87d068',
                    }}
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card>
                  <Statistic
                    title="温度"
                    value={device.metrics?.temperature || 0}
                    suffix="°C"
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card>
                  <Statistic
                    title="湿度"
                    value={device.metrics?.humidity || 0}
                    suffix="%"
                  />
                </Card>
              </Col>
              <Col span={6}>
                <Card>
                  <Statistic
                    title="网络质量"
                    value={device.metrics?.networkQuality || 0}
                    suffix="%"
                  />
                </Card>
              </Col>
            </Row>
          </Card>
        </Col>

        {/* 视频播放 */}
        <Col span={12}>
          <Card
            title="视频监控"
            extra={<Button type="primary" icon={<VideoCameraOutlined />}>播放</Button>}
          >
            <div className={styles.videoPlaceholder}>
              <VideoCameraOutlined style={{ fontSize: 64, color: '#ccc' }} />
              <p>视频播放器</p>
            </div>
          </Card>
        </Col>

        {/* 设备控制 */}
        <Col span={12}>
          <Card
            title="设备控制"
            extra={<Button icon={<ControlOutlined />}>控制面板</Button>}
          >
            <div className={styles.controlPlaceholder}>
              <Space direction="vertical" size="large" style={{ width: '100%' }}>
                <Button block size="large">起飞</Button>
                <Button block size="large">返航</Button>
                <Button block size="large" danger>紧急停止</Button>
              </Space>
            </div>
          </Card>
        </Col>
      </Row>
    </PageContainer>
  );
};

export default DeviceDetail;

样式文件 (deviceDetail/index.less):

.videoPlaceholder {
  height: 400px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  border-radius: 4px;

  p {
    margin-top: 16px;
    color: #999;
  }
}

.controlPlaceholder {
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 24px;
}

3.4.4 全局WebSocket模型 (models/websocketModel.ts)

import { useState, useEffect, useRef } from 'react';
import { message } from 'antd';
import { request } from 'umi';

interface TokenResponse {
  data: {
    result: string;
    expires: number;
  };
  resp_code: number;
}

export default () => {
  const [wsConnected, setWsConnected] = useState(false);
  const [deviceData, setDeviceData] = useState<Record<string, any>>({});
  const wsRef = useRef<WebSocket | null>(null);
  const tokenCacheRef = useRef({ value: '', expire: 0 });
  const subscribedDevices = useRef<Set<string>>(new Set());

  // 获取Token
  const getToken = async (expires: number = 7200) => {
    const now = Date.now();
    if (tokenCacheRef.current.value && tokenCacheRef.current.expire > now) {
      return tokenCacheRef.current.value;
    }

    const response = await request<TokenResponse>('/api-device/token/query', {
      method: 'GET',
      params: { expires },
    });

    if (response.resp_code !== 0) {
      throw new Error('获取Token失败');
    }

    const { result: token, expires: expiresFromServer } = response.data;
    tokenCacheRef.current = {
      value: token,
      expire: now + (expiresFromServer || expires) * 1000,
    };

    return token;
  };

  // 初始化WebSocket
  const initWebSocket = async () => {
    try {
      const token = await getToken();
      const wsUrl = `ws://119.45.169.13:8848/messaging/${token}`;

      wsRef.current = new WebSocket(wsUrl);

      wsRef.current.onopen = () => {
        console.log('WebSocket连接已建立');
        setWsConnected(true);
      };

      wsRef.current.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data);
          handleWebSocketMessage(data);
        } catch (error) {
          console.error('解析WebSocket消息失败:', error);
        }
      };

      wsRef.current.onclose = () => {
        console.log('WebSocket连接已关闭');
        setWsConnected(false);
        setTimeout(initWebSocket, 5000);
      };

      wsRef.current.onerror = (error) => {
        console.error('WebSocket连接错误:', error);
        setWsConnected(false);
      };
    } catch (error) {
      console.error('初始化WebSocket失败:', error);
      message.error('实时连接失败');
    }
  };

  // 处理WebSocket消息
  const handleWebSocketMessage = (data: any) => {
    console.log('收到WebSocket消息:', data);

    // 解析设备SN和数据
    if (data.type === 'result' && data.payload?.data) {
      const match = data.topic?.match(/\/device\/[^/]+\/([^/]+)\//);
      if (match) {
        const deviceSn = match[1];
        setDeviceData((prev) => ({
          ...prev,
          [deviceSn]: data.payload.data,
        }));
      }
    }
  };

  // 订阅设备消息
  const subscribeDevice = (deviceSn: string) => {
    if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) {
      message.warning('WebSocket未连接');
      return;
    }

    if (subscribedDevices.current.has(deviceSn)) {
      return; // 已订阅
    }

    const subscribeMessage = {
      type: 'sub',
      topic: `/device/*/*/message/property/report`,
      parameter: {},
      id: `sub_${deviceSn}_${Date.now()}`,
    };

    wsRef.current.send(JSON.stringify(subscribeMessage));
    subscribedDevices.current.add(deviceSn);
  };

  // 初始化
  useEffect(() => {
    initWebSocket();
    return () => {
      if (wsRef.current) {
        wsRef.current.close();
      }
    };
  }, []);

  return {
    wsConnected,
    deviceData,
    subscribeDevice,
  };
};

3.5 地图组件(与之前相同)

地图组件 MapContainer/AmapContainer.tsx 和 MapContainer/MapboxContainer.tsx 保持不变,只需修改点击事件:

// AmapContainer.tsx 中的标记点击事件
marker.on('click', () => onTourismClick(tourism));

// MapboxContainer.tsx 中的标记点击事件
el.addEventListener('click', () => onTourismClick(tourism));

3.6 后端实现(与之前相同)

后端接口实现保持不变:

  • GET /api-device/device/byTourism/:tourismId - 根据景区ID获取设备列表
  • GET /api-device/device/:deviceSn - 获取设备详情

四、技术细节

4.1 页面设计原则

4.1.1 全屏沉浸式体验

  • 景区地图页面:全屏地图,顶部透明工具栏
  • 景区设备页面:卡片网格布局,清爽简洁
  • 设备详情页面:仪表盘式布局,信息集中展示

4.1.2 流畅的页面跳转

  • 使用 history.push() 进行路由跳转
  • 通过 location.state 传递页面状态
  • 面包屑导航支持快速返回

4.1.3 响应式布局

  • 设备卡片自适应屏幕宽度
  • 移动端优化(xs/sm/md/lg/xl断点)
  • 触摸友好的交互设计

4.2 状态管理策略

4.2.1 页面状态传递

// 从地图页面跳转到设备页面
history.push(`/device/tourismDevices/${tourism.id}`, {
  tourismName: tourism.tourismName,
  tourism: tourism, // 传递完整景区对象
});

// 在设备页面接收状态
const location = useLocation<{ tourismName?: string; tourism?: any }>();
const tourismName = location.state?.tourismName || '景区';

4.2.2 全局WebSocket连接

  • 使用UmiJS Model管理WebSocket连接
  • 全局共享连接状态和设备数据
  • 自动重连机制

4.3 性能优化

4.3.1 数据缓存

  • 景区列表缓存(避免重复请求)
  • 设备数据缓存(LocalStorage)
  • WebSocket消息队列

4.3.2 懒加载

  • 设备卡片虚拟滚动(大量设备时)
  • 视频播放器按需加载
  • 地图标记聚合

4.3.3 代码分割

  • 页面级代码分割(自动)
  • 地图组件动态导入
  • 视频播放器懒加载

五、开发计划

5.1 任务分解

阶段 任务 工作量 优先级
阶段1 后端接口开发 2天 P0
- 设备表结构调整 0.5天 P0
- 根据景区ID获取设备接口 0.5天 P0
- 根据设备SN获取设备详情接口 0.5天 P0
- 根据租户ID获取设备接口(递归查询) 0.5天 P0
阶段2 前端基础框架搭建 2.5天 P0
- 路由配置 0.5天 P0
- 景区地图页面布局 0.5天 P0
- 景区设备页面布局 0.5天 P0
- 设备详情页面布局 0.5天 P0
- 全局WebSocket模型 0.5天 P0
阶段3 核心功能实现 3.5天 P0
- 高德2D地图集成 0.5天 P0
- Mapbox 3D地图集成 1天 P0
- 设备卡片组件 0.5天 P0
- 设备详情实时数据展示 1天 P0
- 页面跳转与状态传递 0.5天 P0
阶段4 视频与控制功能 2天 P1
- 视频流播放(HLS/FLV/RTMP) 1天 P1
- 无人机控制面板 1天 P1
阶段5 优化与测试 2天 P1
- 性能优化(缓存、虚拟滚动) 0.5天 P1
- 响应式布局优化 0.5天 P1
- UI美化与动画 0.5天 P1
- 测试与Bug修复 0.5天 P1

总工作量: 12天

5.2 里程碑

  • 里程碑1 (D2): 后端接口开发完成
  • 里程碑2 (D4.5): 前端基础框架完成,三个页面可正常访问
  • 里程碑3 (D8): 核心功能完成,页面跳转流畅,地图可切换
  • 里程碑4 (D10): 视频播放和控制功能完成
  • 里程碑5 (D12): 优化完成,功能测试通过,可上线

六、环境配置

6.1 环境变量配置

# .env.production
REACT_APP_API_BASE_URL=http://119.45.169.13:9900
REACT_APP_WS_BASE_URL=ws://119.45.169.13:8848
REACT_APP_AMAP_KEY=YOUR_AMAP_KEY
REACT_APP_MAPBOX_TOKEN=YOUR_MAPBOX_TOKEN

6.2 API Key申请

高德地图API Key

  1. 访问 高德开放平台
  2. 注册/登录账号
  3. 进入控制台 → 应用管理 → 创建新应用
  4. 添加Key:选择"Web端(JS API)"
  5. 复制Key到环境变量

Mapbox Token

  1. 访问 Mapbox官网
  2. 注册/登录账号
  3. 进入Account → Tokens
  4. 创建新Token(选择所有权限)
  5. 复制Token到环境变量

七、测试方案

7.1 功能测试

  • 页面跳转测试:地图 → 设备列表 → 设备详情
  • 面包屑导航测试:返回上一级页面
  • 地图切换测试:2D/3D地图切换
  • WebSocket测试:实时数据订阅与更新
  • 状态传递测试:页面间数据传递正确性

7.2 性能测试

  • 100个景区标记渲染性能
  • 500个设备卡片加载性能
  • 页面切换耗时测试
  • WebSocket长连接稳定性测试

7.3 兼容性测试

  • Chrome/Firefox/Safari/Edge浏览器测试
  • 移动端iOS/Android测试
  • 不同屏幕分辨率测试

八、部署方案

8.1 前端部署

  • 构建: npm run build
  • 产物: dist/ 目录
  • 部署: 上传至Nginx服务器或CDN

8.2 后端部署

  • 模块: zlt-business/device-center
  • 端口: 9900
  • 配置:
    • WebSocket服务地址:ws://119.45.169.13:8848
    • 高德地图API Key(环境变量)
    • Mapbox Token(环境变量)

九、注意事项

9.1 页面跳转

  • 使用 history.push() 而非 history.replace()(保留历史记录)
  • 通过 location.state 传递页面状态(避免重复请求)
  • 面包屑支持快速返回

9.2 状态管理

  • WebSocket连接全局共享(UmiJS Model)
  • 设备数据缓存在Model中
  • 页面卸载时取消订阅

9.3 性能优化

  • 设备列表虚拟滚动(大量设备时)
  • 地图标记聚合(大量景区时)
  • 视频播放器懒加载

9.4 用户体验

  • 页面切换动画流畅
  • 加载状态清晰
  • 错误提示友好

十、参考资料

10.1 文档

10.2 示例代码

  • 参考页面:zlt-web/react-web/src/main/frontend/src/pages/device-ops/map-dashboard/index.tsx

文档版本: v3.0(三个独立页面方案) 编写日期: 2025-01-17 编写人: Claude AI 审核人: 待审核