feat: 3d模型

This commit is contained in:
2025-12-09 17:13:20 +08:00
parent 5f603bc69d
commit 358639a8ac
492 changed files with 74670 additions and 190 deletions
@@ -0,0 +1,429 @@
import React, { useEffect, useState } from 'react';
import {
Modal,
Form,
Input,
Select,
InputNumber,
Row,
Col,
Divider,
message,
} from 'antd';
import {
createModel,
updateModel,
ThreeDModelVO,
ThreeDModelDTO,
ModelTypeMap,
} from '@/services/threeDModel';
import { ordersApi } from '@/services/orders';
interface ModelFormModalProps {
visible: boolean;
isEdit: boolean;
model: ThreeDModelVO | null;
onCancel: () => void;
onSuccess: (modelId: number) => void;
}
interface TourismOption {
id: number;
name: string;
}
const ModelFormModal: React.FC<ModelFormModalProps> = ({
visible,
isEdit,
model,
onCancel,
onSuccess,
}) => {
const [form] = Form.useForm();
const [loading, setLoading] = React.useState(false);
const [tourismList, setTourismList] = useState<TourismOption[]>([]);
const [tourismLoading, setTourismLoading] = useState(false);
// 加载景区列表
useEffect(() => {
if (visible) {
loadTourismList();
}
}, [visible]);
const loadTourismList = async () => {
setTourismLoading(true);
try {
const res = await ordersApi.tourism({ current: 1, pageSize: 1000 });
const list = (res.data || []).map((item: any) => ({
id: item.id,
name: item.name || item.tourismName,
}));
setTourismList(list);
} catch (error) {
console.error('加载景区列表失败:', error);
} finally {
setTourismLoading(false);
}
};
// 重置表单
useEffect(() => {
if (visible) {
if (isEdit && model) {
form.setFieldsValue({
modelName: model.modelName,
modelType: model.modelType,
description: model.description,
tourismId: model.tourismId,
tourismName: model.tourismName,
sourceType: model.sourceType,
// 位置参数
offsetLongitude: model.position?.longitude || 0,
offsetLatitude: model.position?.latitude || 0,
offsetHeight: model.position?.height || 0,
// 变换参数
scale: model.transform?.scale || 1,
rotationX: model.transform?.rotationX || 0,
rotationY: model.transform?.rotationY || 0,
rotationZ: model.transform?.rotationZ || 0,
// 渲染参数
maxScreenSpaceError: model.style?.maximumScreenSpaceError || 16,
maxMemoryUsage: model.style?.maximumMemoryUsage || 512,
skipLod: model.style?.skipLevelOfDetail ? 1 : 0,
preferLeaves: model.style?.preferLeaves ? 1 : 0,
status: model.status,
});
} else {
form.resetFields();
// 使用高清晰度默认配置
form.setFieldsValue({
modelType: 1,
modelFormat: '3dtiles',
sourceType: 'dji_terra',
// 位置调整 - 默认不偏移,模型会自动定位
offsetLongitude: 0,
offsetLatitude: 0,
offsetHeight: 0,
// 变换参数 - 默认不变换
scale: 1,
rotationX: 0,
rotationY: 0,
rotationZ: 0,
// 渲染配置 - 使用高清晰度配置(类似大疆司空)
maxScreenSpaceError: 1, // 1-2=高清,16=较模糊
maxMemoryUsage: 2048, // 2GB内存保证清晰度
skipLod: 0, // 0=不跳过,更清晰
preferLeaves: 1, // 1=优先叶子节点
status: 1,
});
}
}
}, [visible, isEdit, model, form]);
// 提交表单
const handleSubmit = async () => {
try {
const values = await form.validateFields();
setLoading(true);
const dto: ThreeDModelDTO = {
...values,
id: isEdit ? model?.id : undefined,
};
let modelId: number;
if (isEdit) {
await updateModel(dto);
modelId = model!.id;
message.success('更新成功');
} else {
const res = await createModel(dto);
modelId = res.datas;
message.success('创建成功');
}
onSuccess(modelId);
} catch (error: any) {
if (error.errorFields) {
// 表单验证错误
return;
}
message.error(error.message || '操作失败');
} finally {
setLoading(false);
}
};
return (
<Modal
title={isEdit ? '编辑模型' : '新建模型'}
open={visible}
onCancel={onCancel}
onOk={handleSubmit}
confirmLoading={loading}
width={720}
destroyOnClose
>
<Form form={form} layout="vertical">
<Row gutter={16}>
<Col span={12}>
<Form.Item
name="modelName"
label="模型名称"
rules={[{ required: true, message: '请输入模型名称' }]}
>
<Input placeholder="请输入模型名称" maxLength={100} />
</Form.Item>
</Col>
<Col span={12}>
<Form.Item
name="modelType"
label="模型类型"
rules={[{ required: true, message: '请选择模型类型' }]}
>
<Select placeholder="请选择模型类型">
{Object.entries(ModelTypeMap).map(([key, value]) => (
<Select.Option key={key} value={Number(key)}>
{value}
</Select.Option>
))}
</Select>
</Form.Item>
</Col>
</Row>
<Row gutter={16}>
<Col span={12}>
<Form.Item name="sourceType" label="来源类型">
<Select placeholder="请选择来源类型">
<Select.Option value="dji_terra">大疆建图</Select.Option>
<Select.Option value="cesium_ion">Cesium Ion</Select.Option>
<Select.Option value="custom">自定义</Select.Option>
</Select>
</Form.Item>
</Col>
<Col span={12}>
<Form.Item name="tourismId" label="关联景区">
<Select
placeholder="请选择关联景区"
allowClear
showSearch
loading={tourismLoading}
optionFilterProp="children"
onChange={(value, option: any) => {
// 同时设置景区名称
form.setFieldValue('tourismName', option?.children || '');
}}
>
{tourismList.map((item) => (
<Select.Option key={item.id} value={item.id}>
{item.name}
</Select.Option>
))}
</Select>
</Form.Item>
<Form.Item name="tourismName" hidden>
<Input />
</Form.Item>
</Col>
</Row>
<Row gutter={16}>
<Col span={12}>
<Form.Item name="status" label="状态">
<Select placeholder="请选择状态">
<Select.Option value={1}>启用</Select.Option>
<Select.Option value={0}>禁用</Select.Option>
</Select>
</Form.Item>
</Col>
</Row>
<Form.Item name="description" label="模型描述">
<Input.TextArea placeholder="请输入模型描述" rows={2} maxLength={500} />
</Form.Item>
<Divider orientation="left">位置调整(通常保持默认0,模型会自动定位)</Divider>
<Row gutter={16}>
<Col span={8}>
<Form.Item
name="offsetLongitude"
label="经度偏移(度)"
tooltip="正值向东偏移,负值向西偏移。范围: -180 ~ 180"
>
<InputNumber
style={{ width: '100%' }}
min={-180}
max={180}
step={0.0001}
precision={6}
placeholder="0"
/>
</Form.Item>
</Col>
<Col span={8}>
<Form.Item
name="offsetLatitude"
label="纬度偏移(度)"
tooltip="正值向北偏移,负值向南偏移。范围: -90 ~ 90"
>
<InputNumber
style={{ width: '100%' }}
min={-90}
max={90}
step={0.0001}
precision={6}
placeholder="0"
/>
</Form.Item>
</Col>
<Col span={8}>
<Form.Item
name="offsetHeight"
label="高度偏移(米)"
tooltip="正值向上抬升,负值向下沉降。大疆建图模型通常需要设置 -500 ~ -2000 米才能贴地"
>
<InputNumber
style={{ width: '100%' }}
min={-10000}
max={10000}
step={10}
precision={0}
placeholder="0"
/>
</Form.Item>
</Col>
</Row>
<Divider orientation="left">变换参数(通常保持默认,除非模型方向不正确)</Divider>
<Row gutter={16}>
<Col span={6}>
<Form.Item
name="scale"
label="缩放比例"
tooltip="1=原始大小,0.5=缩小一半,2=放大一倍"
>
<InputNumber
style={{ width: '100%' }}
min={0.01}
max={100}
step={0.1}
precision={2}
placeholder="1.0"
/>
</Form.Item>
</Col>
<Col span={6}>
<Form.Item
name="rotationX"
label="X轴旋转(弧度)"
tooltip="俯仰角旋转。π≈3.14=180度,π/2≈1.57=90度"
>
<InputNumber
style={{ width: '100%' }}
min={-6.28}
max={6.28}
step={0.1}
precision={4}
placeholder="0"
/>
</Form.Item>
</Col>
<Col span={6}>
<Form.Item
name="rotationY"
label="Y轴旋转(弧度)"
tooltip="翻滚角旋转。π≈3.14=180度,π/2≈1.57=90度"
>
<InputNumber
style={{ width: '100%' }}
min={-6.28}
max={6.28}
step={0.1}
precision={4}
placeholder="0"
/>
</Form.Item>
</Col>
<Col span={6}>
<Form.Item
name="rotationZ"
label="Z轴旋转(弧度)"
tooltip="航向角旋转(朝向)。π≈3.14=180度,π/2≈1.57=90度"
>
<InputNumber
style={{ width: '100%' }}
min={-6.28}
max={6.28}
step={0.1}
precision={4}
placeholder="0"
/>
</Form.Item>
</Col>
</Row>
<Divider orientation="left">渲染配置(核心清晰度设置)</Divider>
<Row gutter={16}>
<Col span={6}>
<Form.Item
name="maxScreenSpaceError"
label="LOD精度"
tooltip="【核心参数】值越小越清晰:1-2=高清(类似大疆司空),8=中等,16=较低,32+=模糊。推荐:1-4"
>
<InputNumber
style={{ width: '100%' }}
min={1}
max={128}
step={1}
placeholder="1"
/>
</Form.Item>
</Col>
<Col span={6}>
<Form.Item
name="maxMemoryUsage"
label="最大内存(MB)"
tooltip="显存/内存限制,越大越能加载高清瓦片。推荐:1024-2048MB"
>
<InputNumber
style={{ width: '100%' }}
min={256}
max={8192}
step={256}
placeholder="2048"
/>
</Form.Item>
</Col>
<Col span={6}>
<Form.Item
name="skipLod"
label="跳过LOD"
tooltip="否=更清晰(逐级加载),是=更快但可能模糊"
>
<Select>
<Select.Option value={0}>否(更清晰)</Select.Option>
<Select.Option value={1}>是(更快)</Select.Option>
</Select>
</Form.Item>
</Col>
<Col span={6}>
<Form.Item
name="preferLeaves"
label="优先叶子节点"
tooltip="是=优先加载最精细的瓦片(推荐)"
>
<Select>
<Select.Option value={1}>是(推荐)</Select.Option>
<Select.Option value={0}>否</Select.Option>
</Select>
</Form.Item>
</Col>
</Row>
</Form>
</Modal>
);
};
export default ModelFormModal;
@@ -0,0 +1,174 @@
.previewContainer {
// 高度调整控制面板
.heightControl {
margin-bottom: 16px;
padding: 16px;
background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);
border: 1px solid #91d5ff;
border-radius: 8px;
.heightControlTitle {
font-size: 14px;
font-weight: 500;
color: #1890ff;
margin-bottom: 12px;
}
.modelHeightInfo {
display: flex;
gap: 24px;
margin-bottom: 16px;
padding: 12px 16px;
background: #fff;
border-radius: 6px;
border: 1px solid #d9d9d9;
.heightInfoItem {
display: flex;
align-items: center;
gap: 8px;
.label {
color: #666;
font-size: 13px;
}
.value {
font-weight: 600;
color: #ff4d4f;
font-size: 15px;
}
.suggestedValue {
font-weight: 600;
color: #52c41a;
font-size: 15px;
}
}
}
.heightControlContent {
display: flex;
align-items: center;
gap: 24px;
.sliderWrapper {
flex: 1;
display: flex;
align-items: center;
gap: 12px;
.sliderLabel {
font-size: 12px;
color: #666;
white-space: nowrap;
}
:global {
.ant-slider {
margin: 10px 0;
}
.ant-slider-mark-text {
color: #666;
font-size: 11px;
}
}
}
.heightInputGroup {
display: flex;
align-items: center;
gap: 12px;
flex-shrink: 0;
}
}
.heightTip {
margin-top: 12px;
font-size: 12px;
color: #666;
padding: 8px 12px;
background: rgba(255, 255, 255, 0.6);
border-radius: 4px;
strong {
color: #1890ff;
font-size: 14px;
}
}
}
.viewerContainer {
position: relative;
width: 100%;
height: 500px;
background: #1a1a2e;
border-radius: 8px;
overflow: hidden;
.cesiumViewer {
width: 100%;
height: 500px;
:global {
.cesium-widget,
.cesium-widget canvas {
width: 100% !important;
height: 100% !important;
}
}
}
.loadingOverlay,
.errorOverlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
display: flex;
justify-content: center;
align-items: center;
background: rgba(0, 0, 0, 0.7);
z-index: 10;
:global {
.ant-spin-text {
color: #fff;
margin-top: 16px;
}
}
}
.errorOverlay {
background: rgba(0, 0, 0, 0.85);
:global {
.ant-alert {
max-width: 400px;
}
}
}
}
.urlInfo {
margin-top: 12px;
padding: 8px 12px;
background: #fafafa;
border-radius: 4px;
display: flex;
align-items: center;
gap: 8px;
}
}
// 隐藏Cesium默认UI
:global {
.cesium-viewer-bottom {
display: none !important;
}
.cesium-viewer-toolbar {
display: none !important;
}
}
@@ -0,0 +1,423 @@
import React, { useEffect, useRef, useState, useCallback } from 'react';
import { Modal, Spin, Alert, Typography, Descriptions, Tag, Slider, InputNumber, Button, Space, message } from 'antd';
import { ThreeDModelVO, updateModel } from '@/services/threeDModel';
import styles from './ModelPreviewModal.less';
const { Text } = Typography;
interface ModelPreviewModalProps {
visible: boolean;
model: ThreeDModelVO | null;
onCancel: () => void;
onHeightUpdated?: () => void; // 高度更新后的回调,用于刷新列表
}
// 动态导入Cesium
let Cesium: any = null;
const ModelPreviewModal: React.FC<ModelPreviewModalProps> = ({
visible,
model,
onCancel,
onHeightUpdated,
}) => {
const containerRef = useRef<HTMLDivElement>(null);
const viewerRef = useRef<any>(null);
const tilesetRef = useRef<any>(null);
const originalCenterRef = useRef<any>(null); // 保存模型原始中心点
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [initialized, setInitialized] = useState(false);
// 高度调整状态
const [heightOffset, setHeightOffset] = useState<number>(0);
const [saving, setSaving] = useState(false);
const [modelHeight, setModelHeight] = useState<number | null>(null); // 模型原始高度
const [suggestedOffset, setSuggestedOffset] = useState<number>(0); // 建议的偏移值
// 清理函数
const cleanup = useCallback(() => {
if (tilesetRef.current) {
if (viewerRef.current && !viewerRef.current.isDestroyed()) {
try {
viewerRef.current.scene.primitives.remove(tilesetRef.current);
} catch (e) {
console.warn('Failed to remove tileset:', e);
}
}
tilesetRef.current = null;
}
if (viewerRef.current && !viewerRef.current.isDestroyed()) {
try {
viewerRef.current.destroy();
} catch (e) {
console.warn('Failed to destroy viewer:', e);
}
viewerRef.current = null;
}
originalCenterRef.current = null;
setInitialized(false);
}, []);
// 实时调整模型高度
const adjustHeight = useCallback((offset: number) => {
if (!tilesetRef.current || !Cesium || !originalCenterRef.current) return;
const tileset = tilesetRef.current;
const originalCenter = originalCenterRef.current;
// 计算新的中心点位置
const cartographic = Cesium.Cartographic.fromCartesian(originalCenter);
const newHeight = cartographic.height + offset;
const newCenter = Cesium.Cartesian3.fromRadians(
cartographic.longitude,
cartographic.latitude,
newHeight
);
// 计算平移量
const translation = Cesium.Cartesian3.subtract(
newCenter,
originalCenter,
new Cesium.Cartesian3()
);
// 应用变换矩阵
tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
// 请求重新渲染
if (viewerRef.current && !viewerRef.current.isDestroyed()) {
viewerRef.current.scene.requestRender();
}
}, []);
// 高度偏移变化时实时调整
useEffect(() => {
if (initialized && tilesetRef.current) {
adjustHeight(heightOffset);
}
}, [heightOffset, initialized, adjustHeight]);
// 保存高度偏移到数据库
const saveHeightOffset = async () => {
if (!model) return;
setSaving(true);
try {
await updateModel({
id: model.id,
modelName: model.modelName,
offsetHeight: heightOffset,
});
message.success(`高度偏移已保存: ${heightOffset}米`);
onHeightUpdated?.();
} catch (err: any) {
message.error('保存失败: ' + (err.message || '未知错误'));
} finally {
setSaving(false);
}
};
// 初始化Viewer和加载模型
const initViewer = useCallback(async () => {
if (!model?.tilesetUrl || !containerRef.current) return;
// 先清理旧的
cleanup();
setLoading(true);
setError(null);
// 初始化高度偏移为模型当前配置的值
const initialHeight = model.position?.height || 0;
setHeightOffset(initialHeight);
try {
// 动态加载Cesium
if (!Cesium) {
const cesiumModule = await import('cesium');
Cesium = cesiumModule;
const cesiumBaseUrl = process.env.CESIUM_BASE_URL || '/';
Cesium.buildModuleUrl.setBaseUrl(`${cesiumBaseUrl}cesium/`);
}
if (!containerRef.current) {
throw new Error('容器未就绪');
}
// 创建Viewer
const viewer = new Cesium.Viewer(containerRef.current, {
terrainProvider: new Cesium.EllipsoidTerrainProvider(),
scene3DOnly: true,
animation: false,
timeline: false,
fullscreenButton: false,
geocoder: false,
homeButton: false,
sceneModePicker: false,
baseLayerPicker: false,
navigationHelpButton: false,
infoBox: false,
selectionIndicator: false,
});
viewerRef.current = viewer;
// 隐藏版权信息
const creditContainer = viewer.cesiumWidget.creditContainer;
if (creditContainer) {
creditContainer.style.display = 'none';
}
// 添加影像图层
const arcgisImagery = new Cesium.UrlTemplateImageryProvider({
url: 'https://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
minimumLevel: 0,
maximumLevel: 18,
});
viewer.imageryLayers.addImageryProvider(arcgisImagery);
// 加载3D Tiles模型 - 预览时使用高质量设置
const tileset = await Cesium.Cesium3DTileset.fromUrl(model.tilesetUrl, {
maximumScreenSpaceError: 1,
maximumMemoryUsage: 2048,
skipLevelOfDetail: false,
preferLeaves: true,
dynamicScreenSpaceError: false,
immediatelyLoadDesiredLevelOfDetail: true,
loadSiblings: true,
});
tilesetRef.current = tileset;
viewer.scene.primitives.add(tileset);
// 保存原始中心点(用于高度调整计算)
originalCenterRef.current = Cesium.Cartesian3.clone(tileset.boundingSphere.center);
// 计算模型的WGS84高度,并给出建议的偏移值
const cartographic = Cesium.Cartographic.fromCartesian(tileset.boundingSphere.center);
const heightInMeters = cartographic.height;
setModelHeight(Math.round(heightInMeters));
// 建议的偏移值:取负值让模型下降到地面
// 保留一点高度(约50米)避免模型陷入地面
const suggested = -Math.round(heightInMeters) + 50;
setSuggestedOffset(suggested);
console.log(`模型高度: ${heightInMeters.toFixed(2)}米, 建议偏移: ${suggested}米`);
// 如果有初始高度偏移,立即应用
if (initialHeight !== 0) {
adjustHeight(initialHeight);
}
// 强制刷新viewer尺寸
viewer.resize();
// 飞到模型位置
try {
await viewer.flyTo(tileset, {
duration: 1.5,
offset: new Cesium.HeadingPitchRange(
Cesium.Math.toRadians(0),
Cesium.Math.toRadians(-45),
0
),
});
} catch (flyError) {
console.warn('flyTo failed, trying zoomTo:', flyError);
await viewer.zoomTo(tileset);
}
// 再次刷新
setTimeout(() => {
if (viewer && !viewer.isDestroyed()) {
viewer.resize();
}
}, 100);
setInitialized(true);
setLoading(false);
} catch (err: any) {
console.error('加载模型失败:', err);
setError(err.message || '加载模型失败');
setLoading(false);
}
}, [model?.tilesetUrl, model?.position?.height, cleanup, adjustHeight]);
// 当弹窗打开时初始化
useEffect(() => {
if (visible && model?.tilesetUrl) {
// 延迟初始化,确保DOM已渲染
const timer = setTimeout(() => {
initViewer();
}, 100);
return () => clearTimeout(timer);
}
}, [visible, model?.tilesetUrl, initViewer]);
// 当弹窗关闭时清理
useEffect(() => {
if (!visible) {
cleanup();
setLoading(false);
setError(null);
setHeightOffset(0);
setModelHeight(null);
setSuggestedOffset(0);
}
}, [visible, cleanup]);
// 组件卸载时清理
useEffect(() => {
return () => {
cleanup();
};
}, [cleanup]);
return (
<Modal
title={`模型预览 - ${model?.modelName || ''}`}
open={visible}
onCancel={onCancel}
width={1100}
footer={null}
destroyOnClose={false}
afterClose={cleanup}
>
<div className={styles.previewContainer}>
{/* 模型信息 */}
{model && (
<Descriptions size="small" column={4} style={{ marginBottom: 16 }}>
<Descriptions.Item label="模型类型">
<Tag color="blue">{model.modelTypeName}</Tag>
</Descriptions.Item>
<Descriptions.Item label="文件数量">{model.fileCount}</Descriptions.Item>
<Descriptions.Item label="文件大小">{model.totalSizeFormat}</Descriptions.Item>
<Descriptions.Item label="来源">{model.sourceType}</Descriptions.Item>
</Descriptions>
)}
{/* 高度调整控制面板 */}
{initialized && (
<div className={styles.heightControl}>
<div className={styles.heightControlTitle}>
<span>🎚️ 高度调整(模型在空中飘着?向下调整;模型陷入地面?向上调整)</span>
</div>
{/* 模型高度信息 */}
{modelHeight !== null && (
<div className={styles.modelHeightInfo}>
<div className={styles.heightInfoItem}>
<span className={styles.label}>模型原始高度:</span>
<span className={styles.value}>{modelHeight} 米</span>
</div>
<div className={styles.heightInfoItem}>
<span className={styles.label}>建议偏移值:</span>
<span className={styles.suggestedValue}>{suggestedOffset} 米</span>
<Button
type="link"
size="small"
onClick={() => setHeightOffset(suggestedOffset)}
>
应用建议值
</Button>
</div>
</div>
)}
<div className={styles.heightControlContent}>
<div className={styles.sliderWrapper}>
<span className={styles.sliderLabel}>下沉 ↓</span>
<Slider
min={-5000}
max={5000}
step={10}
value={heightOffset}
onChange={(val) => setHeightOffset(val)}
tooltip={{ formatter: (val) => `${val}米` }}
marks={{
'-5000': '-5km',
'-2000': '-2km',
'-1000': '-1km',
0: '0',
1000: '+1km',
2000: '+2km',
5000: '+5km',
}}
style={{ flex: 1 }}
/>
<span className={styles.sliderLabel}>↑ 抬升</span>
</div>
<div className={styles.heightInputGroup}>
<InputNumber
value={heightOffset}
onChange={(val) => setHeightOffset(val || 0)}
step={10}
addonAfter="米"
style={{ width: 120 }}
/>
<Space>
<Button size="small" onClick={() => setHeightOffset(0)}>
重置为0
</Button>
<Button
size="small"
onClick={() => setHeightOffset(suggestedOffset)}
>
应用建议值
</Button>
<Button
type="primary"
size="small"
loading={saving}
onClick={saveHeightOffset}
>
保存高度
</Button>
</Space>
</div>
</div>
<div className={styles.heightTip}>
当前高度偏移: <strong>{heightOffset}</strong> 米。调整到合适位置后点击"保存高度",地图仪表盘加载时会自动应用此设置。
</div>
</div>
)}
{/* 预览区域 */}
<div className={styles.viewerContainer}>
{loading && (
<div className={styles.loadingOverlay}>
<Spin size="large" tip="正在加载模型..." />
</div>
)}
{error && (
<div className={styles.errorOverlay}>
<Alert
message="加载失败"
description={error}
type="error"
showIcon
/>
</div>
)}
<div ref={containerRef} className={styles.cesiumViewer} />
</div>
{/* URL信息 */}
{model?.tilesetUrl && (
<div className={styles.urlInfo}>
<Text type="secondary">模型URL: </Text>
<Text copyable ellipsis style={{ maxWidth: 800 }}>
{model.tilesetUrl}
</Text>
</div>
)}
</div>
</Modal>
);
};
export default ModelPreviewModal;
@@ -0,0 +1,109 @@
.uploadContainer {
min-height: 300px;
.selectArea {
.folderSelector {
border: 2px dashed #d9d9d9;
border-radius: 8px;
padding: 40px;
text-align: center;
cursor: pointer;
transition: all 0.3s;
&:hover {
border-color: #1890ff;
background: #f0f7ff;
}
.folderLabel {
display: flex;
flex-direction: column;
align-items: center;
gap: 16px;
cursor: pointer;
.labelText {
display: flex;
flex-direction: column;
gap: 4px;
}
}
}
}
.statsBar {
background: #fafafa;
padding: 12px 16px;
border-radius: 4px;
margin-bottom: 16px;
}
.fileList {
border: 1px solid #f0f0f0;
border-radius: 4px;
overflow: hidden;
:global {
.ant-list-item {
padding: 8px 12px;
border-bottom: 1px solid #f0f0f0;
&:last-child {
border-bottom: none;
}
}
}
.fileItem {
display: flex;
justify-content: space-between;
align-items: center;
&.pending {
background: #fff;
}
&.uploading {
background: #e6f7ff;
}
&.success {
background: #f6ffed;
}
&.error {
background: #fff2f0;
}
.fileInfo {
display: flex;
justify-content: space-between;
align-items: center;
flex: 1;
margin-right: 16px;
min-width: 0;
}
}
}
}
// 自定义滚动条
.fileList :global(.ant-list) {
&::-webkit-scrollbar {
width: 6px;
}
&::-webkit-scrollbar-track {
background: #f0f0f0;
border-radius: 3px;
}
&::-webkit-scrollbar-thumb {
background: #d9d9d9;
border-radius: 3px;
&:hover {
background: #bfbfbf;
}
}
}
@@ -0,0 +1,407 @@
import React, { useState, useCallback, useRef } from 'react';
import {
Modal,
Upload,
Button,
Progress,
List,
Typography,
Space,
Alert,
message,
Spin,
Tag,
Result,
} from 'antd';
import {
InboxOutlined,
FileOutlined,
CheckCircleOutlined,
CloseCircleOutlined,
LoadingOutlined,
FolderOpenOutlined,
} from '@ant-design/icons';
import type { UploadFile } from 'antd/es/upload/interface';
import {
uploadSingleFile,
completeUpload,
ThreeDModelVO,
} from '@/services/threeDModel';
import styles from './ModelUploadModal.less';
const { Dragger } = Upload;
const { Text, Paragraph } = Typography;
interface ModelUploadModalProps {
visible: boolean;
model: ThreeDModelVO | null;
onCancel: () => void;
onComplete: () => void;
}
interface FileUploadItem {
file: File;
relativePath: string;
status: 'pending' | 'uploading' | 'success' | 'error';
progress: number;
url?: string;
error?: string;
}
const ModelUploadModal: React.FC<ModelUploadModalProps> = ({
visible,
model,
onCancel,
onComplete,
}) => {
const [fileList, setFileList] = useState<FileUploadItem[]>([]);
const [uploading, setUploading] = useState(false);
const [uploadComplete, setUploadComplete] = useState(false);
const [overallProgress, setOverallProgress] = useState(0);
const abortRef = useRef(false);
// 重置状态
const resetState = () => {
setFileList([]);
setUploading(false);
setUploadComplete(false);
setOverallProgress(0);
abortRef.current = false;
};
// 处理文件夹选择
const handleFolderSelect = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
const files = e.target.files;
if (!files || files.length === 0) return;
const items: FileUploadItem[] = [];
for (let i = 0; i < files.length; i++) {
const file = files[i];
// webkitRelativePath 包含完整的相对路径
const relativePath = (file as any).webkitRelativePath || file.name;
items.push({
file,
relativePath,
status: 'pending',
progress: 0,
});
}
// 检查是否包含tileset.json
const hasTileset = items.some(
(item) =>
item.relativePath.endsWith('tileset.json') &&
!item.relativePath.includes('/Block/')
);
if (!hasTileset) {
message.warning('未检测到根目录下的tileset.json文件,请确保选择了正确的3D Tiles文件夹');
}
setFileList(items);
setUploadComplete(false);
}, []);
// 开始上传
const handleUpload = async () => {
if (!model?.id || fileList.length === 0) {
message.error('请先选择文件');
return;
}
setUploading(true);
abortRef.current = false;
let successCount = 0;
let failCount = 0;
// 更新文件列表
const updateFileStatus = (
index: number,
status: FileUploadItem['status'],
progress: number,
url?: string,
error?: string
) => {
setFileList((prev) => {
const newList = [...prev];
newList[index] = { ...newList[index], status, progress, url, error };
return newList;
});
};
// 逐个上传文件
for (let i = 0; i < fileList.length; i++) {
if (abortRef.current) break;
const item = fileList[i];
updateFileStatus(i, 'uploading', 0);
try {
const result = await uploadSingleFile(
model.id,
item.file,
item.relativePath,
(percent) => {
updateFileStatus(i, 'uploading', percent);
}
);
if (result.resp_code === 0) {
updateFileStatus(i, 'success', 100, result.datas);
successCount++;
} else {
throw new Error(result.resp_msg || '上传失败');
}
} catch (error: any) {
updateFileStatus(i, 'error', 0, undefined, error.message);
failCount++;
}
// 更新总进度
setOverallProgress(Math.round(((i + 1) / fileList.length) * 100));
}
// 如果全部成功,调用完成接口
if (successCount === fileList.length) {
try {
await completeUpload(model.id);
message.success('所有文件上传完成!');
setUploadComplete(true);
} catch (error) {
message.error('更新状态失败');
}
} else if (failCount > 0) {
message.warning(`上传完成,成功 ${successCount} 个,失败 ${failCount} 个`);
}
setUploading(false);
};
// 取消上传
const handleAbort = () => {
abortRef.current = true;
message.info('正在取消上传...');
};
// 关闭弹窗
const handleClose = () => {
if (uploading) {
Modal.confirm({
title: '确定要取消上传吗?',
content: '取消后已上传的文件将保留',
onOk: () => {
handleAbort();
setTimeout(() => {
resetState();
onCancel();
}, 500);
},
});
} else {
if (uploadComplete) {
onComplete();
} else {
onCancel();
}
resetState();
}
};
// 统计信息
const stats = {
total: fileList.length,
success: fileList.filter((f) => f.status === 'success').length,
error: fileList.filter((f) => f.status === 'error').length,
pending: fileList.filter((f) => f.status === 'pending').length,
uploading: fileList.filter((f) => f.status === 'uploading').length,
totalSize: fileList.reduce((sum, f) => sum + f.file.size, 0),
};
const formatSize = (bytes: number) => {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};
return (
<Modal
title={`上传模型文件 - ${model?.modelName || ''}`}
open={visible}
onCancel={handleClose}
width={800}
footer={
uploadComplete ? (
<Button type="primary" onClick={handleClose}>
完成
</Button>
) : (
<Space>
<Button onClick={handleClose}>{uploading ? '取消' : '关闭'}</Button>
{!uploading && fileList.length > 0 && (
<Button type="primary" onClick={handleUpload}>
开始上传
</Button>
)}
{uploading && (
<Button danger onClick={handleAbort}>
停止上传
</Button>
)}
</Space>
)
}
destroyOnClose
>
<div className={styles.uploadContainer}>
{uploadComplete ? (
<Result
status="success"
title="上传完成"
subTitle={`成功上传 ${stats.success} 个文件,共 ${formatSize(stats.totalSize)}`}
/>
) : (
<>
{/* 文件选择区域 */}
{fileList.length === 0 && (
<div className={styles.selectArea}>
<Alert
message="请选择3D Tiles模型文件夹"
description="选择大疆建图输出的 terra_b3dms 文件夹,包含 tileset.json 和所有 .b3dm 文件"
type="info"
showIcon
style={{ marginBottom: 16 }}
/>
<div className={styles.folderSelector}>
<input
type="file"
id="folderInput"
/* @ts-ignore */
webkitdirectory=""
directory=""
multiple
onChange={handleFolderSelect}
style={{ display: 'none' }}
/>
<label htmlFor="folderInput" className={styles.folderLabel}>
<FolderOpenOutlined style={{ fontSize: 48, color: '#1890ff' }} />
<div className={styles.labelText}>
<Text strong>点击选择文件夹</Text>
<Text type="secondary">或将文件夹拖放到此处</Text>
</div>
</label>
</div>
</div>
)}
{/* 文件列表 */}
{fileList.length > 0 && (
<>
{/* 统计信息 */}
<div className={styles.statsBar}>
<Space split={<span style={{ color: '#d9d9d9' }}>|</span>}>
<Text>共 {stats.total} 个文件</Text>
<Text>总大小 {formatSize(stats.totalSize)}</Text>
{stats.success > 0 && (
<Text type="success">成功 {stats.success}</Text>
)}
{stats.error > 0 && <Text type="danger">失败 {stats.error}</Text>}
{stats.uploading > 0 && (
<Text type="warning">上传中 {stats.uploading}</Text>
)}
</Space>
</div>
{/* 总进度 */}
{uploading && (
<Progress
percent={overallProgress}
status="active"
strokeColor={{
'0%': '#108ee9',
'100%': '#87d068',
}}
style={{ marginBottom: 16 }}
/>
)}
{/* 文件列表 */}
<div className={styles.fileList}>
<List
size="small"
dataSource={fileList}
renderItem={(item, index) => (
<List.Item
className={`${styles.fileItem} ${styles[item.status]}`}
>
<div className={styles.fileInfo}>
<Space>
{item.status === 'pending' && <FileOutlined />}
{item.status === 'uploading' && (
<LoadingOutlined spin />
)}
{item.status === 'success' && (
<CheckCircleOutlined style={{ color: '#52c41a' }} />
)}
{item.status === 'error' && (
<CloseCircleOutlined style={{ color: '#ff4d4f' }} />
)}
<Text
ellipsis={{ tooltip: item.relativePath }}
style={{ maxWidth: 400 }}
>
{item.relativePath}
</Text>
</Space>
<Text type="secondary" style={{ fontSize: 12 }}>
{formatSize(item.file.size)}
</Text>
</div>
{item.status === 'uploading' && (
<Progress
percent={item.progress}
size="small"
style={{ width: 100 }}
/>
)}
{item.status === 'error' && (
<Text type="danger" style={{ fontSize: 12 }}>
{item.error}
</Text>
)}
</List.Item>
)}
style={{ maxHeight: 400, overflow: 'auto' }}
/>
</div>
{/* 重新选择 */}
{!uploading && (
<div style={{ marginTop: 16, textAlign: 'center' }}>
<input
type="file"
id="folderInputReset"
/* @ts-ignore */
webkitdirectory=""
directory=""
multiple
onChange={handleFolderSelect}
style={{ display: 'none' }}
/>
<label htmlFor="folderInputReset">
<Button type="link">重新选择文件夹</Button>
</label>
</div>
)}
</>
)}
</>
)}
</div>
</Modal>
);
};
export default ModelUploadModal;
@@ -0,0 +1,73 @@
.threeDModelPage {
:global {
.ant-pro-table-search {
margin-bottom: 16px;
}
.ant-tag {
margin-right: 0;
}
}
.statusSwitch {
&.disabled {
opacity: 0.5;
}
}
.fileInfo {
display: flex;
flex-direction: column;
.fileCount {
font-weight: 500;
}
.fileSize {
color: #999;
font-size: 12px;
}
}
.actionButtons {
display: flex;
gap: 4px;
}
}
// 上传进度条样式
.uploadProgress {
display: inline-flex;
align-items: center;
gap: 8px;
:global {
.ant-progress {
margin-bottom: 0;
}
}
}
// 预览区域
.previewContainer {
width: 100%;
height: 500px;
background: #000;
border-radius: 8px;
overflow: hidden;
position: relative;
.cesiumViewer {
width: 100%;
height: 100%;
}
.loadingOverlay {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: #fff;
text-align: center;
}
}
@@ -0,0 +1,344 @@
import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import {
Button,
Space,
Modal,
message,
Popconfirm,
Progress,
Tooltip,
Switch,
Tag,
} from 'antd';
import {
PlusOutlined,
DeleteOutlined,
EditOutlined,
EyeOutlined,
CloudUploadOutlined,
} from '@ant-design/icons';
import {
getModelList,
deleteModel,
updateModelStatus,
ModelTypeMap,
ThreeDModelVO,
} from '@/services/threeDModel';
import ModelFormModal from './components/ModelFormModal';
import ModelUploadModal from './components/ModelUploadModal';
import ModelPreviewModal from './components/ModelPreviewModal';
import styles from './index.less';
/**
* 3D模型文件管理页面
*/
const ThreeDModelPage: React.FC = () => {
const actionRef = useRef<ActionType>();
const [formModalVisible, setFormModalVisible] = useState(false);
const [uploadModalVisible, setUploadModalVisible] = useState(false);
const [previewModalVisible, setPreviewModalVisible] = useState(false);
const [currentModel, setCurrentModel] = useState<ThreeDModelVO | null>(null);
const [isEdit, setIsEdit] = useState(false);
// 处理新建
const handleCreate = () => {
setCurrentModel(null);
setIsEdit(false);
setFormModalVisible(true);
};
// 处理编辑
const handleEdit = (record: ThreeDModelVO) => {
setCurrentModel(record);
setIsEdit(true);
setFormModalVisible(true);
};
// 处理上传
const handleUpload = (record: ThreeDModelVO) => {
setCurrentModel(record);
setUploadModalVisible(true);
};
// 处理预览
const handlePreview = (record: ThreeDModelVO) => {
setCurrentModel(record);
setPreviewModalVisible(true);
};
// 处理删除
const handleDelete = async (id: number) => {
try {
await deleteModel(id);
message.success('删除成功');
actionRef.current?.reload();
} catch (error) {
message.error('删除失败');
}
};
// 处理状态切换
const handleStatusChange = async (id: number, checked: boolean) => {
try {
await updateModelStatus(id, checked ? 1 : 0);
message.success(checked ? '已启用' : '已禁用');
actionRef.current?.reload();
} catch (error) {
message.error('操作失败');
}
};
// 表单提交成功回调
const handleFormSuccess = (modelId: number) => {
setFormModalVisible(false);
actionRef.current?.reload();
// 如果是新建,提示去上传文件
if (!isEdit) {
Modal.confirm({
title: '模型创建成功',
content: '是否立即上传模型文件?',
okText: '去上传',
cancelText: '稍后',
onOk: () => {
// 获取新创建的模型然后打开上传
setCurrentModel({ id: modelId } as ThreeDModelVO);
setUploadModalVisible(true);
},
});
}
};
// 上传完成回调
const handleUploadComplete = () => {
setUploadModalVisible(false);
actionRef.current?.reload();
};
// 获取上传状态标签
const getUploadStatusTag = (status: number, progress: number) => {
switch (status) {
case 0:
return <Tag>待上传</Tag>;
case 1:
return (
<Tooltip title={`上传进度: ${progress}%`}>
<Tag color="processing">
上传中 <Progress percent={progress} size="small" style={{ width: 60 }} />
</Tag>
</Tooltip>
);
case 2:
return <Tag color="success">已完成</Tag>;
case 3:
return <Tag color="error">失败</Tag>;
default:
return <Tag>未知</Tag>;
}
};
// 表格列定义
const columns: ProColumns<ThreeDModelVO>[] = [
{
title: '模型名称',
dataIndex: 'modelName',
width: 180,
ellipsis: true,
render: (_, record) => (
<Space>
<span>{record.modelName}</span>
{record.uploadStatus === 2 && record.tilesetUrl && (
<Tooltip title="点击预览">
<EyeOutlined
style={{ color: '#1890ff', cursor: 'pointer' }}
onClick={() => handlePreview(record)}
/>
</Tooltip>
)}
</Space>
),
},
{
title: '模型类型',
dataIndex: 'modelType',
width: 100,
valueEnum: {
1: { text: '倾斜摄影', status: 'Success' },
2: { text: '点云', status: 'Processing' },
3: { text: 'BIM', status: 'Warning' },
4: { text: '其他', status: 'Default' },
},
},
{
title: '关联景区',
dataIndex: 'tourismName',
width: 150,
ellipsis: true,
render: (text) => text || <span style={{ color: '#999' }}>未关联</span>,
},
{
title: '文件信息',
dataIndex: 'fileCount',
width: 120,
search: false,
render: (_, record) => (
<Space direction="vertical" size={0}>
<span>{record.fileCount || 0} 个文件</span>
<span style={{ color: '#999', fontSize: 12 }}>{record.totalSizeFormat || '0 B'}</span>
</Space>
),
},
{
title: '上传状态',
dataIndex: 'uploadStatus',
width: 140,
search: false,
render: (_, record) => getUploadStatusTag(record.uploadStatus, record.uploadProgress),
},
{
title: '状态',
dataIndex: 'status',
width: 80,
valueEnum: {
0: { text: '禁用', status: 'Default' },
1: { text: '启用', status: 'Success' },
},
render: (_, record) => (
<Switch
checked={record.status === 1}
onChange={(checked) => handleStatusChange(record.id, checked)}
disabled={record.uploadStatus !== 2}
size="small"
/>
),
},
{
title: '来源',
dataIndex: 'sourceType',
width: 100,
search: false,
render: (text) => {
const sourceMap: Record<string, string> = {
dji_terra: '大疆建图',
cesium_ion: 'Cesium Ion',
custom: '自定义',
};
return sourceMap[text as string] || text;
},
},
{
title: '创建时间',
dataIndex: 'createTime',
width: 160,
valueType: 'dateTime',
search: false,
},
{
title: '操作',
valueType: 'option',
width: 200,
fixed: 'right',
render: (_, record) => (
<Space size="small">
<Button
type="link"
size="small"
icon={<CloudUploadOutlined />}
onClick={() => handleUpload(record)}
>
{record.uploadStatus === 2 ? '重新上传' : '上传'}
</Button>
<Button
type="link"
size="small"
icon={<EditOutlined />}
onClick={() => handleEdit(record)}
>
编辑
</Button>
<Popconfirm
title="确定要删除该模型吗?删除后数据将无法恢复"
onConfirm={() => handleDelete(record.id)}
okText="确定"
cancelText="取消"
>
<Button type="link" size="small" danger icon={<DeleteOutlined />}>
删除
</Button>
</Popconfirm>
</Space>
),
},
];
return (
<PageContainer
header={{
title: '3D模型管理',
subTitle: '管理大疆建图等工具生成的倾斜摄影、点云等3D模型',
}}
>
<ProTable<ThreeDModelVO>
actionRef={actionRef}
columns={columns}
rowKey="id"
scroll={{ x: 1200 }}
request={async (params) => {
const { current, pageSize, ...rest } = params;
const res = await getModelList({
page: current,
limit: pageSize,
...rest,
});
return {
data: res.data || [],
success: true,
total: res.count || 0,
};
}}
pagination={{
defaultPageSize: 10,
showSizeChanger: true,
}}
toolBarRender={() => [
<Button key="create" type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
新建模型
</Button>,
]}
search={{
labelWidth: 'auto',
defaultCollapsed: false,
}}
/>
{/* 新建/编辑模态框 */}
<ModelFormModal
visible={formModalVisible}
isEdit={isEdit}
model={currentModel}
onCancel={() => setFormModalVisible(false)}
onSuccess={handleFormSuccess}
/>
{/* 上传模态框 */}
<ModelUploadModal
visible={uploadModalVisible}
model={currentModel}
onCancel={() => setUploadModalVisible(false)}
onComplete={handleUploadComplete}
/>
{/* 预览模态框 - 支持实时调整高度并保存 */}
<ModelPreviewModal
visible={previewModalVisible}
model={currentModel}
onCancel={() => setPreviewModalVisible(false)}
onHeightUpdated={() => actionRef.current?.reload()}
/>
</PageContainer>
);
};
export default ThreeDModelPage;
@@ -0,0 +1,227 @@
@import '~antd/lib/style/themes/default.less';
@cyan: #00f0ff;
@bg-dark: rgba(10, 20, 30, 0.95);
@border-color: rgba(0, 240, 255, 0.3);
.leftPanel {
position: absolute;
top: 64px;
left: 0;
bottom: 0;
width: 400px;
background: @bg-dark;
backdrop-filter: blur(20px);
border-right: 1px solid @border-color;
display: flex;
flex-direction: column;
transform: translateX(-100%);
transition: transform 0.4s cubic-bezier(0.2, 0.8, 0.2, 1);
z-index: 900;
box-shadow: 10px 0 30px rgba(0, 0, 0, 0.5);
&.visible {
transform: translateX(0);
}
&::after {
content: '';
position: absolute;
top: 0;
right: 0;
bottom: 0;
width: 1px;
background: linear-gradient(180deg, transparent, @cyan, transparent);
box-shadow: 0 0 10px @cyan;
}
.header {
padding: 16px 20px;
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
background: rgba(0, 240, 255, 0.05);
.title {
font-size: 16px;
font-weight: 700;
color: #fff;
display: flex;
align-items: center;
gap: 8px;
.liveTag {
font-size: 10px;
background: #ff4d4f;
padding: 1px 6px;
border-radius: 2px;
animation: blink 2s infinite;
}
}
.closeBtn {
background: none;
border: 1px solid rgba(255, 255, 255, 0.2);
color: rgba(255, 255, 255, 0.6);
width: 24px;
height: 24px;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: all 0.3s;
&:hover { border-color: #ff4d4f; color: #ff4d4f; }
}
}
.videoContainer {
width: 100%;
aspect-ratio: 16/9;
background: #000;
position: relative;
border-bottom: 1px solid @border-color;
overflow: hidden;
.videoPlaceholder {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
color: rgba(0, 240, 255, 0.5);
background: radial-gradient(circle at center, rgba(0, 40, 60, 0.5) 0%, #000 100%);
background-image: linear-gradient(rgba(0, 240, 255, 0.1) 1px, transparent 1px),
linear-gradient(90deg, rgba(0, 240, 255, 0.1) 1px, transparent 1px);
background-size: 20px 20px;
.icon { font-size: 48px; margin-bottom: 12px; filter: drop-shadow(0 0 10px @cyan); }
}
.hudOverlay {
position: absolute;
top: 10px; left: 10px; right: 10px; bottom: 10px;
pointer-events: none;
border: 1px solid rgba(0, 240, 255, 0.3);
.crosshair {
position: absolute;
top: 50%; left: 50%; width: 20px; height: 20px;
border: 1px solid rgba(0, 255, 0, 0.5);
transform: translate(-50%, -50%);
&::before { content: ''; position: absolute; top: 9px; left: 0; width: 100%; height: 1px; background: rgba(0, 255, 0, 0.8); }
&::after { content: ''; position: absolute; left: 9px; top: 0; height: 100%; width: 1px; background: rgba(0, 255, 0, 0.8); }
}
}
}
// 飞行仪表盘
.flightDashboard {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
padding: 16px 20px;
background: rgba(0,0,0,0.2);
border-bottom: 1px solid rgba(255,255,255,0.05);
.dashItem {
background: rgba(255,255,255,0.05);
padding: 8px;
border-radius: 4px;
text-align: center;
.dashLabel { font-size: 10px; color: rgba(255,255,255,0.4); margin-bottom: 2px; }
.dashValue { font-size: 14px; font-weight: bold; color: #fff; font-family: 'Consolas', monospace; }
}
}
.controlsContent {
flex: 1;
overflow-y: auto;
padding: 20px;
.controlGroup {
margin-bottom: 24px;
.groupTitle {
font-size: 12px;
color: rgba(255, 255, 255, 0.4);
margin-bottom: 12px;
display: flex;
align-items: center;
&::after { content: ''; flex: 1; height: 1px; background: rgba(255, 255, 255, 0.1); margin-left: 8px; }
}
.flightActions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-bottom: 16px;
button {
height: 36px;
background: rgba(0, 240, 255, 0.1);
border: 1px solid rgba(0, 240, 255, 0.3);
color: @cyan;
cursor: pointer;
&:hover { background: rgba(0, 240, 255, 0.2); }
}
}
.joystickArea {
display: flex;
justify-content: space-between;
gap: 12px;
.joystickGroup {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
background: rgba(0,0,0,0.3);
padding: 12px 8px;
border-radius: 8px;
border: 1px solid rgba(255,255,255,0.05);
.joystickLabel {
font-size: 10px;
color: rgba(255,255,255,0.4);
margin-bottom: 8px;
}
.dpad {
display: grid;
grid-template-columns: repeat(3, 32px);
grid-template-rows: repeat(3, 32px);
gap: 4px;
button {
background: rgba(255, 255, 255, 0.1);
border: 1px solid rgba(255, 255, 255, 0.2);
color: #fff;
border-radius: 4px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
font-size: 12px;
&:hover { background: @cyan; color: #000; box-shadow: 0 0 10px @cyan; }
&:active { transform: scale(0.95); }
&.up { grid-column: 2; grid-row: 1; }
&.left { grid-column: 1; grid-row: 2; }
&.right { grid-column: 3; grid-row: 2; }
&.down { grid-column: 2; grid-row: 3; }
}
}
}
}
}
}
}
@keyframes blink {
0%, 100% { opacity: 1; }
50% { opacity: 0.4; }
}
@@ -0,0 +1,196 @@
import React from 'react';
import {
CloseOutlined,
RocketOutlined,
VideoCameraOutlined,
ArrowUpOutlined,
ArrowDownOutlined,
ArrowLeftOutlined,
ArrowRightOutlined,
StopOutlined,
HomeOutlined,
CameraOutlined,
RotateLeftOutlined,
RotateRightOutlined,
VerticalAlignTopOutlined,
VerticalAlignBottomOutlined,
DashboardOutlined,
CompassOutlined
} from '@ant-design/icons';
import { message } from 'antd';
import styles from './LeftControlPanel.less';
interface LeftControlPanelProps {
visible: boolean;
onClose: () => void;
device: any;
realtimeData: any;
}
const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
visible,
onClose,
device,
realtimeData
}) => {
const dockData = realtimeData?.rawData?.dockData;
// 模拟详细飞行数据 (Placeholder Data)
const flightData = {
pitch: -2.5,
roll: 0.1,
yaw: 125.4,
hSpeed: 0.0,
vSpeed: 0.0,
altitude: realtimeData?.gps?.altitude?.toFixed(1) || '0.0',
distance: 12.5, // 离家距离
homeAlt: 0,
satellites: dockData?.position_state?.gps_number || 12,
rtkStatus: 'FIX',
signal: 95,
rcSignal: 100
};
const handleControl = (action: string) => {
message.info(`发送指令: ${action}`);
};
return (
<div className={`${styles.leftPanel} ${visible ? styles.visible : ''}`}>
<div className={styles.header}>
<div className={styles.title}>
<VideoCameraOutlined />
<span>实时监控 / LIVE VIEW</span>
<span className={styles.liveTag}>LIVE</span>
</div>
<button className={styles.closeBtn} onClick={onClose}>
<CloseOutlined />
</button>
</div>
<div className={styles.videoContainer}>
<div className={styles.videoPlaceholder}>
<VideoCameraOutlined className={styles.icon} />
<span>等待图传信号...</span>
<span style={{fontSize: 12, marginTop: 8}}>{device?.deviceSn || '未选择设备'}</span>
</div>
<div className={styles.hudOverlay}>
<div className={styles.crosshair} />
<div style={{position: 'absolute', top: 10, left: 10, color: '#0f0', fontSize: 12, fontFamily: 'monospace'}}>
CAM: Main<br/>ISO: Auto<br/>EXP: 0.0
</div>
{/* HUD底部状态条 */}
<div style={{
position: 'absolute', bottom: 10, left: 10, right: 10,
display: 'flex', justifyContent: 'space-between',
color: '#fff', fontSize: 12, textShadow: '0 0 2px #000'
}}>
<span>H: {flightData.altitude}m</span>
<span>D: {flightData.distance}m</span>
<span>H.S: {flightData.hSpeed}m/s</span>
<span>V.S: {flightData.vSpeed}m/s</span>
</div>
</div>
</div>
{/* 飞行仪表盘区域 */}
<div className={styles.flightDashboard}>
<div className={styles.dashItem}>
<div className={styles.dashLabel}><CompassOutlined /> PITCH</div>
<div className={styles.dashValue}>{flightData.pitch}°</div>
</div>
<div className={styles.dashItem}>
<div className={styles.dashLabel}><CompassOutlined /> ROLL</div>
<div className={styles.dashValue}>{flightData.roll}°</div>
</div>
<div className={styles.dashItem}>
<div className={styles.dashLabel}><CompassOutlined /> YAW</div>
<div className={styles.dashValue}>{flightData.yaw}°</div>
</div>
<div className={styles.dashItem}>
<div className={styles.dashLabel}>RTK</div>
<div className={styles.dashValue} style={{color: '#00ff88'}}>{flightData.rtkStatus}</div>
</div>
<div className={styles.dashItem}>
<div className={styles.dashLabel}>SAT</div>
<div className={styles.dashValue}>{flightData.satellites}</div>
</div>
<div className={styles.dashItem}>
<div className={styles.dashLabel}>LINK</div>
<div className={styles.dashValue}>{flightData.signal}%</div>
</div>
</div>
<div className={styles.controlsContent}>
{/* 主要动作 */}
<div className={styles.controlGroup}>
<div className={styles.groupTitle}>快捷指令 / ACTIONS</div>
<div className={styles.flightActions}>
<button
onClick={() => handleControl('一键起飞')}
disabled={dockData?.mode_code === 1 || dockData?.drone_in_dock !== 1}
>
<RocketOutlined /> 一键起飞
</button>
<button onClick={() => handleControl('一键返航')}>
<HomeOutlined /> 一键返航
</button>
<button className={styles.danger} onClick={() => handleControl('紧急悬停')}>
<StopOutlined /> 紧急悬停
</button>
<button onClick={() => handleControl('拍照')}>
<CameraOutlined /> 拍照
</button>
</div>
</div>
{/* 飞行姿态控制 (模拟双摇杆) */}
<div className={styles.controlGroup}>
<div className={styles.groupTitle}>姿态控制 / ATTITUDE CONTROL</div>
<div className={styles.joystickArea}>
{/* 左手:升降 + 转向 */}
<div className={styles.joystickGroup}>
<div className={styles.joystickLabel}>升降 & 偏航 (Left)</div>
<div className={styles.dpad}>
<button className={styles.up} onClick={() => handleControl('上升')} title="上升"><VerticalAlignTopOutlined /></button>
<button className={styles.left} onClick={() => handleControl('左转')} title="左转"><RotateLeftOutlined /></button>
<button className={styles.right} onClick={() => handleControl('右转')} title="右转"><RotateRightOutlined /></button>
<button className={styles.down} onClick={() => handleControl('下降')} title="下降"><VerticalAlignBottomOutlined /></button>
</div>
</div>
{/* 右手:前后 + 左右 */}
<div className={styles.joystickGroup}>
<div className={styles.joystickLabel}>水平移动 (Right)</div>
<div className={styles.dpad}>
<button className={styles.up} onClick={() => handleControl('前进')} title="前进"><ArrowUpOutlined /></button>
<button className={styles.left} onClick={() => handleControl('向左飞')} title="向左"><ArrowLeftOutlined /></button>
<button className={styles.right} onClick={() => handleControl('向右飞')} title="向右"><ArrowRightOutlined /></button>
<button className={styles.down} onClick={() => handleControl('后退')} title="后退"><ArrowDownOutlined /></button>
</div>
</div>
</div>
</div>
{/* 云台控制 */}
<div className={styles.controlGroup}>
<div className={styles.groupTitle}>云台控制 / GIMBAL</div>
<div className={styles.joystickArea}>
<div className={styles.joystickGroup} style={{flex: 1}}>
<div className={styles.joystickLabel}>云台方向</div>
<div className={styles.dpad}>
<button className={styles.up} onClick={() => handleControl('云台向上')}><ArrowUpOutlined /></button>
<button className={styles.left} onClick={() => handleControl('云台向左')}><ArrowLeftOutlined /></button>
<button className={styles.right} onClick={() => handleControl('云台向右')}><ArrowRightOutlined /></button>
<button className={styles.down} onClick={() => handleControl('云台向下')}><ArrowDownOutlined /></button>
</div>
</div>
</div>
</div>
</div>
</div>
);
};
export default LeftControlPanel;
@@ -0,0 +1,296 @@
@import '~antd/lib/style/themes/default.less';
@cyan: #00f0ff;
@neon-green: #00ff88;
@neon-orange: #ffaa00;
@neon-red: #ff4d4f;
@bg-dark: rgba(10, 20, 30, 0.95);
@border-color: rgba(0, 240, 255, 0.3);
.rightPanel {
position: absolute;
top: 64px;
right: 0;
bottom: 0;
width: 420px; // 稍微加宽一点
background: linear-gradient(
135deg,
rgba(6, 12, 20, 0.98) 0%,
rgba(10, 25, 40, 0.95) 100%
);
backdrop-filter: blur(10px);
z-index: 1000;
display: flex;
flex-direction: column;
transform: translateX(100%);
transition: transform 0.4s cubic-bezier(0.16, 1, 0.3, 1);
border-left: 1px solid @border-color;
box-shadow: -10px 0 30px rgba(0, 0, 0, 0.5);
&.visible {
transform: translateX(0);
}
.header {
flex-shrink: 0;
padding: 20px 24px 16px;
border-bottom: 1px solid rgba(0, 240, 255, 0.1);
background: rgba(0, 20, 40, 0.3);
.titleRow {
display: flex;
justify-content: space-between;
align-items: flex-start;
.titleInfo {
flex: 1;
.mainTitle {
font-size: 20px;
font-weight: 700;
color: #fff;
text-shadow: 0 0 10px rgba(0, 240, 255, 0.5);
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 4px;
.icon { color: @cyan; }
}
.subTitle {
font-size: 12px;
color: rgba(0, 240, 255, 0.6);
font-family: 'Consolas', monospace;
}
}
.closeBtn {
width: 32px;
height: 32px;
display: flex;
align-items: center;
justify-content: center;
border: 1px solid rgba(255, 255, 255, 0.1);
background: rgba(255, 255, 255, 0.05);
color: rgba(255, 255, 255, 0.6);
cursor: pointer;
transition: all 0.3s;
&:hover {
background: rgba(255, 50, 50, 0.2);
border-color: rgba(255, 50, 50, 0.5);
color: @neon-red;
}
}
}
}
.deviceList {
flex-shrink: 0;
padding: 12px 24px;
background: rgba(0, 10, 20, 0.3);
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
.scrollContainer {
display: flex;
gap: 12px;
overflow-x: auto;
padding-bottom: 8px;
&::-webkit-scrollbar { height: 4px; }
&::-webkit-scrollbar-thumb { background: rgba(0, 240, 255, 0.2); border-radius: 2px; }
.deviceItem {
flex-shrink: 0;
width: 140px;
padding: 10px;
background: rgba(0, 240, 255, 0.05);
border: 1px solid rgba(0, 240, 255, 0.1);
cursor: pointer;
transition: all 0.3s;
position: relative;
&:hover { background: rgba(0, 240, 255, 0.1); }
&.active {
background: linear-gradient(135deg, rgba(0, 240, 255, 0.15), rgba(0, 100, 255, 0.1));
border-color: @cyan;
box-shadow: 0 0 15px rgba(0, 240, 255, 0.1);
.name { color: @cyan; font-weight: 600; }
}
.iconWrapper {
display: flex;
justify-content: space-between;
margin-bottom: 6px;
.icon { font-size: 16px; color: rgba(255, 255, 255, 0.6); }
.statusDot {
width: 8px; height: 8px; border-radius: 50%; background: #444;
&.online { background: @neon-green; box-shadow: 0 0 8px @neon-green; }
}
}
.name {
font-size: 12px;
color: rgba(255, 255, 255, 0.8);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
}
}
}
.content {
flex: 1;
overflow-y: auto;
.customTabs {
color: #fff;
:global {
.ant-tabs-nav {
margin-bottom: 0;
padding: 0 24px;
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
.ant-tabs-tab {
color: rgba(255, 255, 255, 0.4);
padding: 16px 0;
margin-right: 24px;
transition: all 0.3s;
&:hover { color: @cyan; }
}
.ant-tabs-tab-active .ant-tabs-tab-btn {
color: @cyan;
font-weight: 600;
text-shadow: none !important;
}
.ant-tabs-ink-bar {
background: @cyan;
height: 3px;
box-shadow: 0 0 10px @cyan;
}
}
.ant-tabs-content-holder {
padding: 24px;
}
}
}
.detailContainer {
// 核心状态卡片
.statusCard {
background: rgba(255,255,255,0.03);
border: 1px solid rgba(255,255,255,0.1);
padding: 16px;
border-radius: 4px;
margin-bottom: 24px;
.statusHeader {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 16px;
.statusTitle { color: rgba(255,255,255,0.6); font-size: 12px; letter-spacing: 1px; }
.statusTag {
font-size: 12px; font-weight: bold; padding: 2px 8px; border-radius: 2px;
&.success { background: rgba(0,255,136,0.2); color: @neon-green; }
&.error { background: rgba(255,77,79,0.2); color: @neon-red; }
}
}
.mainStatusGrid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 16px;
.mainStatusItem {
.label { font-size: 12px; color: rgba(255,255,255,0.4); margin-bottom: 4px; }
.value { font-size: 18px; color: #fff; font-weight: bold; margin-bottom: 4px; display: flex; align-items: center; gap: 8px; }
:global(.ant-progress-inner) { background-color: rgba(255,255,255,0.1); }
}
}
}
.section {
margin-bottom: 24px;
.sectionHeader {
font-size: 12px;
color: rgba(255, 255, 255, 0.4);
margin-bottom: 12px;
padding-left: 8px;
border-left: 2px solid @cyan;
text-transform: uppercase;
letter-spacing: 1px;
}
.grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.hudItem {
background: rgba(255, 255, 255, 0.03);
padding: 10px 12px;
border: 1px solid rgba(255, 255, 255, 0.05);
display: flex;
flex-direction: column;
justify-content: center;
.label { font-size: 12px; color: rgba(255, 255, 255, 0.4); margin-bottom: 2px; }
.value {
font-size: 14px;
color: rgba(255, 255, 255, 0.9);
font-family: 'Consolas', monospace;
font-weight: 500;
.unit { font-size: 12px; color: rgba(255, 255, 255, 0.3); margin-left: 4px; }
&.warning { color: @neon-orange; }
&.error { color: @neon-red; }
&.success { color: @neon-green; }
}
}
}
.actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
margin-top: 32px;
button {
padding: 12px;
background: rgba(0, 240, 255, 0.1);
border: 1px solid rgba(0, 240, 255, 0.3);
color: @cyan;
font-weight: 600;
cursor: pointer;
transition: all 0.3s;
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
&:hover:not(:disabled) {
background: rgba(0, 240, 255, 0.2);
box-shadow: 0 0 15px rgba(0, 240, 255, 0.2);
transform: translateY(-2px);
}
&:disabled { opacity: 0.5; cursor: not-allowed; filter: grayscale(1); }
&.primary {
background: rgba(0, 240, 255, 0.2);
border-color: @cyan;
color: #fff;
text-shadow: none;
&:hover:not(:disabled) { background: rgba(0, 240, 255, 0.4); }
}
}
}
}
}
}
@@ -0,0 +1,255 @@
import React, { useState, useEffect } from 'react';
import { Spin, Empty, message, Tooltip, Tabs, Progress } from 'antd';
import {
CloseOutlined,
EnvironmentOutlined,
RocketOutlined,
VideoCameraOutlined,
HomeOutlined,
ThunderboltOutlined,
DashboardOutlined,
SignalFilled,
} from '@ant-design/icons';
import { deviceApi } from '@/services/device';
import { ordersApi } from '@/services/orders';
import useDeviceSSE from '../hooks/useDeviceSSE';
import styles from './RightPanel.less';
const { TabPane } = Tabs;
interface RightPanelProps {
visible: boolean;
tourism: any;
onClose: () => void;
onControlClick: (device: any, realtimeData: any) => void;
}
const RightPanel: React.FC<RightPanelProps> = ({
visible,
tourism,
onClose,
onControlClick
}) => {
const [deviceList, setDeviceList] = useState<any[]>([]);
const [selectedDeviceSn, setSelectedDeviceSn] = useState<string>('');
const [loading, setLoading] = useState(false);
const { realtimeData, sseConnected, connectSSE, disconnectSSE } = useDeviceSSE();
const fetchDeviceList = async (tourismId: number) => {
setLoading(true);
try {
const deviceSns = await ordersApi.getDeviceSnsByTourismId(tourismId);
if (!deviceSns || deviceSns.length === 0) {
setDeviceList([]);
return;
}
const promises = deviceSns.map((sn: string) =>
deviceApi.deviceList({ page: 1, limit: 1, deviceSn: sn })
);
const results = await Promise.all(promises);
const devices = results
.map((res: any) => (res.data && res.data.length > 0 ? res.data[0] : null))
.filter((device: any) => device !== null);
setDeviceList(devices);
if (devices.length > 0) setSelectedDeviceSn(devices[0].deviceSn || '');
} catch (error) {
console.error(error);
message.error('获取设备列表失败');
} finally {
setLoading(false);
}
};
useEffect(() => {
if (visible && tourism?.id) fetchDeviceList(tourism.id);
else { setDeviceList([]); setSelectedDeviceSn(''); }
}, [visible, tourism?.id]);
useEffect(() => {
if (selectedDeviceSn && visible) connectSSE(selectedDeviceSn);
return () => { if (selectedDeviceSn) disconnectSSE(selectedDeviceSn); };
}, [selectedDeviceSn, visible]);
useEffect(() => {
if (!visible && selectedDeviceSn) disconnectSSE(selectedDeviceSn);
}, [visible]);
const handleDeviceSelect = (deviceSn: string) => {
if (deviceSn !== selectedDeviceSn) setSelectedDeviceSn(deviceSn);
};
const selectedDevice = deviceList.find((d) => d.deviceSn === selectedDeviceSn);
const dockData = realtimeData?.rawData?.dockData;
const battery = realtimeData?.battery ?? 0;
const formatValue = (val: any, unit: string = '') => (val !== undefined && val !== null ? `${val}${unit}` : '-');
const renderItem = (label: string, value: any, unit: string = '', status: 'normal'|'warning'|'error'|'success' = 'normal') => (
<div className={styles.hudItem}>
<div className={styles.label}>{label}</div>
<div className={`${styles.value} ${styles[status]}`}>
{value !== undefined && value !== null ? value : '-'}
<span className={styles.unit}>{unit}</span>
</div>
</div>
);
return (
<div className={`${styles.rightPanel} ${visible ? styles.visible : ''}`}>
<div className={styles.header}>
<div className={styles.titleRow}>
<div className={styles.titleInfo}>
<div className={styles.mainTitle}>
<EnvironmentOutlined className={styles.icon} />
{tourism?.tourismName || '景区详情'}
</div>
<div className={styles.subTitle}>{deviceList.length} DEVICES ONLINE</div>
</div>
<button className={styles.closeBtn} onClick={onClose}><CloseOutlined /></button>
</div>
</div>
{deviceList.length > 0 && (
<div className={styles.deviceList}>
<div className={styles.scrollContainer}>
{deviceList.map((device) => {
const isSelected = device.deviceSn === selectedDeviceSn;
const isDeviceOnline = realtimeData?.deviceSn === device.deviceSn && realtimeData?.online;
return (
<div
key={device.deviceSn}
className={`${styles.deviceItem} ${isSelected ? styles.active : ''}`}
onClick={() => handleDeviceSelect(device.deviceSn)}
>
<div className={styles.iconWrapper}>
<HomeOutlined className={styles.icon} />
<Tooltip title={isDeviceOnline ? '在线' : '离线'}>
<div className={`${styles.statusDot} ${isDeviceOnline ? styles.online : ''}`} />
</Tooltip>
</div>
<div className={styles.name}>{device.deviceName || device.deviceSn}</div>
</div>
);
})}
</div>
</div>
)}
<div className={styles.content}>
<Spin spinning={loading}>
{!selectedDevice ? (
<Empty description="暂无设备数据" image={Empty.PRESENTED_IMAGE_SIMPLE} />
) : (
<Tabs defaultActiveKey="1" className={styles.customTabs}>
{/* Tab 1: 综合状态 (对齐2D: 机库信息 + 无人机信息) */}
<TabPane tab={<span><DashboardOutlined />综合状态</span>} key="1">
<div className={styles.detailContainer}>
{/* Block A: 机库信息 */}
<div className={styles.section}>
<div className={styles.sectionHeader}>机库信息 / DOCK INFO</div>
{/* 状态卡片 */}
<div className={styles.statusCard}>
<div className={styles.statusHeader}>
<span className={styles.statusTitle}>{selectedDevice?.deviceName || selectedDevice?.deviceSn}</span>
<span className={`${styles.statusTag} ${realtimeData?.online ? styles.success : styles.error}`}>
{realtimeData?.online ? '在线' : '离线'}
</span>
</div>
<div className={styles.grid}>
{renderItem('机库SN', selectedDevice?.deviceSn)}
{renderItem('运行模式', dockData?.mode_code === 1 ? '工作' : '待机', '', dockData?.mode_code === 1 ? 'warning' : 'success')}
{renderItem('舱门', dockData?.cover_state === 1 ? '开启' : '关闭')}
{renderItem('告警', dockData?.alarm_state === 1 ? '告警' : '正常', '', dockData?.alarm_state === 1 ? 'error' : 'success')}
{renderItem('急停', dockData?.emergency_stop_state === 1 ? '触发' : '正常', '', dockData?.emergency_stop_state === 1 ? 'error' : 'success')}
{renderItem('推杆', dockData?.putter_state === 1 ? '展开' : '收起')}
</div>
</div>
</div>
{/* Block B: 无人机信息 */}
<div className={styles.section}>
<div className={styles.sectionHeader}>无人机信息 / DRONE INFO</div>
<div className={styles.grid}>
{renderItem('无人机SN', dockData?.sub_device?.device_sn || '--')}
{renderItem('连接状态', dockData?.sub_device?.device_online_status === 1 ? '在线' : '离线', '', dockData?.sub_device?.device_online_status === 1 ? 'success' : 'normal')}
{renderItem('在库状态', dockData?.drone_in_dock === 1 ? '在库' : '外出', '', dockData?.drone_in_dock === 1 ? 'success' : 'warning')}
{renderItem('对频状态', dockData?.sub_device?.device_paired === 1 ? '已对频' : '未对频')}
{renderItem('RTK卫星', dockData?.position_state?.rtk_number, '颗')}
{renderItem('定位状态', dockData?.position_state?.is_fixed === 2 ? '固定解' : '非固定', '', dockData?.position_state?.is_fixed === 2 ? 'success' : 'warning')}
{renderItem('网络信号', dockData?.network_state?.type === 2 ? '4G' : 'WiFi')}
{renderItem('网络质量', dockData?.network_state?.quality, '/5')}
</div>
</div>
{/* 操作区 */}
<div className={styles.actions}>
<button className={styles.primary} onClick={() => onControlClick(selectedDevice, realtimeData)}>
<VideoCameraOutlined /> 进入操控台
</button>
<button disabled={dockData?.mode_code === 1 || dockData?.drone_in_dock !== 1} onClick={() => message.info('一键起飞指令发送')}>
<RocketOutlined /> 一键起飞
</button>
</div>
</div>
</TabPane>
{/* Tab 2: 详细状态 (对齐2D: 机库环境电气 + 无人机详细状态) */}
<TabPane tab={<span><ThunderboltOutlined />详细状态</span>} key="2">
<div className={styles.detailContainer}>
{/* Block A: 机库环境与电气 */}
<div className={styles.section}>
<div className={styles.sectionHeader}>机库环境与电气 / DOCK ENV & POWER</div>
<div className={styles.grid}>
{renderItem('环境温度', dockData?.environment_temperature, '°C')}
{renderItem('机库温度', dockData?.temperature, '°C')}
{renderItem('环境湿度', dockData?.humidity, '%')}
{renderItem('风速', dockData?.wind_speed, 'm/s')}
{renderItem('降雨量', dockData?.rainfall, 'mm')}
{renderItem('累计运行', formatValue(Math.floor((dockData?.acc_time ?? 0) / 3600), 'h'))}
{renderItem('供电电压', dockData?.electric_supply_voltage, 'V')}
{renderItem('输入功率', formatValue(dockData?.acdc_power_input, 'W'))}
{renderItem('工作电流', formatValue((dockData?.working_current ?? 0) / 1000, 'A'))}
{renderItem('备电电压', formatValue((dockData?.backup_battery?.voltage ?? 0) / 1000, 'V'))}
</div>
</div>
{/* Block B: 无人机详细状态 */}
<div className={styles.section}>
<div className={styles.sectionHeader}>无人机详细状态 / DRONE DETAIL</div>
{/* 电池大图标 */}
<div style={{display:'flex', alignItems:'center', marginBottom: 16, background:'rgba(255,255,255,0.05)', padding:12, borderRadius:4}}>
<div style={{marginRight:16}}>
<div style={{fontSize:12, color:'rgba(255,255,255,0.6)'}}>BATTERY</div>
<div style={{fontSize:24, fontWeight:'bold', color:battery<20?'#ff4d4f':'#00ff88'}}>{battery}%</div>
</div>
<div style={{flex:1}}>
<Progress percent={battery} showInfo={false} strokeColor={battery<20?'#ff4d4f':'#00ff88'} trailColor="rgba(255,255,255,0.1)" />
</div>
</div>
<div className={styles.grid}>
{renderItem('电池电压', formatValue((dockData?.drone_battery_maintenance_info?.batteries?.[0]?.voltage ?? 0) / 1000, 'V'))}
{renderItem('电池温度', realtimeData?.temperature, '°C')}
{renderItem('充电状态', dockData?.drone_charge_state?.state === 1 ? '充电中' : '未充电')}
{renderItem('加热状态', dockData?.drone_battery_maintenance_info?.heat_state === 1 ? '加热中' : '未加热')}
{renderItem('维护状态', dockData?.drone_battery_maintenance_info?.maintenance_state === 1 ? '维护中' : '正常')}
{renderItem('存储模式', dockData?.battery_store_mode === 1 ? '计划模式' : '普通')}
</div>
</div>
</div>
</TabPane>
</Tabs>
)}
</Spin>
</div>
</div>
);
};
export default RightPanel;
@@ -0,0 +1,275 @@
// 3D科技风格底部面板
.bottomPanel {
position: absolute;
left: 20px;
right: 20px;
bottom: 20px;
background: linear-gradient(
135deg,
rgba(10, 20, 40, 0.92) 0%,
rgba(20, 40, 70, 0.88) 50%,
rgba(10, 30, 50, 0.92) 100%
);
backdrop-filter: blur(20px);
border: 1px solid rgba(0, 200, 255, 0.3);
border-radius: 16px;
box-shadow:
0 0 30px rgba(0, 150, 255, 0.2),
0 0 60px rgba(0, 100, 200, 0.1),
inset 0 1px 0 rgba(255, 255, 255, 0.1);
z-index: 1000;
transform: translateY(calc(100% + 40px));
opacity: 0;
transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
max-height: 280px;
overflow: hidden;
// 顶部发光线条
&::before {
content: '';
position: absolute;
top: 0;
left: 20px;
right: 20px;
height: 2px;
background: linear-gradient(
90deg,
transparent 0%,
rgba(0, 200, 255, 0.8) 20%,
rgba(100, 220, 255, 1) 50%,
rgba(0, 200, 255, 0.8) 80%,
transparent 100%
);
border-radius: 2px;
box-shadow: 0 0 10px rgba(0, 200, 255, 0.8);
}
&.visible {
transform: translateY(0);
opacity: 1;
}
&.expanded {
max-height: 500px;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 16px 20px 12px;
border-bottom: 1px solid rgba(0, 200, 255, 0.15);
.headerLeft {
display: flex;
align-items: center;
gap: 12px;
.tourismIcon {
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
background: linear-gradient(135deg, rgba(0, 150, 255, 0.3), rgba(0, 200, 255, 0.1));
border: 1px solid rgba(0, 200, 255, 0.4);
border-radius: 10px;
color: #00d4ff;
font-size: 18px;
box-shadow: 0 0 15px rgba(0, 200, 255, 0.3);
}
.tourismInfo {
.tourismName {
font-size: 16px;
font-weight: 600;
color: #fff;
text-shadow: 0 0 10px rgba(255, 255, 255, 0.3);
letter-spacing: 1px;
}
.deviceCount {
font-size: 12px;
color: rgba(0, 200, 255, 0.8);
margin-top: 2px;
}
}
}
.headerRight {
display: flex;
align-items: center;
gap: 8px;
.iconBtn {
display: flex;
align-items: center;
justify-content: center;
width: 36px;
height: 36px;
border: 1px solid rgba(0, 200, 255, 0.3);
background: rgba(0, 150, 255, 0.1);
border-radius: 8px;
cursor: pointer;
color: #00d4ff;
transition: all 0.3s;
&:hover {
background: rgba(0, 200, 255, 0.2);
border-color: rgba(0, 200, 255, 0.6);
box-shadow: 0 0 15px rgba(0, 200, 255, 0.4);
transform: scale(1.05);
}
&.closeBtn:hover {
background: rgba(255, 80, 80, 0.2);
border-color: rgba(255, 80, 80, 0.6);
color: #ff6b6b;
box-shadow: 0 0 15px rgba(255, 80, 80, 0.4);
}
}
}
}
.deviceTabs {
display: flex;
gap: 10px;
padding: 12px 20px;
overflow-x: auto;
border-bottom: 1px solid rgba(0, 200, 255, 0.1);
&::-webkit-scrollbar {
height: 4px;
}
&::-webkit-scrollbar-track {
background: rgba(0, 100, 150, 0.2);
border-radius: 2px;
}
&::-webkit-scrollbar-thumb {
background: rgba(0, 200, 255, 0.4);
border-radius: 2px;
}
.deviceTab {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 16px;
background: rgba(0, 100, 150, 0.2);
border: 1px solid rgba(0, 200, 255, 0.2);
border-radius: 25px;
cursor: pointer;
white-space: nowrap;
transition: all 0.3s;
&:hover {
background: rgba(0, 150, 200, 0.3);
border-color: rgba(0, 200, 255, 0.4);
}
&.selected {
background: linear-gradient(135deg, rgba(0, 150, 255, 0.4), rgba(0, 200, 255, 0.2));
border-color: rgba(0, 200, 255, 0.8);
box-shadow:
0 0 20px rgba(0, 200, 255, 0.3),
inset 0 0 10px rgba(0, 200, 255, 0.1);
}
.statusDot {
width: 10px;
height: 10px;
border-radius: 50%;
background: #666;
transition: all 0.3s;
box-shadow: 0 0 5px rgba(100, 100, 100, 0.5);
&.online {
background: #00ff88;
box-shadow: 0 0 10px rgba(0, 255, 136, 0.8);
animation: pulse 2s infinite;
}
}
.deviceName {
font-size: 13px;
color: #e0f0ff;
font-weight: 500;
}
}
}
.content {
padding: 16px 20px;
overflow-y: auto;
max-height: calc(100% - 130px);
&::-webkit-scrollbar {
width: 4px;
}
&::-webkit-scrollbar-track {
background: rgba(0, 100, 150, 0.2);
border-radius: 2px;
}
&::-webkit-scrollbar-thumb {
background: rgba(0, 200, 255, 0.4);
border-radius: 2px;
}
:global(.ant-empty-description) {
color: rgba(255, 255, 255, 0.5);
}
:global(.ant-spin-dot-item) {
background-color: #00d4ff;
}
}
}
// 脉冲动画
@keyframes pulse {
0% {
box-shadow: 0 0 5px rgba(0, 255, 136, 0.8);
}
50% {
box-shadow: 0 0 15px rgba(0, 255, 136, 1), 0 0 25px rgba(0, 255, 136, 0.5);
}
100% {
box-shadow: 0 0 5px rgba(0, 255, 136, 0.8);
}
}
// 响应式
@media (max-width: 768px) {
.bottomPanel {
left: 10px;
right: 10px;
bottom: 10px;
border-radius: 12px;
.header {
padding: 12px 16px 10px;
.tourismIcon {
width: 36px;
height: 36px;
font-size: 16px;
}
.tourismName {
font-size: 14px;
}
}
.deviceTabs {
padding: 10px 16px;
}
.content {
padding: 12px 16px;
}
}
}
@@ -0,0 +1,231 @@
import React, { useState, useEffect } from 'react';
import { Spin, Empty, message, Modal } from 'antd';
import {
CloseOutlined,
ExpandAltOutlined,
CompressOutlined,
EnvironmentOutlined,
RocketOutlined,
VideoCameraOutlined,
} from '@ant-design/icons';
import { deviceApi } from '@/services/device';
import { ordersApi } from '@/services/orders';
import useDeviceSSE from '../hooks/useDeviceSSE';
import DeviceInfo from '../DeviceInfo';
import styles from './index.less';
interface BottomPanelProps {
visible: boolean;
tourism: any;
onClose: () => void;
}
const BottomPanel: React.FC<BottomPanelProps> = ({ visible, tourism, onClose }) => {
const [expanded, setExpanded] = useState(false);
const [deviceList, setDeviceList] = useState<any[]>([]);
const [selectedDeviceSn, setSelectedDeviceSn] = useState<string>('');
const [loading, setLoading] = useState(false);
const [droneControlVisible, setDroneControlVisible] = useState(false);
const { realtimeData, sseConnected, connectSSE, disconnectSSE } = useDeviceSSE();
// 获取设备列表
const fetchDeviceList = async (tourismId: number) => {
setLoading(true);
try {
// 获取设备SN列表
const deviceSns = await ordersApi.getDeviceSnsByTourismId(tourismId);
if (!deviceSns || deviceSns.length === 0) {
setDeviceList([]);
return;
}
// 批量查询设备详情
const promises = deviceSns.map((sn: string) =>
deviceApi.deviceList({ page: 1, limit: 1, deviceSn: sn })
);
const results = await Promise.all(promises);
const devices = results
.map((res: any) => (res.data && res.data.length > 0 ? res.data[0] : null))
.filter((device: any) => device !== null);
setDeviceList(devices);
// 默认选中第一个设备
if (devices.length > 0) {
setSelectedDeviceSn(devices[0].deviceSn || '');
}
} catch (error) {
console.error('获取设备列表失败:', error);
message.error('获取设备列表失败');
} finally {
setLoading(false);
}
};
// 景区变化时,重新获取设备列表
useEffect(() => {
if (visible && tourism?.id) {
fetchDeviceList(tourism.id);
} else {
setDeviceList([]);
setSelectedDeviceSn('');
setExpanded(false);
}
}, [visible, tourism?.id]);
// 选中设备变化时,连接SSE
useEffect(() => {
if (selectedDeviceSn && visible) {
connectSSE(selectedDeviceSn);
}
return () => {
if (selectedDeviceSn) {
disconnectSSE(selectedDeviceSn);
}
};
}, [selectedDeviceSn, visible]);
// 面板关闭时断开SSE
useEffect(() => {
if (!visible && selectedDeviceSn) {
disconnectSSE(selectedDeviceSn);
}
}, [visible]);
// 处理设备选择
const handleDeviceSelect = (deviceSn: string) => {
if (deviceSn !== selectedDeviceSn) {
setSelectedDeviceSn(deviceSn);
}
};
// 处理一键起飞
const handleTakeoff = () => {
const dockData = realtimeData?.rawData?.dockData;
if (dockData?.mode_code === 1) {
message.warning('机库正在执行任务,无法起飞');
return;
}
if (dockData?.drone_in_dock !== 1) {
message.warning('无人机不在库,无法起飞');
return;
}
message.info('一键起飞功能开发中');
};
// 获取选中设备
const selectedDevice = deviceList.find((d) => d.deviceSn === selectedDeviceSn);
return (
<>
<div className={`${styles.bottomPanel} ${visible ? styles.visible : ''} ${expanded ? styles.expanded : ''}`}>
{/* 头部 */}
<div className={styles.header}>
<div className={styles.headerLeft}>
<div className={styles.tourismIcon}>
<EnvironmentOutlined />
</div>
<div className={styles.tourismInfo}>
<div className={styles.tourismName}>{tourism?.tourismName || '景区'}</div>
<div className={styles.deviceCount}>{deviceList.length} 个设备在线</div>
</div>
</div>
<div className={styles.headerRight}>
<button
className={styles.iconBtn}
onClick={() => setExpanded(!expanded)}
title={expanded ? '收起' : '展开'}
>
{expanded ? <CompressOutlined /> : <ExpandAltOutlined />}
</button>
<button
className={`${styles.iconBtn} ${styles.closeBtn}`}
onClick={onClose}
title="关闭"
>
<CloseOutlined />
</button>
</div>
</div>
{/* 设备列表 */}
<div className={styles.deviceTabs}>
{deviceList.length === 0 && !loading && (
<div style={{ color: 'rgba(255,255,255,0.5)', fontSize: 13 }}>暂无设备</div>
)}
{deviceList.map((device) => {
const isSelected = device.deviceSn === selectedDeviceSn;
const isOnline = realtimeData?.deviceSn === device.deviceSn && realtimeData?.online;
return (
<div
key={device.deviceSn}
className={`${styles.deviceTab} ${isSelected ? styles.selected : ''}`}
onClick={() => handleDeviceSelect(device.deviceSn)}
>
<span className={`${styles.statusDot} ${isOnline ? styles.online : ''}`} />
<span className={styles.deviceName}>{device.deviceName || device.deviceSn}</span>
</div>
);
})}
</div>
{/* 内容区 */}
<div className={styles.content}>
<Spin spinning={loading}>
{deviceList.length === 0 ? (
<Empty
description="该景区暂无设备"
image={Empty.PRESENTED_IMAGE_SIMPLE}
/>
) : selectedDevice ? (
<DeviceInfo
device={selectedDevice}
realtimeData={realtimeData}
sseConnected={sseConnected}
expanded={expanded}
onTakeoff={handleTakeoff}
onControl={() => setDroneControlVisible(true)}
/>
) : null}
</Spin>
</div>
</div>
{/* 无人机操控弹窗 */}
<Modal
title={
<span style={{ color: '#00d4ff' }}>
<RocketOutlined style={{ marginRight: 8 }} />
无人机操控台 - {realtimeData?.rawData?.dockData?.sub_device?.device_sn || '--'}
</span>
}
open={droneControlVisible}
onCancel={() => setDroneControlVisible(false)}
width={1000}
footer={null}
destroyOnClose
styles={{
content: {
background: 'linear-gradient(135deg, rgba(10, 20, 40, 0.98), rgba(20, 40, 70, 0.95))',
border: '1px solid rgba(0, 200, 255, 0.3)',
},
header: {
background: 'transparent',
borderBottom: '1px solid rgba(0, 200, 255, 0.2)',
},
}}
>
<div style={{ textAlign: 'center', padding: '60px 0' }}>
<VideoCameraOutlined style={{ fontSize: 64, color: 'rgba(0, 200, 255, 0.5)' }} />
<p style={{ marginTop: 16, color: 'rgba(255, 255, 255, 0.6)' }}>无人机操控功能开发中...</p>
</div>
</Modal>
</>
);
};
export default BottomPanel;
@@ -0,0 +1,331 @@
// 3D科技风格设备信息
.compactView {
.statusRow {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
flex-wrap: wrap;
.statusGroup {
display: flex;
align-items: center;
gap: 20px;
flex-wrap: wrap;
}
.statusItem {
display: flex;
align-items: center;
gap: 8px;
.statusIcon {
width: 32px;
height: 32px;
display: flex;
align-items: center;
justify-content: center;
background: rgba(0, 150, 255, 0.15);
border: 1px solid rgba(0, 200, 255, 0.3);
border-radius: 8px;
color: #00d4ff;
font-size: 14px;
}
.statusInfo {
.statusLabel {
font-size: 11px;
color: rgba(255, 255, 255, 0.5);
text-transform: uppercase;
letter-spacing: 0.5px;
}
.statusValue {
font-size: 14px;
font-weight: 600;
color: #fff;
&.online {
color: #00ff88;
text-shadow: 0 0 8px rgba(0, 255, 136, 0.5);
}
&.offline {
color: #888;
}
&.warning {
color: #ffaa00;
text-shadow: 0 0 8px rgba(255, 170, 0, 0.5);
}
}
}
}
.batteryItem {
display: flex;
align-items: center;
gap: 10px;
padding: 8px 16px;
background: linear-gradient(135deg, rgba(0, 100, 50, 0.3), rgba(0, 150, 100, 0.15));
border: 1px solid rgba(0, 255, 136, 0.3);
border-radius: 20px;
.batteryIcon {
font-size: 18px;
}
.batteryText {
font-size: 16px;
font-weight: bold;
font-family: 'Courier New', monospace;
}
&.high {
border-color: rgba(0, 255, 136, 0.5);
.batteryIcon, .batteryText {
color: #00ff88;
text-shadow: 0 0 10px rgba(0, 255, 136, 0.6);
}
}
&.medium {
background: linear-gradient(135deg, rgba(100, 80, 0, 0.3), rgba(150, 120, 0, 0.15));
border-color: rgba(255, 200, 0, 0.5);
.batteryIcon, .batteryText {
color: #ffcc00;
text-shadow: 0 0 10px rgba(255, 200, 0, 0.6);
}
}
&.low {
background: linear-gradient(135deg, rgba(100, 30, 30, 0.3), rgba(150, 50, 50, 0.15));
border-color: rgba(255, 80, 80, 0.5);
.batteryIcon, .batteryText {
color: #ff5555;
text-shadow: 0 0 10px rgba(255, 80, 80, 0.6);
}
}
}
.actionButtons {
display: flex;
gap: 10px;
.actionBtn {
display: flex;
align-items: center;
gap: 6px;
padding: 8px 20px;
border: 1px solid rgba(0, 200, 255, 0.4);
border-radius: 20px;
background: linear-gradient(135deg, rgba(0, 150, 255, 0.2), rgba(0, 100, 200, 0.1));
color: #00d4ff;
font-size: 13px;
font-weight: 500;
cursor: pointer;
transition: all 0.3s;
&:hover:not(:disabled) {
background: linear-gradient(135deg, rgba(0, 200, 255, 0.4), rgba(0, 150, 255, 0.2));
border-color: rgba(0, 200, 255, 0.8);
box-shadow: 0 0 20px rgba(0, 200, 255, 0.4);
transform: translateY(-2px);
}
&:disabled {
opacity: 0.4;
cursor: not-allowed;
}
&.primary {
background: linear-gradient(135deg, rgba(0, 200, 100, 0.3), rgba(0, 150, 80, 0.2));
border-color: rgba(0, 255, 136, 0.5);
color: #00ff88;
&:hover:not(:disabled) {
background: linear-gradient(135deg, rgba(0, 255, 136, 0.4), rgba(0, 200, 100, 0.3));
border-color: rgba(0, 255, 136, 0.8);
box-shadow: 0 0 20px rgba(0, 255, 136, 0.4);
}
}
}
}
}
}
.expandedView {
.dataGrid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 16px;
margin-bottom: 16px;
@media (max-width: 900px) {
grid-template-columns: repeat(2, 1fr);
}
@media (max-width: 600px) {
grid-template-columns: 1fr;
}
}
.dataCard {
background: linear-gradient(135deg, rgba(0, 100, 150, 0.2), rgba(0, 80, 120, 0.1));
border: 1px solid rgba(0, 200, 255, 0.2);
border-radius: 12px;
padding: 14px;
transition: all 0.3s;
&:hover {
border-color: rgba(0, 200, 255, 0.4);
box-shadow: 0 0 15px rgba(0, 200, 255, 0.15);
}
.cardHeader {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 12px;
padding-bottom: 8px;
border-bottom: 1px solid rgba(0, 200, 255, 0.15);
.cardIcon {
width: 28px;
height: 28px;
display: flex;
align-items: center;
justify-content: center;
background: rgba(0, 200, 255, 0.15);
border-radius: 6px;
color: #00d4ff;
font-size: 14px;
}
.cardTitle {
font-size: 13px;
font-weight: 600;
color: rgba(255, 255, 255, 0.9);
letter-spacing: 0.5px;
}
}
.cardContent {
.dataRow {
display: flex;
justify-content: space-between;
align-items: center;
padding: 6px 0;
&:not(:last-child) {
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
}
.dataLabel {
font-size: 12px;
color: rgba(255, 255, 255, 0.5);
}
.dataValue {
font-size: 13px;
color: #fff;
font-weight: 500;
font-family: 'Courier New', monospace;
&.success {
color: #00ff88;
}
&.warning {
color: #ffcc00;
}
&.error {
color: #ff5555;
}
}
}
}
}
.actionBar {
display: flex;
justify-content: space-between;
align-items: center;
padding-top: 16px;
border-top: 1px solid rgba(0, 200, 255, 0.15);
.actionButtons {
display: flex;
gap: 12px;
.actionBtn {
display: flex;
align-items: center;
gap: 8px;
padding: 10px 24px;
border: 1px solid rgba(0, 200, 255, 0.4);
border-radius: 25px;
background: linear-gradient(135deg, rgba(0, 150, 255, 0.2), rgba(0, 100, 200, 0.1));
color: #00d4ff;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: all 0.3s;
&:hover:not(:disabled) {
background: linear-gradient(135deg, rgba(0, 200, 255, 0.4), rgba(0, 150, 255, 0.2));
border-color: rgba(0, 200, 255, 0.8);
box-shadow: 0 0 25px rgba(0, 200, 255, 0.4);
transform: translateY(-2px);
}
&:disabled {
opacity: 0.4;
cursor: not-allowed;
}
&.primary {
background: linear-gradient(135deg, rgba(0, 200, 100, 0.3), rgba(0, 150, 80, 0.2));
border-color: rgba(0, 255, 136, 0.5);
color: #00ff88;
&:hover:not(:disabled) {
background: linear-gradient(135deg, rgba(0, 255, 136, 0.4), rgba(0, 200, 100, 0.3));
border-color: rgba(0, 255, 136, 0.8);
box-shadow: 0 0 25px rgba(0, 255, 136, 0.4);
}
}
&.danger {
background: linear-gradient(135deg, rgba(200, 50, 50, 0.3), rgba(150, 30, 30, 0.2));
border-color: rgba(255, 80, 80, 0.5);
color: #ff6b6b;
&:hover:not(:disabled) {
background: linear-gradient(135deg, rgba(255, 80, 80, 0.4), rgba(200, 50, 50, 0.3));
border-color: rgba(255, 80, 80, 0.8);
box-shadow: 0 0 25px rgba(255, 80, 80, 0.4);
}
}
}
}
.gpsInfo {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 16px;
background: rgba(0, 100, 150, 0.2);
border: 1px solid rgba(0, 200, 255, 0.2);
border-radius: 20px;
font-size: 12px;
color: rgba(255, 255, 255, 0.7);
font-family: 'Courier New', monospace;
.gpsIcon {
color: #00d4ff;
}
}
}
}
@@ -0,0 +1,288 @@
import React from 'react';
import {
ThunderboltOutlined,
RocketOutlined,
HomeOutlined,
AlertOutlined,
CloudOutlined,
EnvironmentOutlined,
WifiOutlined,
SettingOutlined,
} from '@ant-design/icons';
import type { RealtimeData } from '../hooks/useDeviceSSE';
import styles from './index.less';
interface DeviceInfoProps {
device: any;
realtimeData: RealtimeData | null;
sseConnected: boolean;
expanded: boolean;
onTakeoff?: () => void;
onControl?: () => void;
}
// 精简视图
export const CompactView: React.FC<DeviceInfoProps> = ({
device,
realtimeData,
sseConnected,
onTakeoff,
onControl,
}) => {
const isOnline = realtimeData?.online;
const battery = realtimeData?.battery ?? 0;
const droneOnline = realtimeData?.rawData?.dockData?.sub_device?.device_online_status === 1;
const droneInDock = realtimeData?.rawData?.dockData?.drone_in_dock === 1;
const modeCode = realtimeData?.rawData?.dockData?.mode_code;
const getBatteryClass = () => {
if (battery > 50) return styles.high;
if (battery > 20) return styles.medium;
return styles.low;
};
return (
<div className={styles.compactView}>
<div className={styles.statusRow}>
<div className={styles.statusGroup}>
{/* 机库状态 */}
<div className={styles.statusItem}>
<div className={styles.statusIcon}>
<HomeOutlined />
</div>
<div className={styles.statusInfo}>
<div className={styles.statusLabel}>机库</div>
<div className={`${styles.statusValue} ${isOnline ? styles.online : styles.offline}`}>
{isOnline ? '在线' : '离线'}
</div>
</div>
</div>
{/* 无人机状态 */}
<div className={styles.statusItem}>
<div className={styles.statusIcon}>
<RocketOutlined />
</div>
<div className={styles.statusInfo}>
<div className={styles.statusLabel}>无人机</div>
<div className={`${styles.statusValue} ${droneOnline ? styles.warning : styles.offline}`}>
{droneOnline ? '已开机' : '未开机'}
</div>
</div>
</div>
{/* 在库状态 */}
<div className={styles.statusItem}>
<div className={styles.statusIcon}>
<SettingOutlined />
</div>
<div className={styles.statusInfo}>
<div className={styles.statusLabel}>状态</div>
<div className={`${styles.statusValue} ${droneInDock ? styles.online : styles.warning}`}>
{droneInDock ? '在库' : '外出'}
</div>
</div>
</div>
{/* 电池电量 */}
<div className={`${styles.batteryItem} ${getBatteryClass()}`}>
<ThunderboltOutlined className={styles.batteryIcon} />
<span className={styles.batteryText}>{battery}%</span>
</div>
</div>
{/* 操作按钮 */}
<div className={styles.actionButtons}>
<button
className={`${styles.actionBtn} ${styles.primary}`}
onClick={onTakeoff}
disabled={modeCode === 1 || !droneInDock}
>
<RocketOutlined />
一键起飞
</button>
<button className={styles.actionBtn} onClick={onControl}>
<WifiOutlined />
操控
</button>
</div>
</div>
</div>
);
};
// 完整视图
export const ExpandedView: React.FC<DeviceInfoProps> = ({
device,
realtimeData,
sseConnected,
onTakeoff,
onControl,
}) => {
const dockData = realtimeData?.rawData?.dockData;
const isOnline = realtimeData?.online;
const battery = realtimeData?.battery ?? 0;
const getModeText = (code?: number) => {
if (code === 0) return '待机';
if (code === 1) return '工作中';
return '未知';
};
const getCoverText = (state?: number) => {
if (state === 0) return '关闭';
if (state === 1) return '打开';
return '等待';
};
return (
<div className={styles.expandedView}>
<div className={styles.dataGrid}>
{/* 机库信息 */}
<div className={styles.dataCard}>
<div className={styles.cardHeader}>
<div className={styles.cardIcon}>
<HomeOutlined />
</div>
<span className={styles.cardTitle}>机库状态</span>
</div>
<div className={styles.cardContent}>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>名称</span>
<span className={styles.dataValue}>{device?.deviceName || '-'}</span>
</div>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>状态</span>
<span className={`${styles.dataValue} ${dockData?.mode_code === 0 ? styles.success : styles.warning}`}>
{getModeText(dockData?.mode_code)}
</span>
</div>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>舱门</span>
<span className={`${styles.dataValue} ${dockData?.cover_state === 0 ? styles.success : styles.warning}`}>
{getCoverText(dockData?.cover_state)}
</span>
</div>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>告警</span>
<span className={`${styles.dataValue} ${dockData?.alarm_state === 0 ? styles.success : styles.error}`}>
{dockData?.alarm_state === 0 ? '正常' : '有告警'}
</span>
</div>
</div>
</div>
{/* 无人机信息 */}
<div className={styles.dataCard}>
<div className={styles.cardHeader}>
<div className={styles.cardIcon}>
<RocketOutlined />
</div>
<span className={styles.cardTitle}>无人机状态</span>
</div>
<div className={styles.cardContent}>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>SN</span>
<span className={styles.dataValue}>{dockData?.sub_device?.device_sn || '--'}</span>
</div>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>开机</span>
<span className={`${styles.dataValue} ${dockData?.sub_device?.device_online_status === 1 ? styles.success : ''}`}>
{dockData?.sub_device?.device_online_status === 1 ? '已开机' : '未开机'}
</span>
</div>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>电量</span>
<span className={`${styles.dataValue} ${battery > 50 ? styles.success : battery > 20 ? styles.warning : styles.error}`}>
{battery}%
</span>
</div>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>温度</span>
<span className={styles.dataValue}>{realtimeData?.temperature ?? 0}°C</span>
</div>
</div>
</div>
{/* 环境数据 */}
<div className={styles.dataCard}>
<div className={styles.cardHeader}>
<div className={styles.cardIcon}>
<CloudOutlined />
</div>
<span className={styles.cardTitle}>环境数据</span>
</div>
<div className={styles.cardContent}>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>温度</span>
<span className={styles.dataValue}>
{dockData?.environment_temperature ?? dockData?.temperature ?? 0}°C
</span>
</div>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>湿度</span>
<span className={styles.dataValue}>{dockData?.humidity ?? 0}%</span>
</div>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>风速</span>
<span className={styles.dataValue}>{dockData?.wind_speed ?? 0} m/s</span>
</div>
<div className={styles.dataRow}>
<span className={styles.dataLabel}>降雨</span>
<span className={styles.dataValue}>{dockData?.rainfall ?? 0} mm</span>
</div>
</div>
</div>
</div>
{/* 底部操作栏 */}
<div className={styles.actionBar}>
<div className={styles.actionButtons}>
<button
className={`${styles.actionBtn} ${styles.primary}`}
onClick={onTakeoff}
disabled={dockData?.mode_code === 1 || dockData?.drone_in_dock !== 1}
>
<RocketOutlined />
一键起飞
</button>
<button className={styles.actionBtn} onClick={onControl}>
<WifiOutlined />
操控无人机
</button>
<button className={styles.actionBtn} disabled>
<HomeOutlined />
一键返航
</button>
<button className={`${styles.actionBtn} ${styles.danger}`} disabled>
<AlertOutlined />
紧急悬停
</button>
</div>
{/* GPS信息 */}
<div className={styles.gpsInfo}>
<EnvironmentOutlined className={styles.gpsIcon} />
<span>
{(realtimeData?.gps?.latitude ?? 0).toFixed(6)}°,{' '}
{(realtimeData?.gps?.longitude ?? 0).toFixed(6)}°,{' '}
{(realtimeData?.gps?.altitude ?? 0).toFixed(1)}m
</span>
</div>
</div>
</div>
);
};
// 主组件
const DeviceInfo: React.FC<DeviceInfoProps> = (props) => {
const { expanded, ...rest } = props;
if (expanded) {
return <ExpandedView {...props} />;
}
return <CompactView {...props} />;
};
export default DeviceInfo;
@@ -0,0 +1,454 @@
# 大疆建图模型加载指南
## 一、模型处理流程
### 1. 大疆建图输出格式
大疆 Terra 建图软件输出的主要格式:
| 格式 | 说明 | Cesium支持 |
|------|------|-----------|
| **OSGB** | 倾斜摄影标准格式 | ❌ 需转换 |
| **3D Tiles** | Cesium原生格式 | ✅ 直接使用 |
| **OBJ** | 通用3D格式 | ⚠️ 需转换 |
| **PLY** | 点云格式 | ⚠️ 需转换 |
**推荐**: 直接在大疆Terra导出时选择 **3D Tiles** 格式
### 2. 模型转换(如果输出OSGB)
#### 方式一: Cesium Ion (推荐)
```bash
# 1. 注册 Cesium Ion 账号 https://cesium.com/ion/
# 2. 上传OSGB文件夹
# 3. 选择 "3D Capture" 或 "3D Model"
# 4. 等待处理完成,获取 Asset ID
```
#### 方式二: 开源工具转换
```bash
# 使用 cesiumlab 或 obj23dtiles
npm install -g 3d-tiles-tools
# OSGB转3D Tiles (需要osgb23dtiles工具)
osgb23dtiles -i ./osgb_folder -o ./3dtiles_output
```
#### 方式三: FME (企业级)
- 使用 Safe Software FME
- 支持批量转换和自动化流程
### 3. 模型存储方案
#### 方案A: 对象存储 + CDN (推荐)
```
OSS/MinIO/S3
├── scenic-models/
│ ├── {tourismId}/
│ │ ├── tileset.json # 入口文件
│ │ ├── data/
│ │ │ ├── L0/ # LOD层级
│ │ │ ├── L1/
│ │ │ └── ...
│ │ └── textures/ # 纹理文件
```
**优势**:
- 支持CDN加速
- 按需加载,节省带宽
- 支持断点续传
#### 方案B: Cesium Ion 托管
```typescript
// 使用 Asset ID 加载
const tileset = await Cesium.Cesium3DTileset.fromIonAssetId(YOUR_ASSET_ID, {
// 配置选项
});
```
#### 方案C: 本地服务器
```
nginx静态资源服务
├── /models/
│ ├── scenic_001/tileset.json
│ └── scenic_002/tileset.json
```
---
## 二、前端使用方式
### 1. 基础配置
```tsx
import CesiumContainer from './components/MapContainer/CesiumContainer';
// 定义模型配置
const tilesetConfigs = [
{
id: 'scenic_huangshan',
name: '黄山景区3D模型',
url: 'https://your-cdn.com/models/huangshan/tileset.json',
tourismId: 101,
position: {
longitude: 0, // 经度微调
latitude: 0, // 纬度微调
height: 0, // 高度偏移
},
style: {
maximumScreenSpaceError: 16, // LOD精度
maximumMemoryUsage: 512, // 最大内存MB
},
visible: true,
},
];
// 使用组件
<CesiumContainer
tourismList={tourismList}
tilesetConfigs={tilesetConfigs}
/>
```
### 2. 动态加载景区模型
```tsx
// 从后端API获取模型配置
const fetchTilesetConfigs = async (tourismId: number) => {
const response = await fetch(`/api/tourism/${tourismId}/3d-model`);
const data = await response.json();
return {
id: `tileset_${tourismId}`,
name: data.name,
url: data.tilesetUrl,
tourismId,
position: data.position,
style: data.style,
};
};
```
### 3. 性能优化配置
```typescript
// 低端设备配置
const lowEndConfig = {
maximumScreenSpaceError: 32, // 降低LOD精度
maximumMemoryUsage: 256, // 限制内存
skipLevelOfDetail: true,
preferLeaves: true,
progressiveResolutionHeightFraction: 0.5,
};
// 高端设备配置
const highEndConfig = {
maximumScreenSpaceError: 8, // 高精度LOD
maximumMemoryUsage: 1024, // 更多内存
skipLevelOfDetail: false,
preferLeaves: false,
};
```
---
## 三、后端API设计
### 1. 模型管理接口
```java
// 景区3D模型Controller
@RestController
@RequestMapping("/api/tourism")
public class Tourism3DModelController {
// 获取景区的3D模型配置
@GetMapping("/{tourismId}/3d-model")
public Result<TilesetConfigVO> getTilesetConfig(@PathVariable Long tourismId) {
return Result.succeed(tourismService.getTilesetConfig(tourismId));
}
// 上传模型(获取上传凭证)
@PostMapping("/{tourismId}/3d-model/upload-token")
public Result<UploadTokenVO> getUploadToken(@PathVariable Long tourismId) {
return Result.succeed(ossService.generateUploadToken(tourismId));
}
// 更新模型配置
@PutMapping("/{tourismId}/3d-model")
public Result<Void> updateTilesetConfig(
@PathVariable Long tourismId,
@RequestBody TilesetConfigDTO dto
) {
tourismService.updateTilesetConfig(tourismId, dto);
return Result.succeed();
}
}
```
### 2. 数据库设计
```sql
-- 景区3D模型表
CREATE TABLE tourism_3d_model (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
tourism_id BIGINT NOT NULL COMMENT '关联景区ID',
model_name VARCHAR(100) NOT NULL COMMENT '模型名称',
tileset_url VARCHAR(500) NOT NULL COMMENT 'tileset.json URL',
-- 位置调整
offset_longitude DECIMAL(10,7) DEFAULT 0 COMMENT '经度偏移',
offset_latitude DECIMAL(10,7) DEFAULT 0 COMMENT '纬度偏移',
offset_height DECIMAL(10,2) DEFAULT 0 COMMENT '高度偏移',
-- 变换参数
scale DECIMAL(5,3) DEFAULT 1.0 COMMENT '缩放比例',
rotation_x DECIMAL(6,4) DEFAULT 0 COMMENT 'X轴旋转(弧度)',
rotation_y DECIMAL(6,4) DEFAULT 0 COMMENT 'Y轴旋转',
rotation_z DECIMAL(6,4) DEFAULT 0 COMMENT 'Z轴旋转',
-- 渲染配置
max_screen_space_error INT DEFAULT 16 COMMENT 'LOD精度',
max_memory_usage INT DEFAULT 512 COMMENT '最大内存(MB)',
-- 元数据
file_size BIGINT COMMENT '文件大小(bytes)',
create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
status TINYINT DEFAULT 1 COMMENT '1-正常 0-禁用',
INDEX idx_tourism_id (tourism_id),
UNIQUE KEY uk_tourism (tourism_id)
) COMMENT='景区3D模型配置';
```
### 3. VO/DTO定义
```java
@Data
public class TilesetConfigVO {
private String id;
private String name;
private String url;
private Long tourismId;
private PositionConfig position;
private TransformConfig transform;
private StyleConfig style;
private Boolean visible;
}
@Data
public class PositionConfig {
private Double longitude;
private Double latitude;
private Double height;
}
@Data
public class StyleConfig {
private Integer maximumScreenSpaceError = 16;
private Integer maximumMemoryUsage = 512;
private Boolean skipLevelOfDetail = true;
private Boolean preferLeaves = true;
}
```
---
## 四、完整业务流程
### 流程图
```
┌─────────────────────────────────────────────────────────────────────┐
│ 大疆建图模型上线流程 │
└─────────────────────────────────────────────────────────────────────┘
1. 模型采集
┌──────────────┐
│ 无人机航拍 │ ──→ 大疆Terra建图 ──→ 输出3D Tiles
└──────────────┘
2. 模型上传
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ 获取上传凭证 │ ──→ │ 分片上传OSS │ ──→ │ CDN预热 │
└──────────────┘ └──────────────┘ └──────────────┘
3. 配置关联
┌──────────────┐ ┌──────────────┐
│ 保存模型配置 │ ──→ │ 关联景区ID │
└──────────────┘ └──────────────┘
4. 前端加载
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ 查询模型配置 │ ──→ │ Cesium加载 │ ──→ │ 渐进式渲染 │
└──────────────┘ └──────────────┘ └──────────────┘
```
### 详细步骤
#### Step 1: 模型采集与处理
1. 使用大疆无人机对景区进行航拍
2. 将航拍数据导入大疆Terra
3. 选择"重建"任务,输出格式选择 **3D Tiles**
4. 等待处理完成,检查模型质量
#### Step 2: 模型上传
```typescript
// 前端上传流程
const uploadModel = async (tourismId: number, files: FileList) => {
// 1. 获取上传凭证
const { uploadUrl, ossPath } = await api.getUploadToken(tourismId);
// 2. 分片上传大文件
for (const file of files) {
await uploadToOSS(uploadUrl, ossPath, file);
}
// 3. 通知后端上传完成
await api.notifyUploadComplete(tourismId, ossPath);
};
```
#### Step 3: 模型配置
```typescript
// 管理后台配置模型参数
const saveModelConfig = async (tourismId: number, config: ModelConfig) => {
await api.updateTilesetConfig(tourismId, {
name: config.name,
tilesetUrl: `https://cdn.example.com/models/${tourismId}/tileset.json`,
position: {
longitude: config.offsetLng,
latitude: config.offsetLat,
height: config.offsetHeight,
},
style: {
maximumScreenSpaceError: config.lodQuality,
maximumMemoryUsage: config.memoryLimit,
},
});
};
```
#### Step 4: 前端展示
```typescript
// 地图仪表盘自动加载关联模型
useEffect(() => {
if (selectedTourism && selectedTourism.has3DModel) {
loadTourismModel(selectedTourism.id);
}
}, [selectedTourism]);
const loadTourismModel = async (tourismId: number) => {
const config = await api.getTilesetConfig(tourismId);
await handleLoadTileset(config);
handleFlyToTileset(config.id);
};
```
---
## 五、性能优化最佳实践
### 1. LOD (Level of Detail) 策略
```typescript
// 根据设备性能动态调整
const getOptimalConfig = () => {
const memory = navigator.deviceMemory || 4; // GB
const cores = navigator.hardwareConcurrency || 4;
if (memory >= 8 && cores >= 8) {
return { maximumScreenSpaceError: 8, maximumMemoryUsage: 1024 };
} else if (memory >= 4) {
return { maximumScreenSpaceError: 16, maximumMemoryUsage: 512 };
} else {
return { maximumScreenSpaceError: 32, maximumMemoryUsage: 256 };
}
};
```
### 2. 视锥裁剪
```typescript
// 启用视锥裁剪优化
const tilesetConfig = {
cullWithChildrenBounds: true, // 子节点包围盒裁剪
cullRequestsWhileMoving: true, // 移动时暂停请求
cullRequestsWhileMovingMultiplier: 60.0,
};
```
### 3. 预加载策略
```typescript
// 预加载飞行目的地
const tilesetConfig = {
preloadWhenHidden: true, // 隐藏时也预加载
preloadFlightDestinations: true, // 预加载飞行目标
};
```
### 4. 内存管理
```typescript
// 监控内存使用
viewer.scene.postRender.addEventListener(() => {
const statistics = tileset.statistics;
console.log('已加载Tiles:', statistics.numberOfTilesLoaded);
console.log('内存使用:', statistics.totalMemoryUsageInBytes / 1024 / 1024, 'MB');
});
// 当内存超限时降级
if (statistics.totalMemoryUsageInBytes > MAX_MEMORY) {
tileset.maximumScreenSpaceError *= 2; // 降低精度
}
```
### 5. 网络优化
```nginx
# Nginx配置 - 启用gzip和缓存
location /models/ {
gzip on;
gzip_types application/json application/octet-stream;
# 长期缓存静态资源
add_header Cache-Control "public, max-age=31536000, immutable";
# CORS支持
add_header Access-Control-Allow-Origin *;
}
```
---
## 六、常见问题
### Q1: 模型位置偏移怎么调整?
```typescript
// 使用position配置微调
const config = {
position: {
longitude: 0.0001, // 向东偏移约10米
latitude: -0.0001, // 向南偏移约10米
height: 5, // 抬高5米
}
};
```
### Q2: 模型加载太慢?
1. 检查CDN是否生效
2. 降低 `maximumScreenSpaceError` 值
3. 启用 `skipLevelOfDetail`
4. 检查模型文件大小,考虑简化
### Q3: 模型显示不完整?
1. 检查 `tileset.json` 路径是否正确
2. 确认所有子文件都已上传
3. 检查浏览器控制台的网络请求
### Q4: 内存占用过高?
1. 降低 `maximumMemoryUsage`
2. 增大 `maximumScreenSpaceError`
3. 启用 `cullRequestsWhileMoving`
@@ -0,0 +1,153 @@
.tilesetPanel {
position: absolute;
top: 10px;
right: 440px; // 放在 RightPanel (420px) 左边,不遮挡 Home 按钮
width: 320px;
max-height: calc(100vh - 100px);
z-index: 1100; // 高于 RightPanel 的 z-index (1000)
animation: slideInRight 0.3s ease-out;
@keyframes slideInRight {
from {
opacity: 0;
transform: translateX(20px);
}
to {
opacity: 1;
transform: translateX(0);
}
}
.panelCard {
background: rgba(10, 20, 40, 0.95);
border: 1px solid rgba(0, 240, 255, 0.3);
border-radius: 8px;
backdrop-filter: blur(10px);
:global {
.ant-card-head {
background: rgba(0, 240, 255, 0.1);
border-bottom: 1px solid rgba(0, 240, 255, 0.2);
color: #fff;
padding: 8px 12px;
min-height: auto;
.ant-card-head-title {
padding: 4px 0;
font-size: 14px;
}
.ant-card-extra {
padding: 0;
.ant-btn {
color: rgba(255, 255, 255, 0.6);
&:hover {
color: #fff;
}
}
}
}
.ant-card-body {
padding: 8px;
max-height: 400px;
overflow-y: auto;
&::-webkit-scrollbar {
width: 4px;
}
&::-webkit-scrollbar-track {
background: rgba(255, 255, 255, 0.05);
}
&::-webkit-scrollbar-thumb {
background: rgba(0, 240, 255, 0.3);
border-radius: 2px;
}
}
.ant-list-item {
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
padding: 8px 0;
}
.ant-empty-description {
color: rgba(255, 255, 255, 0.5);
}
}
}
.listItem {
display: block;
}
.itemContent {
width: 100%;
}
.itemHeader {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 8px;
}
.itemName {
color: #fff;
font-size: 13px;
font-weight: 500;
max-width: 160px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.progress {
margin-bottom: 8px;
:global {
.ant-progress-text {
color: rgba(255, 255, 255, 0.8);
font-size: 11px;
}
}
}
.errorMsg {
color: #ff4d4f;
font-size: 11px;
margin-bottom: 8px;
padding: 4px 8px;
background: rgba(255, 77, 79, 0.1);
border-radius: 4px;
}
.itemActions {
display: flex;
justify-content: flex-end;
gap: 8px;
:global {
.ant-btn {
font-size: 12px;
}
.ant-switch {
background: rgba(255, 255, 255, 0.2);
&.ant-switch-checked {
background: #00f0ff;
}
}
}
}
}
// 暗色模式兼容
@media (prefers-color-scheme: dark) {
.tilesetPanel {
.panelCard {
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
}
}
}
@@ -0,0 +1,202 @@
/**
* 3D Tiles 模型管理面板
* 用于显示和管理景区倾斜摄影模型
*/
import React from 'react';
import { Card, List, Progress, Button, Switch, Space, Tag, Tooltip, Empty } from 'antd';
import {
EyeOutlined,
EyeInvisibleOutlined,
AimOutlined,
DeleteOutlined,
ReloadOutlined,
CloudDownloadOutlined,
CheckCircleOutlined,
CloseCircleOutlined,
LoadingOutlined,
} from '@ant-design/icons';
import type { TilesetConfig, TilesetState } from '../hooks/useTilesetLoader';
import styles from './index.less';
interface TilesetPanelProps {
visible: boolean;
tilesets: Map<string, TilesetState>;
configs: TilesetConfig[];
onLoad: (config: TilesetConfig) => void;
onUnload: (id: string) => void;
onFlyTo: (id: string) => void;
onToggleVisible: (id: string, visible: boolean) => void;
onClose: () => void;
}
const TilesetPanel: React.FC<TilesetPanelProps> = ({
visible,
tilesets,
configs,
onLoad,
onUnload,
onFlyTo,
onToggleVisible,
onClose,
}) => {
if (!visible) return null;
// 获取状态图标
const getStatusIcon = (state?: TilesetState) => {
if (!state) return <CloudDownloadOutlined style={{ color: '#999' }} />;
switch (state.status) {
case 'loading':
return <LoadingOutlined style={{ color: '#1890ff' }} spin />;
case 'loaded':
return <CheckCircleOutlined style={{ color: '#52c41a' }} />;
case 'error':
return <CloseCircleOutlined style={{ color: '#ff4d4f' }} />;
default:
return <CloudDownloadOutlined style={{ color: '#999' }} />;
}
};
// 获取状态标签
const getStatusTag = (state?: TilesetState) => {
if (!state) return <Tag>未加载</Tag>;
switch (state.status) {
case 'loading':
return <Tag color="processing">加载中 {state.progress}%</Tag>;
case 'loaded':
return <Tag color="success">已加载</Tag>;
case 'error':
return <Tag color="error">加载失败</Tag>;
default:
return <Tag>未加载</Tag>;
}
};
return (
<div className={styles.tilesetPanel}>
<Card
title={
<Space>
<span>3D模型管理</span>
<Tag color="cyan">{configs.length} 个模型</Tag>
</Space>
}
extra={
<Button type="text" size="small" onClick={onClose}>
关闭
</Button>
}
size="small"
className={styles.panelCard}
>
{configs.length === 0 ? (
<Empty description="暂无3D模型" image={Empty.PRESENTED_IMAGE_SIMPLE} />
) : (
<List
dataSource={configs}
renderItem={(config) => {
const state = tilesets.get(config.id);
const isLoaded = state?.status === 'loaded';
const isLoading = state?.status === 'loading';
return (
<List.Item className={styles.listItem}>
<div className={styles.itemContent}>
<div className={styles.itemHeader}>
<Space>
{getStatusIcon(state)}
<span className={styles.itemName}>{config.name}</span>
</Space>
{getStatusTag(state)}
</div>
{/* 加载进度 */}
{isLoading && (
<Progress
percent={state?.progress || 0}
size="small"
strokeColor="#00f0ff"
trailColor="rgba(255,255,255,0.1)"
className={styles.progress}
/>
)}
{/* 错误信息 */}
{state?.status === 'error' && (
<div className={styles.errorMsg}>
{state.error || '加载失败,请重试'}
</div>
)}
{/* 操作按钮 */}
<div className={styles.itemActions}>
{!isLoaded && !isLoading && (
<Tooltip title="加载模型">
<Button
type="primary"
size="small"
icon={<CloudDownloadOutlined />}
onClick={() => onLoad(config)}
>
加载
</Button>
</Tooltip>
)}
{isLoaded && (
<Space size="small">
<Tooltip title="飞往模型">
<Button
type="default"
size="small"
icon={<AimOutlined />}
onClick={() => onFlyTo(config.id)}
/>
</Tooltip>
<Tooltip title={config.visible !== false ? '隐藏' : '显示'}>
<Switch
size="small"
checked={config.visible !== false}
onChange={(checked) => onToggleVisible(config.id, checked)}
checkedChildren={<EyeOutlined />}
unCheckedChildren={<EyeInvisibleOutlined />}
/>
</Tooltip>
<Tooltip title="卸载模型">
<Button
type="text"
size="small"
danger
icon={<DeleteOutlined />}
onClick={() => onUnload(config.id)}
/>
</Tooltip>
</Space>
)}
{state?.status === 'error' && (
<Tooltip title="重新加载">
<Button
type="default"
size="small"
icon={<ReloadOutlined />}
onClick={() => onLoad(config)}
>
重试
</Button>
</Tooltip>
)}
</div>
</div>
</List.Item>
);
}}
/>
)}
</Card>
</div>
);
};
export default TilesetPanel;
@@ -0,0 +1,240 @@
import { useState, useRef, useEffect, useCallback } from 'react';
import { message } from 'antd';
// GPS信息
interface GpsData {
latitude: number;
longitude: number;
altitude: number;
}
// 机库数据接口定义 (省略部分详细字段以节省空间,保持原有定义)
export interface DockData {
// ... (保持原有字段定义不变,此处省略展示)
[key: string]: any;
}
// 实时数据
export interface RealtimeData {
deviceSn: string;
online: boolean;
battery?: number;
temperature?: number;
humidity?: number;
gps?: GpsData;
flightMode?: string;
flightStatus?: string;
timestamp?: number;
rawData?: {
dockData?: any;
[key: string]: any;
};
}
interface UseDeviceSSEResult {
realtimeData: RealtimeData | null;
sseConnected: boolean;
connectSSE: (deviceSn: string) => Promise<void>;
disconnectSSE: (deviceSn?: string) => Promise<void>;
}
export function useDeviceSSE(): UseDeviceSSEResult {
const [realtimeData, setRealtimeData] = useState<RealtimeData | null>(null);
const [sseConnected, setSSEConnected] = useState(false);
const abortControllerRef = useRef<AbortController | null>(null);
const currentDeviceSnRef = useRef<string>('');
const clientSessionIdRef = useRef<string>(
`client_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`
);
// 核心断开逻辑,提取为纯函数以便在不同生命周期调用
const performDisconnect = (deviceSn: string, sessionId: string, token: string | null) => {
if (!deviceSn || !token) return;
// 尝试使用 fetch keepalive
fetch(`/api-device/sse/device-status/${deviceSn}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`,
'X-Client-Session-Id': sessionId,
},
keepalive: true,
}).catch(err => console.error('Disconnect fetch failed:', err));
// 备用方案:如果支持 Beacon 且后端允许 POST 处理断开 (通常 API 设计为 DELETE,Beacon 不适用,故仅作备注)
// navigator.sendBeacon(...) 仅支持 POST
};
// 断开SSE连接
const disconnectSSE = useCallback(async (deviceSn?: string) => {
const snToDisconnect = deviceSn || currentDeviceSnRef.current;
// 1. 取消当前的 fetch 连接 (客户端主动断开)
if (abortControllerRef.current) {
abortControllerRef.current.abort();
abortControllerRef.current = null;
}
// 2. 发送请求通知后端 (服务端清理资源)
if (snToDisconnect) {
const token = sessionStorage.getItem('access_token');
performDisconnect(snToDisconnect, clientSessionIdRef.current, token);
}
setSSEConnected(false);
currentDeviceSnRef.current = '';
console.log('SSE连接已断开');
}, []);
// 处理SSE事件
const handleSSEEvent = useCallback((eventName: string, data: string) => {
try {
if (eventName === 'connected') {
console.log('SSE连接确认:', data);
} else if (eventName === 'device-data-update') {
const parsedData = JSON.parse(data);
setRealtimeData(parsedData);
} else if (eventName === 'heartbeat') {
// 心跳
}
} catch (error) {
console.error('解析SSE数据失败:', error);
}
}, []);
// 连接SSE
const connectSSE = useCallback(async (deviceSn: string) => {
// 如果已经连接了同一个设备,先不断开,或者视需求而定。
// 这里采取策略:如果 ID 变了,先断开旧的。
if (currentDeviceSnRef.current && currentDeviceSnRef.current !== deviceSn) {
await disconnectSSE(currentDeviceSnRef.current);
}
if (!deviceSn) return;
currentDeviceSnRef.current = deviceSn;
try {
const token = sessionStorage.getItem('access_token');
const url = `/api-device/sse/device-status/${deviceSn}`;
const abortController = new AbortController();
abortControllerRef.current = abortController;
console.log('正在建立SSE连接:', deviceSn);
const response = await fetch(url, {
method: 'GET',
headers: {
'Accept': 'text/event-stream',
'Cache-Control': 'no-cache',
'Authorization': `Bearer ${token}`,
'X-Client-Session-Id': clientSessionIdRef.current,
},
cache: 'no-store',
signal: abortController.signal,
});
if (!response.ok) {
throw new Error(`SSE连接失败: ${response.status}`);
}
setSSEConnected(true);
const reader = response.body?.getReader();
const decoder = new TextDecoder();
if (!reader) throw new Error('无法读取响应流');
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) {
console.log('SSE连接已关闭');
setSSEConnected(false);
break;
}
const chunk = decoder.decode(value, { stream: true });
buffer += chunk;
const lines = buffer.split('\n');
buffer = lines.pop() || '';
let currentEvent = '';
let currentData = '';
for (const line of lines) {
const trimmedLine = line.trim();
if (trimmedLine === '') {
if (currentEvent && currentData) {
handleSSEEvent(currentEvent, currentData);
}
currentEvent = '';
currentData = '';
} else if (line.startsWith('event:')) {
currentEvent = line.substring(6).trim();
} else if (line.startsWith('data:')) {
currentData = line.substring(5).trim();
}
}
}
} catch (error: any) {
if (error.name === 'AbortError') {
return;
}
console.error('SSE连接错误:', error);
setSSEConnected(false);
// message.error('连接实时数据失败'); // 避免频繁报错
// 简单重连逻辑
setTimeout(() => {
if (currentDeviceSnRef.current === deviceSn && !abortControllerRef.current) {
// 只有在没有活跃连接时才重连
// connectSSE(deviceSn); // 慎用自动重连,可能导致死循环
}
}, 5000);
}
}, [disconnectSSE, handleSSEEvent]);
// 监听浏览器刷新/关闭事件 (beforeunload)
useEffect(() => {
const handleBeforeUnload = () => {
if (currentDeviceSnRef.current) {
const token = sessionStorage.getItem('access_token');
performDisconnect(currentDeviceSnRef.current, clientSessionIdRef.current, token);
}
};
window.addEventListener('beforeunload', handleBeforeUnload);
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
};
}, []);
// 组件卸载清理 (React Unmount)
useEffect(() => {
return () => {
// 在组件卸载时,也尝试发送断开请求
if (currentDeviceSnRef.current) {
const token = sessionStorage.getItem('access_token');
performDisconnect(currentDeviceSnRef.current, clientSessionIdRef.current, token);
}
if (abortControllerRef.current) {
abortControllerRef.current.abort();
}
};
}, []);
return {
realtimeData,
sseConnected,
connectSSE,
disconnectSSE,
};
}
export default useDeviceSSE;
@@ -0,0 +1,330 @@
/**
* 3D Tiles 倾斜摄影模型加载器 Hook
* 用于加载大疆建图等工具生成的3D Tiles模型
*/
import { useState, useCallback, useRef } from 'react';
// 模型配置接口
export interface TilesetConfig {
id: string; // 模型唯一标识
name: string; // 模型名称
url: string; // tileset.json 的URL地址
tourismId?: number; // 关联的景区ID
position?: { // 模型位置调整
longitude?: number; // 经度偏移
latitude?: number; // 纬度偏移
height?: number; // 高度偏移
};
transform?: { // 模型变换
scale?: number; // 缩放比例
rotationX?: number; // X轴旋转(弧度)
rotationY?: number; // Y轴旋转
rotationZ?: number; // Z轴旋转
};
style?: { // 渲染样式
maximumScreenSpaceError?: number; // LOD精度控制(默认16)
maximumMemoryUsage?: number; // 最大内存使用(MB)
skipLevelOfDetail?: boolean; // 是否跳过LOD
preferLeaves?: boolean; // 优先加载叶子节点
};
visible?: boolean; // 是否可见
}
// 模型加载状态
export interface TilesetState {
id: string;
status: 'pending' | 'loading' | 'loaded' | 'error';
progress: number; // 加载进度 0-100
error?: string;
tileset?: any; // Cesium3DTileset 实例
}
// Hook返回类型
export interface UseTilesetLoaderResult {
tilesets: Map<string, TilesetState>;
loadTileset: (config: TilesetConfig, viewer: any, Cesium: any) => Promise<any>;
unloadTileset: (id: string, viewer: any) => void;
unloadAllTilesets: (viewer: any) => void;
flyToTileset: (id: string, viewer: any, Cesium: any) => void;
setTilesetVisible: (id: string, visible: boolean) => void;
updateTilesetStyle: (id: string, style: any, Cesium: any) => void;
}
export const useTilesetLoader = (): UseTilesetLoaderResult => {
const [tilesets, setTilesets] = useState<Map<string, TilesetState>>(new Map());
const tilesetsRef = useRef<Map<string, any>>(new Map());
/**
* 加载3D Tiles模型
*/
const loadTileset = useCallback(async (
config: TilesetConfig,
viewer: any,
Cesium: any
): Promise<any> => {
if (!viewer || !Cesium) {
console.error('Viewer或Cesium未初始化');
return null;
}
// 如果已经加载,直接返回
if (tilesetsRef.current.has(config.id)) {
console.log(`模型 ${config.id} 已加载,跳过`);
return tilesetsRef.current.get(config.id);
}
// 更新状态为loading
setTilesets(prev => {
const newMap = new Map(prev);
newMap.set(config.id, {
id: config.id,
status: 'loading',
progress: 0,
});
return newMap;
});
try {
// 创建3DTileset - 高清晰度渲染配置
const tileset = await Cesium.Cesium3DTileset.fromUrl(config.url, {
// 核心清晰度控制 - 值越小越清晰(大疆司空使用约1-2)
maximumScreenSpaceError: config.style?.maximumScreenSpaceError ?? 1,
maximumMemoryUsage: config.style?.maximumMemoryUsage ?? 2048, // 增加内存以加载更多高精度瓦片
// 禁用LOD跳跃以获得更好的清晰度
skipLevelOfDetail: config.style?.skipLevelOfDetail ?? false,
preferLeaves: config.style?.preferLeaves ?? true,
// 动态调度 - 关闭以保持一致的高清晰度
dynamicScreenSpaceError: false,
// 预加载配置 - 积极预加载
preloadWhenHidden: true,
preloadFlightDestinations: true,
// 渐进式加载 - 减少模糊过渡
progressiveResolutionHeightFraction: 0.5,
// 焦点区域优化
foveatedScreenSpaceError: true,
foveatedConeSize: 0.1,
foveatedMinimumScreenSpaceErrorRelaxation: 0.0,
// 裁剪优化 - 减少移动时的清晰度降低
cullWithChildrenBounds: true,
cullRequestsWhileMoving: false, // 禁用移动时的请求裁剪
cullRequestsWhileMovingMultiplier: 1.0,
// 缓存策略 - 立即加载高精度
immediatelyLoadDesiredLevelOfDetail: true,
loadSiblings: true, // 加载相邻瓦片以减少边缘模糊
// 显示设置
show: config.visible !== false,
});
// 监听加载进度
tileset.loadProgress.addEventListener((numberOfPendingRequests: number, numberOfTilesProcessing: number) => {
const total = numberOfPendingRequests + numberOfTilesProcessing;
const progress = total > 0 ? Math.min(99, 100 - (total * 2)) : 100;
setTilesets(prev => {
const newMap = new Map(prev);
const state = newMap.get(config.id);
if (state) {
newMap.set(config.id, { ...state, progress });
}
return newMap;
});
});
// 模型位置调整 - 只有当位置偏移不为0时才调整
if (config.position) {
const { longitude = 0, latitude = 0, height = 0 } = config.position;
// 只有当有非零偏移时才应用位置调整
if (longitude !== 0 || latitude !== 0 || height !== 0) {
const boundingSphere = tileset.boundingSphere;
const cartographic = Cesium.Cartographic.fromCartesian(boundingSphere.center);
const newLon = cartographic.longitude + Cesium.Math.toRadians(longitude);
const newLat = cartographic.latitude + Cesium.Math.toRadians(latitude);
const newHeight = cartographic.height + height;
const newCenter = Cesium.Cartesian3.fromRadians(newLon, newLat, newHeight);
const translation = Cesium.Cartesian3.subtract(newCenter, boundingSphere.center, new Cesium.Cartesian3());
tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
}
}
// 模型变换(缩放/旋转) - 只有当有非默认值时才应用
if (config.transform) {
const { scale = 1, rotationX = 0, rotationY = 0, rotationZ = 0 } = config.transform;
// 只有当缩放不为1或有旋转时才应用变换
const needsTransform = scale !== 1 || rotationX !== 0 || rotationY !== 0 || rotationZ !== 0;
if (needsTransform) {
const boundingSphere = tileset.boundingSphere;
const center = boundingSphere.center;
// 创建变换矩阵
const transformMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(center);
// 应用旋转
if (rotationX !== 0 || rotationY !== 0 || rotationZ !== 0) {
const rotationMatrix = Cesium.Matrix3.fromHeadingPitchRoll(
new Cesium.HeadingPitchRoll(rotationZ, rotationX, rotationY)
);
const rotation4 = Cesium.Matrix4.fromRotationTranslation(rotationMatrix);
Cesium.Matrix4.multiply(transformMatrix, rotation4, transformMatrix);
}
// 应用缩放
if (scale !== 1) {
const scaleMatrix = Cesium.Matrix4.fromScale(new Cesium.Cartesian3(scale, scale, scale));
Cesium.Matrix4.multiply(transformMatrix, scaleMatrix, transformMatrix);
}
tileset.modelMatrix = Cesium.Matrix4.multiply(
tileset.modelMatrix || Cesium.Matrix4.IDENTITY,
transformMatrix,
new Cesium.Matrix4()
);
}
}
// 添加到场景
viewer.scene.primitives.add(tileset);
// 存储引用
tilesetsRef.current.set(config.id, tileset);
// 更新状态为loaded
setTilesets(prev => {
const newMap = new Map(prev);
newMap.set(config.id, {
id: config.id,
status: 'loaded',
progress: 100,
tileset,
});
return newMap;
});
console.log(`3D Tiles模型 [${config.name}] 加载成功`);
return tileset;
} catch (error: any) {
console.error(`3D Tiles模型 [${config.name}] 加载失败:`, error);
setTilesets(prev => {
const newMap = new Map(prev);
newMap.set(config.id, {
id: config.id,
status: 'error',
progress: 0,
error: error.message || '加载失败',
});
return newMap;
});
return null;
}
}, []);
/**
* 卸载指定模型
*/
const unloadTileset = useCallback((id: string, viewer: any) => {
const tileset = tilesetsRef.current.get(id);
if (tileset && viewer) {
viewer.scene.primitives.remove(tileset);
tilesetsRef.current.delete(id);
setTilesets(prev => {
const newMap = new Map(prev);
newMap.delete(id);
return newMap;
});
console.log(`模型 ${id} 已卸载`);
}
}, []);
/**
* 卸载所有模型
*/
const unloadAllTilesets = useCallback((viewer: any) => {
if (!viewer) return;
tilesetsRef.current.forEach((tileset, id) => {
viewer.scene.primitives.remove(tileset);
});
tilesetsRef.current.clear();
setTilesets(new Map());
console.log('所有3D Tiles模型已卸载');
}, []);
/**
* 飞行到指定模型
*/
const flyToTileset = useCallback((id: string, viewer: any, Cesium: any) => {
const tileset = tilesetsRef.current.get(id);
if (!tileset || !viewer || !Cesium) return;
const boundingSphere = tileset.boundingSphere;
const center = boundingSphere.center;
const radius = boundingSphere.radius;
// 计算合适的观察距离
const offset = new Cesium.HeadingPitchRange(
Cesium.Math.toRadians(0), // heading
Cesium.Math.toRadians(-45), // pitch (45度俯视)
radius * 2.5 // 距离
);
viewer.camera.flyToBoundingSphere(boundingSphere, {
offset,
duration: 2.0,
});
}, []);
/**
* 设置模型可见性
*/
const setTilesetVisible = useCallback((id: string, visible: boolean) => {
const tileset = tilesetsRef.current.get(id);
if (tileset) {
tileset.show = visible;
}
}, []);
/**
* 更新模型样式(着色/高亮等)
*/
const updateTilesetStyle = useCallback((id: string, style: any, Cesium: any) => {
const tileset = tilesetsRef.current.get(id);
if (!tileset || !Cesium) return;
// 示例: 设置建筑颜色
tileset.style = new Cesium.Cesium3DTileStyle({
color: style.color || "color('white')",
show: style.show !== false,
pointSize: style.pointSize || 5,
});
}, []);
return {
tilesets,
loadTileset,
unloadTileset,
unloadAllTilesets,
flyToTileset,
setTilesetVisible,
updateTilesetStyle,
};
};
export default useTilesetLoader;
@@ -18,6 +18,7 @@ const AmapContainer: React.FC<AmapContainerProps> = (props) => {
const mapRef = useRef<HTMLDivElement>(null);
const mapInstanceRef = useRef<any>(null);
const markersRef = useRef<Map<string, any>>(new Map());
const [mapReady, setMapReady] = React.useState(false); // 新增状态
// 初始化地图
useEffect(() => {
@@ -44,6 +45,9 @@ const AmapContainer: React.FC<AmapContainerProps> = (props) => {
resizeEnable: true,
});
// 标记地图已就绪
setMapReady(true);
console.log('地图初始化成功,开始加载控件插件...');
// 添加地图控件 - 使用 AMap.plugin 异步加载
window.AMap.plugin(['AMap.Scale', 'AMap.ToolBar'], () => {
@@ -169,7 +173,7 @@ const AmapContainer: React.FC<AmapContainerProps> = (props) => {
marker.setMap(mapInstanceRef.current);
markersRef.current.set(`tourism_${tourism.id}`, marker);
});
}, [tourismList, onTourismClick]);
}, [tourismList, onTourismClick, mapReady]);
return <div ref={mapRef} style={{ width: '100%', height: '100%' }} />;
};
@@ -1,82 +1,304 @@
import React, { useEffect, useRef, useState } from 'react';
import { message } from 'antd';
import React, { useEffect, useRef, useState, useCallback } from 'react';
import { message, Button, Tooltip } from 'antd';
import { AppstoreOutlined } from '@ant-design/icons';
import RightPanel from './3d/BottomPanel/RightPanel';
import LeftControlPanel from './3d/BottomPanel/LeftControlPanel';
import TilesetPanel from './3d/TilesetPanel';
import { useTilesetLoader, TilesetConfig } from './3d/hooks/useTilesetLoader';
import { getModelsByTourismId, convertToTilesetConfig } from '@/services/threeDModel';
// 动态导入Cesium
let Cesium: any = null;
interface CesiumContainerProps {
tourismList: any[];
onTourismClick: (tourism: any) => void;
externalSelectedTourism?: any; // 接收外部选择的景区
}
const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
const { tourismList, onTourismClick } = props;
const { tourismList, externalSelectedTourism } = props;
const containerRef = useRef<HTMLDivElement>(null);
const viewerRef = useRef<any>(null);
const entitiesRef = useRef<Map<string, any>>(new Map());
const [loading, setLoading] = useState(true);
// 3D 模式专属状态
const [selectedTourism, setSelectedTourism] = useState<any>(null);
const [rightPanelVisible, setRightPanelVisible] = useState(false);
const [leftPanelVisible, setLeftPanelVisible] = useState(false);
// 传递给 LeftControlPanel 的数据
const [controlDevice, setControlDevice] = useState<any>(null);
const [controlRealtimeData, setControlRealtimeData] = useState<any>(null);
// 3D Tiles 模型管理
const [tilesetPanelVisible, setTilesetPanelVisible] = useState(false);
const [currentTourismModels, setCurrentTourismModels] = useState<TilesetConfig[]>([]); // 当前景区的模型
const [modelLoading, setModelLoading] = useState(false);
const {
tilesets,
loadTileset,
unloadTileset,
unloadAllTilesets,
flyToTileset,
setTilesetVisible,
} = useTilesetLoader();
// 相机飞到景区
const flyToTourism = useCallback((tourism: any) => {
if (!viewerRef.current || !Cesium) return;
const lon = parseFloat(tourism.longitude);
const lat = parseFloat(tourism.latitude);
if (isNaN(lon) || isNaN(lat)) return;
viewerRef.current.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(lon, lat, 10000), // 5000km 高度
orientation: {
heading: 0,
pitch: Cesium.Math.toRadians(-90), // 垂直俯视
roll: 0,
},
duration: 1.5,
});
}, []);
// 相机飞回全球视角
const flyToGlobal = useCallback(() => {
if (!viewerRef.current || !Cesium) return;
viewerRef.current.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(104.195397, 35.86166, 15000000),
orientation: {
heading: 0,
pitch: Cesium.Math.toRadians(-90),
roll: 0,
},
duration: 1.5,
});
}, []);
// 加载景区绑定的模型,返回是否有模型
const loadTourismModels = useCallback(async (tourismId: number): Promise<boolean> => {
if (!viewerRef.current || !Cesium) {
console.log('Viewer或Cesium未准备好');
return false;
}
console.log('开始查询景区模型, tourismId:', tourismId);
setModelLoading(true);
// 先卸载之前的模型
unloadAllTilesets(viewerRef.current);
setCurrentTourismModels([]);
try {
const res = await getModelsByTourismId(tourismId);
console.log('查询景区模型结果:', res);
const modelList = res.datas || res.data; // 兼容两种返回格式
if (res.resp_code === 0 && modelList && modelList.length > 0) {
const configs = modelList.map((model: any) => convertToTilesetConfig(model));
console.log('转换后的模型配置:', configs);
setCurrentTourismModels(configs);
let loadedCount = 0;
// 加载所有模型
for (const config of configs) {
console.log('准备加载模型:', config.name, 'URL:', config.url);
if (config.url) {
const tileset = await loadTileset(config, viewerRef.current, Cesium);
if (tileset) {
loadedCount++;
message.success(`模型 [${config.name}] 加载成功`);
// 加载成功后飞到第一个模型位置
if (loadedCount === 1) {
// 使用 viewer.flyTo 自动飞到模型
try {
await viewerRef.current.flyTo(tileset, {
duration: 2.0,
offset: new Cesium.HeadingPitchRange(
Cesium.Math.toRadians(0),
Cesium.Math.toRadians(-45),
0
),
});
} catch (e) {
console.warn('flyTo 失败,尝试 zoomTo:', e);
await viewerRef.current.zoomTo(tileset);
}
}
}
} else {
console.warn('模型URL为空,跳过加载:', config.name);
}
}
setModelLoading(false);
return loadedCount > 0;
} else {
console.log('该景区没有绑定模型或查询结果为空');
setModelLoading(false);
return false;
}
} catch (error) {
console.error('加载景区模型失败:', error);
setModelLoading(false);
return false;
}
}, [loadTileset, unloadAllTilesets]);
// 处理景区点击
const handleTourismSelect = useCallback((tourism: any) => {
setSelectedTourism(tourism);
setRightPanelVisible(true);
// 切换景区时,关闭左侧操控台
setLeftPanelVisible(false);
// 查询并加载该景区绑定的3D模型
// 如果有模型会自动飞到模型位置,没有模型才飞到景区位置
if (tourism.id) {
loadTourismModels(tourism.id).then((hasModel) => {
if (!hasModel) {
flyToTourism(tourism);
}
});
} else {
flyToTourism(tourism);
}
}, [flyToTourism, loadTourismModels]);
// 处理外部选择变化
useEffect(() => {
if (externalSelectedTourism && !loading) {
handleTourismSelect(externalSelectedTourism);
}
}, [externalSelectedTourism, loading, handleTourismSelect]);
// 处理从右侧面板点击“操控”
const handleOpenControl = useCallback((device: any, realtimeData: any) => {
setControlDevice(device);
setControlRealtimeData(realtimeData);
setLeftPanelVisible(true);
}, []);
// 关闭右侧面板
const handleRightPanelClose = useCallback(() => {
setRightPanelVisible(false);
setSelectedTourism(null);
setLeftPanelVisible(false); // 同时也关闭左侧
flyToGlobal();
}, [flyToGlobal]);
// ========== 3D Tiles 模型管理方法 ==========
// 加载模型
const handleLoadTileset = useCallback(async (config: TilesetConfig) => {
if (!viewerRef.current || !Cesium) {
message.warning('请等待地图加载完成');
return;
}
const tileset = await loadTileset(config, viewerRef.current, Cesium);
if (tileset) {
message.success(`模型 [${config.name}] 加载成功`);
}
}, [loadTileset]);
// 卸载模型
const handleUnloadTileset = useCallback((id: string) => {
unloadTileset(id, viewerRef.current);
message.info('模型已卸载');
}, [unloadTileset]);
// 飞往模型
const handleFlyToTileset = useCallback((id: string) => {
flyToTileset(id, viewerRef.current, Cesium);
}, [flyToTileset]);
// 切换模型可见性
const handleToggleTilesetVisible = useCallback((id: string, visible: boolean) => {
setTilesetVisible(id, visible);
// 更新当前景区模型配置状态
setCurrentTourismModels(prev =>
prev.map(c => c.id === id ? { ...c, visible } : c)
);
}, [setTilesetVisible]);
// 初始化Cesium
useEffect(() => {
const initCesium = async () => {
try {
// 动态导入Cesium
if (!Cesium) {
const cesiumModule = await import('cesium');
Cesium = cesiumModule;
// 动态加载Cesium样式(使用CDN,稳定可靠)
const cesiumBaseUrl = process.env.CESIUM_BASE_URL || '/';
Cesium.buildModuleUrl.setBaseUrl(`${cesiumBaseUrl}cesium/`);
if (!document.querySelector('link[href*="cesium"]')) {
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = 'https://unpkg.com/cesium@1.110.0/Build/Cesium/Widgets/widgets.css';
link.href = `${cesiumBaseUrl}cesium/Widgets/widgets.css`;
document.head.appendChild(link);
}
}
if (!containerRef.current) return;
// 配置Cesium Ion Token(使用默认的,或配置自己的)
// Cesium.Ion.defaultAccessToken = process.env.REACT_APP_CESIUM_TOKEN || '';
// 创建Viewer
viewerRef.current = new Cesium.Viewer(containerRef.current, {
// 使用天地图或高德作为底图(国内访问)
imageryProvider: new Cesium.UrlTemplateImageryProvider({
url: 'https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}',
minimumLevel: 3,
maximumLevel: 18,
}),
// 地形设置 - 使用默认地形(平坦)
terrainProvider: new Cesium.EllipsoidTerrainProvider(),
// UI组件配置
animation: false, // 不显示动画控件
timeline: false, // 不显示时间轴
fullscreenButton: false, // 不显示全屏按钮
geocoder: false, // 不显示地理位置搜索
homeButton: true, // 显示主页按钮
sceneModePicker: true, // 显示2D/3D切换
baseLayerPicker: false, // 不显示底图选择器
navigationHelpButton: false,// 不显示帮助按钮
// 性能优化
requestRenderMode: true, // 请求渲染模式
scene3DOnly: false,
shouldAnimate: true,
animation: false,
timeline: false,
fullscreenButton: false,
geocoder: false,
homeButton: true,
sceneModePicker: true,
baseLayerPicker: false,
navigationHelpButton: false,
infoBox: false,
selectionIndicator: false,
requestRenderMode: true,
maximumRenderTimeChange: Infinity,
});
// 设置初始视角(中国中心,可以看到全国范围)
viewerRef.current.imageryLayers.remove(viewerRef.current.imageryLayers.get(0));
viewerRef.current.scene.globe.baseColor = Cesium.Color.fromCssColorString('#1e4d7b');
const arcgisImagery = new Cesium.UrlTemplateImageryProvider({
url: 'https://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
minimumLevel: 0,
maximumLevel: 18,
});
viewerRef.current.imageryLayers.addImageryProvider(arcgisImagery);
viewerRef.current.scene.globe.enableLighting = false;
viewerRef.current.scene.globe.show = true;
viewerRef.current.scene.skyAtmosphere.show = true;
viewerRef.current.camera.setView({
destination: Cesium.Cartesian3.fromDegrees(104.195397, 35.86166, 5000000), // 提高高度到5000km
destination: Cesium.Cartesian3.fromDegrees(104.195397, 35.86166, 15000000),
orientation: {
heading: Cesium.Math.toRadians(0),
pitch: Cesium.Math.toRadians(-60), // 俯视角度
roll: 0.0,
heading: 0,
pitch: Cesium.Math.toRadians(-90),
roll: 0,
},
});
// 移除Cesium Logo和版权信息的点击事件
// 重写 Home 按钮行为
viewerRef.current.homeButton.viewModel.command.beforeExecute.addEventListener((e: any) => {
e.cancel = true; // 取消默认行为
viewerRef.current.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(104.195397, 35.86166, 15000000),
orientation: {
heading: 0,
pitch: Cesium.Math.toRadians(-90),
roll: 0,
},
duration: 1.5,
});
});
const creditContainer = viewerRef.current.cesiumWidget.creditContainer;
if (creditContainer) {
creditContainer.style.display = 'none';
@@ -94,7 +316,6 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
initCesium();
return () => {
// 清理
if (viewerRef.current && !viewerRef.current.isDestroyed()) {
viewerRef.current.destroy();
}
@@ -103,11 +324,10 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
// 更新景区标记
useEffect(() => {
if (!viewerRef.current || !Cesium || !tourismList.length) return;
if (loading || !viewerRef.current || !Cesium || !tourismList.length) return;
const viewer = viewerRef.current;
// 清除旧标记
entitiesRef.current.forEach((entity, key) => {
if (key.startsWith('tourism_')) {
viewer.entities.remove(entity);
@@ -115,36 +335,22 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
}
});
// 验证并过滤有效的景区坐标(只显示有经纬度的景区)
const validTourisms = tourismList.filter((tourism) => {
const lat = parseFloat(tourism.latitude);
const lng = parseFloat(tourism.longitude);
return !isNaN(lat) && !isNaN(lng) && lat !== 0 && lng !== 0;
});
// 如果没有有效景区,不进行后续操作
if (validTourisms.length === 0) {
return;
}
// 添加景区标记
const positions: any[] = [];
if (validTourisms.length === 0) return;
validTourisms.forEach((tourism) => {
const lon = parseFloat(tourism.longitude);
const lat = parseFloat(tourism.latitude);
// 根据 status 状态设置颜色:1=绿色(启用),0=红色(禁用)
const pointColor = tourism.status === 1 ? '#52c41a' : '#ff4d4f';
positions.push(Cesium.Cartesian3.fromDegrees(lon, lat));
// 创建实体标记
const entity = viewer.entities.add({
id: `tourism_${tourism.id}`,
position: Cesium.Cartesian3.fromDegrees(lon, lat, 0),
// 点标记
point: {
pixelSize: 20,
color: Cesium.Color.fromCssColorString(pointColor),
@@ -152,8 +358,6 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
outlineWidth: 3,
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
},
// 标签
label: {
text: tourism.tourismName || '景区',
font: '14px sans-serif',
@@ -166,8 +370,6 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
// 存储景区数据
properties: {
tourismData: tourism,
},
@@ -175,39 +377,34 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
entitiesRef.current.set(`tourism_${tourism.id}`, entity);
});
}, [tourismList]);
}, [tourismList, loading]);
// 点击事件
useEffect(() => {
if (!viewerRef.current || !Cesium) return;
if (loading || !viewerRef.current || !Cesium) return;
const viewer = viewerRef.current;
viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
// 左键点击
handler.setInputAction((movement: any) => {
const pickedObject = viewer.scene.pick(movement.position);
if (Cesium.defined(pickedObject) && pickedObject.id) {
const entity = pickedObject.id;
const tourismData = entity.properties?.tourismData?.getValue();
if (tourismData) {
onTourismClick(tourismData);
handleTourismSelect(tourismData);
}
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
// 鼠标移动悬停效果
handler.setInputAction((movement: any) => {
const pickedObject = viewer.scene.pick(movement.endPosition);
if (Cesium.defined(pickedObject) && pickedObject.id && pickedObject.id.point) {
// 鼠标悬停时放大点
pickedObject.id.point.pixelSize = 25;
document.body.style.cursor = 'pointer';
} else {
// 恢复所有点的大小
entitiesRef.current.forEach((entity) => {
if (entity.point) {
entity.point.pixelSize = 20;
@@ -221,11 +418,12 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
handler.destroy();
document.body.style.cursor = 'default';
};
}, [onTourismClick]);
}, [loading, handleTourismSelect]);
return (
<div style={{ width: '100%', height: '100%', position: 'relative' }}>
<div ref={containerRef} style={{ width: '100%', height: '100%' }} />
{loading && (
<div
style={{
@@ -243,8 +441,75 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
加载3D地图中...
</div>
)}
{/* 模型加载中提示 */}
{modelLoading && (
<div
style={{
position: 'absolute',
top: 60,
left: '50%',
transform: 'translateX(-50%)',
color: '#fff',
fontSize: 14,
background: 'rgba(0,0,0,0.7)',
padding: '8px 16px',
borderRadius: 4,
zIndex: 800,
}}
>
正在加载3D模型...
</div>
)}
{/* 3D模型管理按钮 - 当景区有绑定模型时显示 */}
{!loading && currentTourismModels.length > 0 && (
<Tooltip title="3D模型管理">
<Button
type="primary"
icon={<AppstoreOutlined />}
onClick={() => setTilesetPanelVisible(!tilesetPanelVisible)}
style={{
position: 'absolute',
top: 10,
right: 180,
zIndex: 700,
background: tilesetPanelVisible ? '#00f0ff' : 'rgba(10, 20, 40, 0.9)',
borderColor: '#00f0ff',
}}
/>
</Tooltip>
)}
{/* 3D Tiles模型管理面板 */}
<TilesetPanel
visible={tilesetPanelVisible}
tilesets={tilesets}
configs={currentTourismModels}
onLoad={handleLoadTileset}
onUnload={handleUnloadTileset}
onFlyTo={handleFlyToTileset}
onToggleVisible={handleToggleTilesetVisible}
onClose={() => setTilesetPanelVisible(false)}
/>
{/* 左侧操控台 */}
<LeftControlPanel
visible={leftPanelVisible}
onClose={() => setLeftPanelVisible(false)}
device={controlDevice}
realtimeData={controlRealtimeData}
/>
{/* 右侧数据面板 */}
<RightPanel
visible={rightPanelVisible}
tourism={selectedTourism}
onClose={handleRightPanelClose}
onControlClick={handleOpenControl}
/>
</div>
);
};
export default CesiumContainer;
export default CesiumContainer;
@@ -7,20 +7,28 @@ interface MapContainerProps {
mode: '2d' | '3d';
tourismList: any[];
onTourismClick: (tourism: any) => void;
selectedTourism?: any;
}
const MapContainer: React.FC<MapContainerProps> = (props) => {
const { mode, ...otherProps } = props;
const { mode, tourismList, onTourismClick, selectedTourism } = props;
return (
<div className={styles.mapContainer}>
{/* 2D地图 - 高德 */}
{mode === '2d' && <AmapContainer {...otherProps} />}
{mode === '2d' && (
<AmapContainer tourismList={tourismList} onTourismClick={onTourismClick} />
)}
{/* 3D地图 - Cesium */}
{mode === '3d' && <CesiumContainer {...otherProps} />}
{/* 3D地图 - Cesium(内部处理点击,显示底部面板) */}
{mode === '3d' && (
<CesiumContainer
tourismList={tourismList}
externalSelectedTourism={selectedTourism}
/>
)}
</div>
);
};
export default MapContainer;
export default MapContainer;
@@ -11,14 +11,15 @@
left: 0;
right: 0;
height: 64px;
background: rgba(255, 255, 255, 0.95);
background: rgba(10, 20, 30, 0.9);
backdrop-filter: blur(10px);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
box-shadow: 0 2px 20px rgba(0, 0, 0, 0.5);
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 24px;
z-index: 1000;
border-bottom: 1px solid rgba(0, 240, 255, 0.1);
.left {
display: flex;
@@ -27,7 +28,89 @@
.title {
font-size: 18px;
font-weight: 600;
color: #000;
color: #fff;
text-shadow: 0 0 10px rgba(0, 240, 255, 0.5);
letter-spacing: 1px;
}
// 统计 Badge 样式复写
:global {
.ant-badge-status-text {
color: #00ff88 !important; // 亮绿色
font-weight: 500;
text-shadow: 0 0 5px rgba(0, 0, 0, 0.8); // 黑色阴影增加对比度
background: rgba(0, 0, 0, 0.3); // 半透明背景
padding: 2px 8px;
border-radius: 4px;
}
}
// 下拉框样式
.tourismSelect {
width: 280px;
margin-left: 16px;
:global {
.ant-select-selector {
background-color: rgba(0, 240, 255, 0.05) !important;
border: 1px solid rgba(0, 240, 255, 0.3) !important;
color: #fff;
height: 32px;
border-radius: 2px;
box-shadow: 0 0 5px rgba(0, 240, 255, 0.1);
&:hover {
border-color: #00f0ff !important;
box-shadow: 0 0 10px rgba(0, 240, 255, 0.2);
}
}
.ant-select-selection-item {
color: #fff;
font-weight: 500;
line-height: 30px;
}
.ant-select-selection-placeholder {
color: rgba(255, 255, 255, 0.4);
}
.ant-select-arrow {
color: #00f0ff;
}
}
}
}
// 按钮和单选框样式复写
:global {
.ant-radio-button-wrapper {
background: rgba(255,255,255,0.05);
border-color: rgba(255,255,255,0.1);
color: rgba(255,255,255,0.6);
&:hover {
color: #00f0ff;
}
&.ant-radio-button-wrapper-checked {
background: rgba(0, 240, 255, 0.2);
border-color: #00f0ff;
color: #00f0ff;
box-shadow: 0 0 10px rgba(0, 240, 255, 0.2);
}
}
.ant-btn {
background: rgba(255,255,255,0.05);
border-color: rgba(255,255,255,0.1);
color: #fff;
&:hover {
border-color: #00f0ff;
color: #00f0ff;
background: rgba(0, 240, 255, 0.1);
}
}
}
}
@@ -40,3 +123,29 @@
bottom: 0;
}
}
// 下拉弹窗样式
.tourismSelectPopup {
:global {
.ant-select-dropdown {
background-color: rgba(10, 20, 30, 0.95);
border: 1px solid rgba(0, 240, 255, 0.3);
backdrop-filter: blur(10px);
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
.ant-select-item {
color: rgba(255, 255, 255, 0.8);
&-option-active {
background-color: rgba(0, 240, 255, 0.1);
}
&-option-selected {
background-color: rgba(0, 240, 255, 0.2);
color: #00f0ff;
font-weight: 600;
}
}
}
}
}
@@ -1,10 +1,11 @@
import React, { useState, useEffect } from 'react';
import { Button, Space, Badge, message, Radio } from 'antd';
import { Button, Space, Badge, message, Radio, Select } from 'antd';
import {
ReloadOutlined,
FullscreenOutlined,
FullscreenExitOutlined,
GlobalOutlined,
EnvironmentOutlined
} from '@ant-design/icons';
import { history } from 'umi';
import MapContainer from './components/MapContainer';
@@ -12,15 +13,25 @@ import { ordersApi } from '@/services/orders';
import { tenantApi } from '@/services/tenant';
import styles from './index.less';
const { Option } = Select;
type MapMode = '2d' | '3d';
const MapDashboard: React.FC = () => {
const [tourismList, setTourismList] = useState<any[]>([]);
const [loading, setLoading] = useState(false);
const [mapMode, setMapMode] = useState<MapMode>('2d');
// 初始化时优先读取 sessionStorage,默认为 3d
const [mapMode, setMapMode] = useState<MapMode>(() => {
const savedMode = sessionStorage.getItem('mapDashboard_mode');
return (savedMode === '2d' || savedMode === '3d') ? savedMode : '3d';
});
const [isFullscreen, setIsFullscreen] = useState(false);
const [params, setParams] = useState<{ tenantId?: string; includeChildren?: boolean }>({});
// 用于 3D 模式下的外部选择控制
const [selectedTourism, setSelectedTourism] = useState<any>(null);
// 首次进入时,默认按"当前租户 + 包含下级租户"查询
useEffect(() => {
(async () => {
@@ -70,9 +81,23 @@ const MapDashboard: React.FC = () => {
});
};
// 下拉框选择事件
const handleDropdownSelect = (tourismId: number) => {
const tourism = tourismList.find(t => t.id === tourismId);
if (!tourism) return;
if (mapMode === '2d') {
handleTourismClick(tourism);
} else {
// 3D 模式下,传递给子组件进行定位和展示
setSelectedTourism(tourism);
}
};
// 地图模式切换
const handleMapModeChange = (mode: MapMode) => {
setMapMode(mode);
sessionStorage.setItem('mapDashboard_mode', mode); // 记住用户的选择
message.success(`已切换到${mode === '2d' ? '二维' : '三维'}地图`);
};
@@ -94,6 +119,13 @@ const MapDashboard: React.FC = () => {
}
}, [params.tenantId]);
// 过滤有效景区 (有经纬度)
const validTourismList = tourismList.filter(t => {
const lat = parseFloat(t.latitude);
const lon = parseFloat(t.longitude);
return !isNaN(lat) && !isNaN(lon) && lat !== 0 && lon !== 0;
});
return (
<div className={styles.mapDashboard}>
{/* 顶部工具栏 */}
@@ -103,8 +135,26 @@ const MapDashboard: React.FC = () => {
<Badge
status="success"
text={`共${tourismList.length}个景区`}
style={{ marginLeft: 16 }}
style={{ marginLeft: 16, marginRight: 16 }}
/>
{/* 景区选择下拉框 */}
<Select
showSearch
placeholder="请选择景区进入..."
optionFilterProp="children"
onChange={handleDropdownSelect}
filterOption={(input, option) =>
(option?.children as unknown as string).toLowerCase().indexOf(input.toLowerCase()) >= 0
}
className={styles.tourismSelect}
suffixIcon={<EnvironmentOutlined style={{ color: '#00f0ff' }} />}
popupClassName={styles.tourismSelectPopup}
>
{validTourismList.map(t => (
<Option key={t.id} value={t.id}>{t.tourismName}</Option>
))}
</Select>
</div>
<Space size="middle">
@@ -114,11 +164,11 @@ const MapDashboard: React.FC = () => {
onChange={(e) => handleMapModeChange(e.target.value)}
buttonStyle="solid"
>
<Radio.Button value="2d">
<GlobalOutlined /> 高德2D
</Radio.Button>
<Radio.Button value="3d">
<GlobalOutlined /> Cesium 3D
<GlobalOutlined />3维地图
</Radio.Button>
<Radio.Button value="2d">
<GlobalOutlined />2维地图
</Radio.Button>
</Radio.Group>
@@ -145,6 +195,7 @@ const MapDashboard: React.FC = () => {
mode={mapMode}
tourismList={tourismList}
onTourismClick={handleTourismClick}
selectedTourism={selectedTourism} // 传递选中的景区
/>
</div>
</div>
@@ -0,0 +1,54 @@
import React from 'react';
import {
ModalForm,
ProFormDigit,
} from '@ant-design/pro-components';
import { Descriptions } from 'antd';
import type { GuideProfile } from '@/services/guide';
interface CommissionRateModalProps {
visible: boolean;
onVisibleChange: (visible: boolean) => void;
onFinish: (values: { commissionRate: number }) => Promise<boolean>;
guide?: GuideProfile;
}
const CommissionRateModal: React.FC<CommissionRateModalProps> = ({
visible,
onVisibleChange,
onFinish,
guide,
}) => {
if (!guide) return null;
return (
<ModalForm<{ commissionRate: number }>
title="设置佣金比例"
visible={visible}
onVisibleChange={onVisibleChange}
onFinish={onFinish}
initialValues={{ commissionRate: guide.commissionRate }}
modalProps={{ destroyOnClose: true }}
width={400}
>
<Descriptions column={1} size="small" style={{ marginBottom: 16 }}>
<Descriptions.Item label="导游编号">{guide.guideNo}</Descriptions.Item>
<Descriptions.Item label="导游姓名">{guide.guideName || '-'}</Descriptions.Item>
<Descriptions.Item label="当前佣金比例">{guide.commissionRate}%</Descriptions.Item>
</Descriptions>
<ProFormDigit
name="commissionRate"
label="新佣金比例(%)"
placeholder="请输入新的佣金比例"
rules={[{ required: true, message: '请输入佣金比例' }]}
min={0}
max={100}
fieldProps={{ precision: 2 }}
extra="可设置0-100之间的数值,精确到小数点后2位"
/>
</ModalForm>
);
};
export default CommissionRateModal;
@@ -0,0 +1,172 @@
import React, { useRef, useState } from 'react';
import { ProFormText, ProFormSelect, ProTable, type ActionType } from '@ant-design/pro-components';
import { Space, Tag, message, Popconfirm, Row, Col, Form } from 'antd';
import { GlassCard, GradientButton, SearchBarPlus } from '@/components/ui';
import { SyncOutlined } from '@ant-design/icons';
import {
guideApi,
GuideCommission,
CommissionStatusEnum,
CommissionStatusMap,
} from '@/services/guide';
interface CommissionTabProps {
params: Record<string, any>;
}
const CommissionTab: React.FC<CommissionTabProps> = ({ params: baseParams }) => {
const [params, setParams] = useState<Record<string, any>>(baseParams);
const [batchSettling, setBatchSettling] = useState(false);
const actionRef = useRef<ActionType>();
// 当外部 params 变化时更新
React.useEffect(() => {
setParams((prev) => ({ ...prev, ...baseParams }));
actionRef.current?.reload();
}, [baseParams.tenantId, baseParams.includeChildren]);
const handleSettle = async (record: GuideCommission) => {
const hide = message.loading('结算中...');
try {
await guideApi.settleCommission(record.id);
message.success('结算成功');
actionRef.current?.reload();
} catch {
message.error('结算失败');
} finally {
hide();
}
};
const handleBatchSettle = async () => {
setBatchSettling(true);
const hide = message.loading('批量结算中...');
try {
const res = await guideApi.batchSettleCommissions(7);
const count = (res as any)?.data ?? 0;
message.success(`批量结算完成,共结算 ${count} 条记录`);
actionRef.current?.reload();
} catch {
message.error('批量结算失败');
} finally {
hide();
setBatchSettling(false);
}
};
const columns: any[] = [
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 },
{ title: '佣金单号', dataIndex: 'commissionNo', width: 150, copyable: true },
{ title: '导游编号', dataIndex: 'guideNo', width: 120 },
{ title: '导游姓名', dataIndex: 'guideName', width: 100 },
{ title: '订单编号', dataIndex: 'orderNo', width: 150, copyable: true },
{
title: '订单金额',
dataIndex: 'orderAmount',
width: 100,
render: (v: number) => `¥${(v / 100).toFixed(2)}`,
},
{
title: '佣金比例',
dataIndex: 'commissionRate',
width: 90,
render: (v: number) => `${v}%`,
},
{
title: '佣金金额',
dataIndex: 'commissionAmount',
width: 100,
render: (v: number) => <span style={{ color: '#52c41a', fontWeight: 'bold' }}>¥{(v / 100).toFixed(2)}</span>,
},
{
title: '状态',
dataIndex: 'status',
width: 90,
render: (v: number) => {
const status = CommissionStatusMap[v];
return <Tag color={status?.color || 'default'}>{status?.text || '未知'}</Tag>;
},
},
{ title: '结算时间', dataIndex: 'settleTime', valueType: 'dateTime', width: 160 },
{ title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime', width: 160 },
{ title: '备注', dataIndex: 'remark', width: 150, ellipsis: true },
{
title: '操作',
key: 'action',
width: 100,
fixed: 'right',
render: (_: any, record: GuideCommission) => {
if (record.status === CommissionStatusEnum.PENDING) {
return (
<Popconfirm
title="确认手动结算该笔佣金?"
onConfirm={() => handleSettle(record)}
>
<a>结算</a>
</Popconfirm>
);
}
return <span style={{ color: '#999' }}>-</span>;
},
},
];
return (
<>
<Row style={{ marginBottom: 16 }} gutter={16} align="middle">
<Col flex="auto">
<Form
layout="inline"
onFinish={(values) => {
setParams((prev) => ({ ...prev, ...values }));
actionRef.current?.reload();
}}
>
<Form.Item name="orderNo" label="订单编号">
<input placeholder="请输入订单编号" style={{ width: 150, padding: '4px 8px', border: '1px solid #d9d9d9', borderRadius: 4 }} />
</Form.Item>
<Form.Item name="guideNo" label="导游编号">
<input placeholder="请输入导游编号" style={{ width: 150, padding: '4px 8px', border: '1px solid #d9d9d9', borderRadius: 4 }} />
</Form.Item>
<Form.Item>
<GradientButton type="primary" htmlType="submit" size="small">查询</GradientButton>
</Form.Item>
</Form>
</Col>
<Col>
<Popconfirm
title="确认执行批量结算?将结算所有满足T+7条件的待结算佣金"
onConfirm={handleBatchSettle}
>
<GradientButton
size="small"
type="primary"
icon={<SyncOutlined spin={batchSettling} />}
loading={batchSettling}
>
批量结算(T+7)
</GradientButton>
</Popconfirm>
</Col>
</Row>
<GlassCard>
{params?.tenantId ? (
<ProTable<GuideCommission>
rowKey="id"
actionRef={actionRef}
params={params}
request={(p) => guideApi.getCommissionList({ ...(p as any), ...params })}
columns={columns}
search={false}
scroll={{ x: 1400 }}
pagination={{ showSizeChanger: true, showQuickJumper: true }}
toolBarRender={false}
/>
) : null}
</GlassCard>
</>
);
};
export default CommissionTab;
@@ -0,0 +1,116 @@
import React from 'react';
import {
ModalForm,
ProFormRadio,
ProFormTextArea,
} from '@ant-design/pro-components';
import { Descriptions, Statistic, Row, Col, Divider } from 'antd';
import type { GuideProfile } from '@/services/guide';
import { GuideStatusMap } from '@/services/guide';
export interface GuideAuditFormValues {
approved: boolean;
auditRemark?: string;
}
interface GuideAuditModalProps {
visible: boolean;
onVisibleChange: (visible: boolean) => void;
onFinish: (values: GuideAuditFormValues) => Promise<boolean>;
guide?: GuideProfile;
}
const GuideAuditModal: React.FC<GuideAuditModalProps> = ({
visible,
onVisibleChange,
onFinish,
guide,
}) => {
if (!guide) return null;
return (
<ModalForm<GuideAuditFormValues>
title="导游审核"
visible={visible}
onVisibleChange={onVisibleChange}
onFinish={onFinish}
modalProps={{ destroyOnClose: true }}
width={600}
>
<Descriptions column={2} bordered size="small">
<Descriptions.Item label="导游编号">{guide.guideNo}</Descriptions.Item>
<Descriptions.Item label="导游姓名">{guide.guideName || '-'}</Descriptions.Item>
<Descriptions.Item label="联系电话">{guide.guidePhone || '-'}</Descriptions.Item>
<Descriptions.Item label="身份证号">
{guide.idCard ? `${guide.idCard.substring(0, 6)}****${guide.idCard.substring(14)}` : '-'}
</Descriptions.Item>
<Descriptions.Item label="当前状态">
{GuideStatusMap[guide.status]?.text || '未知'}
</Descriptions.Item>
<Descriptions.Item label="佣金比例">{guide.commissionRate}%</Descriptions.Item>
<Descriptions.Item label="创建时间" span={2}>{guide.createTime || '-'}</Descriptions.Item>
</Descriptions>
<Divider />
<Row gutter={16} style={{ marginBottom: 16 }}>
<Col span={6}>
<Statistic
title="累计佣金"
value={guide.totalCommission / 100}
precision={2}
prefix="¥"
valueStyle={{ fontSize: 16 }}
/>
</Col>
<Col span={6}>
<Statistic
title="可提现"
value={guide.availableCommission / 100}
precision={2}
prefix="¥"
valueStyle={{ fontSize: 16, color: '#52c41a' }}
/>
</Col>
<Col span={6}>
<Statistic
title="冻结中"
value={guide.frozenCommission / 100}
precision={2}
prefix="¥"
valueStyle={{ fontSize: 16, color: '#faad14' }}
/>
</Col>
<Col span={6}>
<Statistic
title="已提现"
value={guide.withdrawnCommission / 100}
precision={2}
prefix="¥"
valueStyle={{ fontSize: 16 }}
/>
</Col>
</Row>
<Divider />
<ProFormRadio.Group
name="approved"
label="审核结果"
rules={[{ required: true, message: '请选择审核结果' }]}
options={[
{ label: '通过', value: true },
{ label: '拒绝', value: false },
]}
/>
<ProFormTextArea
name="auditRemark"
label="审核备注"
placeholder="请输入审核备注(可选)"
fieldProps={{ rows: 3 }}
/>
</ModalForm>
);
};
export default GuideAuditModal;
@@ -0,0 +1,121 @@
import React from 'react';
import {
ModalForm,
ProFormText,
ProFormDigit,
ProFormSelect,
} from '@ant-design/pro-components';
import { tenantApi } from '@/services/tenant';
export interface GuideFormValues {
name: string;
phone: string;
idCard?: string;
tenantId: string;
openid?: string;
avatar?: string;
commissionRate?: number;
}
interface GuideFormProps {
title: string;
visible: boolean;
onVisibleChange: (visible: boolean) => void;
onFinish: (values: GuideFormValues) => Promise<boolean>;
initialValues?: Partial<GuideFormValues>;
}
const GuideForm: React.FC<GuideFormProps> = ({
title,
visible,
onVisibleChange,
onFinish,
initialValues,
}) => {
return (
<ModalForm<GuideFormValues>
title={title}
visible={visible}
onVisibleChange={onVisibleChange}
onFinish={onFinish}
initialValues={initialValues}
modalProps={{ destroyOnClose: true }}
width={500}
>
<ProFormText
name="name"
label="导游姓名"
placeholder="请输入导游姓名"
rules={[{ required: true, message: '请输入导游姓名' }]}
/>
<ProFormText
name="phone"
label="联系电话"
placeholder="请输入联系电话"
rules={[
{ required: true, message: '请输入联系电话' },
{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' },
]}
/>
<ProFormText
name="idCard"
label="身份证号"
placeholder="请输入身份证号"
rules={[
{ pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号' },
]}
/>
<ProFormSelect
name="tenantId"
label="所属租户"
placeholder="请选择导游所属租户"
rules={[{ required: true, message: '请选择所属租户' }]}
request={async () => {
try {
const res = await tenantApi.getAccessibleTenants();
const treeData = res?.data || res || [];
const flattenTree = (nodes: any[]): any[] => {
let result: any[] = [];
for (const node of nodes) {
result.push({ label: node.name || node.tenantName, value: node.id || node.tenantId });
if (node.children?.length) {
result = result.concat(flattenTree(node.children));
}
}
return result;
};
return flattenTree(treeData);
} catch {
return [];
}
}}
showSearch
fieldProps={{
optionFilterProp: 'label',
}}
/>
<ProFormText
name="openid"
label="微信OpenID"
placeholder="请输入微信OpenID(可选)"
/>
<ProFormText
name="avatar"
label="头像URL"
placeholder="请输入头像URL(可选)"
/>
<ProFormDigit
name="commissionRate"
label="佣金比例(%)"
placeholder="请输入佣金比例"
min={0}
max={100}
fieldProps={{ precision: 2 }}
initialValue={10}
extra="默认10%,可设置0-100之间的数值"
/>
</ModalForm>
);
};
export default GuideForm;
@@ -0,0 +1,88 @@
import React from 'react';
import {
ModalForm,
ProFormText,
} from '@ant-design/pro-components';
import { Descriptions, Alert } from 'antd';
import type { GuideWithdrawal } from '@/services/guide';
import { WithdrawTypeMap } from '@/services/guide';
interface TransferConfirmModalProps {
visible: boolean;
onVisibleChange: (visible: boolean) => void;
onFinish: (values: { transferNo: string }) => Promise<boolean>;
withdrawal?: GuideWithdrawal;
}
const TransferConfirmModal: React.FC<TransferConfirmModalProps> = ({
visible,
onVisibleChange,
onFinish,
withdrawal,
}) => {
if (!withdrawal) return null;
// 解析账户信息
let accountInfoDisplay = '-';
if (withdrawal.accountInfo) {
try {
const info = typeof withdrawal.accountInfo === 'string'
? JSON.parse(withdrawal.accountInfo)
: withdrawal.accountInfo;
if (withdrawal.withdrawType === 1) {
accountInfoDisplay = `微信OpenID: ${info.openid || '-'}`;
} else {
accountInfoDisplay = `${info.bankName || '-'} ${info.bankAccount || '-'}`;
}
} catch {
accountInfoDisplay = withdrawal.accountInfo as string;
}
}
return (
<ModalForm<{ transferNo: string }>
title="确认打款"
visible={visible}
onVisibleChange={onVisibleChange}
onFinish={onFinish}
modalProps={{ destroyOnClose: true }}
width={500}
>
<Alert
message="请确认已完成线下打款操作后再确认"
type="warning"
showIcon
style={{ marginBottom: 16 }}
/>
<Descriptions column={1} bordered size="small">
<Descriptions.Item label="提现单号">{withdrawal.withdrawNo}</Descriptions.Item>
<Descriptions.Item label="导游姓名">{withdrawal.guideName || '-'}</Descriptions.Item>
<Descriptions.Item label="提现金额">
<span style={{ color: '#ff4d4f', fontWeight: 'bold' }}>
¥{(withdrawal.amount / 100).toFixed(2)}
</span>
</Descriptions.Item>
<Descriptions.Item label="实际到账">
<span style={{ color: '#52c41a', fontWeight: 'bold' }}>
¥{((withdrawal.actualAmount ?? withdrawal.amount - withdrawal.fee) / 100).toFixed(2)}
</span>
</Descriptions.Item>
<Descriptions.Item label="提现方式">
{WithdrawTypeMap[withdrawal.withdrawType] || '未知'}
</Descriptions.Item>
<Descriptions.Item label="收款账户">{accountInfoDisplay}</Descriptions.Item>
</Descriptions>
<ProFormText
name="transferNo"
label="转账单号"
placeholder="请输入微信/银行转账单号"
rules={[{ required: true, message: '请输入转账单号' }]}
extra="请输入打款时的微信企业付款单号或银行转账流水号"
/>
</ModalForm>
);
};
export default TransferConfirmModal;
@@ -0,0 +1,65 @@
import React from 'react';
import {
ModalForm,
ProFormTextArea,
} from '@ant-design/pro-components';
import { Descriptions, Alert } from 'antd';
import type { GuideWithdrawal } from '@/services/guide';
import { WithdrawTypeMap } from '@/services/guide';
interface TransferFailedModalProps {
visible: boolean;
onVisibleChange: (visible: boolean) => void;
onFinish: (values: { failReason: string }) => Promise<boolean>;
withdrawal?: GuideWithdrawal;
}
const TransferFailedModal: React.FC<TransferFailedModalProps> = ({
visible,
onVisibleChange,
onFinish,
withdrawal,
}) => {
if (!withdrawal) return null;
return (
<ModalForm<{ failReason: string }>
title="打款失败"
visible={visible}
onVisibleChange={onVisibleChange}
onFinish={onFinish}
modalProps={{ destroyOnClose: true }}
width={500}
>
<Alert
message="确认打款失败后,冻结的金额将退回导游可提现余额"
type="error"
showIcon
style={{ marginBottom: 16 }}
/>
<Descriptions column={1} bordered size="small">
<Descriptions.Item label="提现单号">{withdrawal.withdrawNo}</Descriptions.Item>
<Descriptions.Item label="导游姓名">{withdrawal.guideName || '-'}</Descriptions.Item>
<Descriptions.Item label="提现金额">
<span style={{ color: '#ff4d4f', fontWeight: 'bold' }}>
¥{(withdrawal.amount / 100).toFixed(2)}
</span>
</Descriptions.Item>
<Descriptions.Item label="提现方式">
{WithdrawTypeMap[withdrawal.withdrawType] || '未知'}
</Descriptions.Item>
</Descriptions>
<ProFormTextArea
name="failReason"
label="失败原因"
placeholder="请输入打款失败原因"
rules={[{ required: true, message: '请输入失败原因' }]}
fieldProps={{ rows: 3 }}
/>
</ModalForm>
);
};
export default TransferFailedModal;
@@ -0,0 +1,122 @@
import React from 'react';
import {
ModalForm,
ProFormRadio,
ProFormTextArea,
} from '@ant-design/pro-components';
import { Descriptions, Tag, Divider } from 'antd';
import type { GuideWithdrawal } from '@/services/guide';
import { WithdrawalStatusEnum, WithdrawalStatusMap, WithdrawTypeMap } from '@/services/guide';
export interface WithdrawalAuditFormValues {
approved: boolean;
auditRemark?: string;
}
interface WithdrawalAuditModalProps {
visible: boolean;
onVisibleChange: (visible: boolean) => void;
onFinish: (values: WithdrawalAuditFormValues) => Promise<boolean>;
withdrawal?: GuideWithdrawal;
}
const WithdrawalAuditModal: React.FC<WithdrawalAuditModalProps> = ({
visible,
onVisibleChange,
onFinish,
withdrawal,
}) => {
if (!withdrawal) return null;
// 解析账户信息
let accountInfoDisplay = '-';
if (withdrawal.accountInfo) {
try {
const info = typeof withdrawal.accountInfo === 'string'
? JSON.parse(withdrawal.accountInfo)
: withdrawal.accountInfo;
if (withdrawal.withdrawType === 1) {
accountInfoDisplay = `微信OpenID: ${info.openid || '-'}`;
} else {
accountInfoDisplay = `${info.bankName || '-'} ${info.bankAccount || '-'}`;
}
} catch {
accountInfoDisplay = withdrawal.accountInfo as string;
}
}
const statusInfo = WithdrawalStatusMap[withdrawal.status];
const canAudit = withdrawal.status === WithdrawalStatusEnum.PENDING;
return (
<ModalForm<WithdrawalAuditFormValues>
title={canAudit ? '提现审核' : '提现详情'}
visible={visible}
onVisibleChange={onVisibleChange}
onFinish={canAudit ? onFinish : async () => { onVisibleChange(false); return true; }}
modalProps={{ destroyOnClose: true }}
width={600}
submitter={canAudit ? undefined : { submitButtonProps: { children: '关闭' }, resetButtonProps: { style: { display: 'none' } } }}
>
<Descriptions column={2} bordered size="small">
<Descriptions.Item label="提现单号">{withdrawal.withdrawNo}</Descriptions.Item>
<Descriptions.Item label="当前状态">
<Tag color={statusInfo?.color || 'default'}>{statusInfo?.text || '未知'}</Tag>
</Descriptions.Item>
<Descriptions.Item label="导游编号">{withdrawal.guideNo || '-'}</Descriptions.Item>
<Descriptions.Item label="导游姓名">{withdrawal.guideName || '-'}</Descriptions.Item>
<Descriptions.Item label="提现金额">
<span style={{ color: '#ff4d4f', fontWeight: 'bold', fontSize: 16 }}>
¥{(withdrawal.amount / 100).toFixed(2)}
</span>
</Descriptions.Item>
<Descriptions.Item label="手续费">¥{(withdrawal.fee / 100).toFixed(2)}</Descriptions.Item>
<Descriptions.Item label="实际到账">
<span style={{ color: '#52c41a', fontWeight: 'bold' }}>
¥{((withdrawal.actualAmount ?? withdrawal.amount - withdrawal.fee) / 100).toFixed(2)}
</span>
</Descriptions.Item>
<Descriptions.Item label="提现方式">
{WithdrawTypeMap[withdrawal.withdrawType] || '未知'}
</Descriptions.Item>
<Descriptions.Item label="收款账户" span={2}>{accountInfoDisplay}</Descriptions.Item>
<Descriptions.Item label="申请时间" span={2}>{withdrawal.applyTime || '-'}</Descriptions.Item>
{withdrawal.auditTime && (
<Descriptions.Item label="审核时间" span={2}>{withdrawal.auditTime}</Descriptions.Item>
)}
{withdrawal.auditRemark && (
<Descriptions.Item label="审核备注" span={2}>{withdrawal.auditRemark}</Descriptions.Item>
)}
{withdrawal.transferNo && (
<Descriptions.Item label="转账单号" span={2}>{withdrawal.transferNo}</Descriptions.Item>
)}
{withdrawal.failReason && (
<Descriptions.Item label="失败原因" span={2}>{withdrawal.failReason}</Descriptions.Item>
)}
</Descriptions>
{canAudit && (
<>
<Divider />
<ProFormRadio.Group
name="approved"
label="审核结果"
rules={[{ required: true, message: '请选择审核结果' }]}
options={[
{ label: '通过', value: true },
{ label: '拒绝', value: false },
]}
/>
<ProFormTextArea
name="auditRemark"
label="审核备注"
placeholder="请输入审核备注(可选)"
fieldProps={{ rows: 3 }}
/>
</>
)}
</ModalForm>
);
};
export default WithdrawalAuditModal;
@@ -0,0 +1,257 @@
import React, { useRef, useState } from 'react';
import { ProTable, type ActionType } from '@ant-design/pro-components';
import { Space, Tag, message, Dropdown, Row, Col, Form, Select } from 'antd';
import { GlassCard, GradientButton } from '@/components/ui';
import { DownOutlined } from '@ant-design/icons';
import {
guideApi,
GuideWithdrawal,
WithdrawalStatusEnum,
WithdrawalStatusMap,
WithdrawTypeMap,
} from '@/services/guide';
import WithdrawalAuditModal, { WithdrawalAuditFormValues } from './WithdrawalAuditModal';
import TransferConfirmModal from './TransferConfirmModal';
import TransferFailedModal from './TransferFailedModal';
interface WithdrawalTabProps {
params: Record<string, any>;
currentUserId: number;
}
const WithdrawalTab: React.FC<WithdrawalTabProps> = ({ params: baseParams, currentUserId }) => {
const [params, setParams] = useState<Record<string, any>>(baseParams);
const [auditOpen, setAuditOpen] = useState(false);
const [transferOpen, setTransferOpen] = useState(false);
const [failedOpen, setFailedOpen] = useState(false);
const [current, setCurrent] = useState<GuideWithdrawal | undefined>(undefined);
const actionRef = useRef<ActionType>();
// 当外部 params 变化时更新
React.useEffect(() => {
setParams((prev) => ({ ...prev, ...baseParams }));
actionRef.current?.reload();
}, [baseParams.tenantId, baseParams.includeChildren]);
const columns: any[] = [
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 },
{ title: '提现单号', dataIndex: 'withdrawNo', width: 150, copyable: true },
{ title: '导游编号', dataIndex: 'guideNo', width: 120 },
{ title: '导游姓名', dataIndex: 'guideName', width: 100 },
{
title: '提现金额',
dataIndex: 'amount',
width: 110,
render: (v: number) => <span style={{ color: '#ff4d4f', fontWeight: 'bold' }}>¥{(v / 100).toFixed(2)}</span>,
},
{
title: '手续费',
dataIndex: 'fee',
width: 90,
render: (v: number) => `¥${(v / 100).toFixed(2)}`,
},
{
title: '实际到账',
dataIndex: 'actualAmount',
width: 110,
render: (v: number, record: GuideWithdrawal) => {
const amount = v ?? (record.amount - record.fee);
return <span style={{ color: '#52c41a', fontWeight: 'bold' }}>¥{(amount / 100).toFixed(2)}</span>;
},
},
{
title: '提现方式',
dataIndex: 'withdrawType',
width: 100,
render: (v: number) => WithdrawTypeMap[v] || '未知',
},
{
title: '状态',
dataIndex: 'status',
width: 100,
render: (v: number) => {
const status = WithdrawalStatusMap[v];
return <Tag color={status?.color || 'default'}>{status?.text || '未知'}</Tag>;
},
},
{ title: '申请时间', dataIndex: 'applyTime', valueType: 'dateTime', width: 160 },
{ title: '审核时间', dataIndex: 'auditTime', valueType: 'dateTime', width: 160 },
{ title: '审核备注', dataIndex: 'auditRemark', width: 120, ellipsis: true },
{ title: '转账单号', dataIndex: 'transferNo', width: 140, copyable: true },
{ title: '失败原因', dataIndex: 'failReason', width: 120, ellipsis: true },
{
title: '操作',
key: 'action',
width: 120,
fixed: 'right',
render: (_: any, record: GuideWithdrawal) => {
const menuItems = [];
if (record.status === WithdrawalStatusEnum.PENDING) {
menuItems.push({
key: 'audit',
label: '审核',
onClick: () => {
setCurrent(record);
setAuditOpen(true);
},
});
}
if (record.status === WithdrawalStatusEnum.APPROVED ||
record.status === WithdrawalStatusEnum.TRANSFERRING) {
menuItems.push({
key: 'transfer',
label: '确认打款',
onClick: () => {
setCurrent(record);
setTransferOpen(true);
},
});
menuItems.push({
key: 'failed',
label: '打款失败',
danger: true,
onClick: () => {
setCurrent(record);
setFailedOpen(true);
},
});
}
if (menuItems.length === 0) {
return (
<a onClick={() => { setCurrent(record); setAuditOpen(true); }}>查看</a>
);
}
return (
<Space>
<a onClick={() => { setCurrent(record); setAuditOpen(true); }}>查看</a>
<Dropdown menu={{ items: menuItems }}>
<a onClick={(e) => e.preventDefault()}>
操作 <DownOutlined />
</a>
</Dropdown>
</Space>
);
},
},
];
return (
<>
<Row style={{ marginBottom: 16 }} gutter={16} align="middle">
<Col flex="auto">
<Form
layout="inline"
onFinish={(values) => {
setParams((prev) => ({ ...prev, ...values }));
actionRef.current?.reload();
}}
>
<Form.Item name="withdrawNo" label="提现单号">
<input placeholder="请输入提现单号" style={{ width: 150, padding: '4px 8px', border: '1px solid #d9d9d9', borderRadius: 4 }} />
</Form.Item>
<Form.Item name="guideNo" label="导游编号">
<input placeholder="请输入导游编号" style={{ width: 150, padding: '4px 8px', border: '1px solid #d9d9d9', borderRadius: 4 }} />
</Form.Item>
<Form.Item name="status" label="状态">
<Select placeholder="全部" style={{ width: 120 }} allowClear>
<Select.Option value={WithdrawalStatusEnum.PENDING}>待审核</Select.Option>
<Select.Option value={WithdrawalStatusEnum.APPROVED}>审核通过</Select.Option>
<Select.Option value={WithdrawalStatusEnum.REJECTED}>审核拒绝</Select.Option>
<Select.Option value={WithdrawalStatusEnum.COMPLETED}>已到账</Select.Option>
<Select.Option value={WithdrawalStatusEnum.FAILED}>打款失败</Select.Option>
</Select>
</Form.Item>
<Form.Item>
<GradientButton type="primary" htmlType="submit" size="small">查询</GradientButton>
</Form.Item>
</Form>
</Col>
</Row>
<GlassCard>
{params?.tenantId ? (
<ProTable<GuideWithdrawal>
rowKey="id"
actionRef={actionRef}
params={params}
request={(p) => guideApi.getWithdrawalList({ ...(p as any), ...params })}
columns={columns}
search={false}
scroll={{ x: 1600 }}
pagination={{ showSizeChanger: true, showQuickJumper: true }}
toolBarRender={false}
/>
) : null}
</GlassCard>
<WithdrawalAuditModal
visible={auditOpen}
onVisibleChange={setAuditOpen}
withdrawal={current}
onFinish={async (values: WithdrawalAuditFormValues) => {
if (!current) return false;
const hide = message.loading('处理中...');
try {
await guideApi.auditWithdrawal(current.id, currentUserId, values);
message.success('审核完成');
actionRef.current?.reload();
return true;
} catch {
message.error('审核失败');
return false;
} finally {
hide();
}
}}
/>
<TransferConfirmModal
visible={transferOpen}
onVisibleChange={setTransferOpen}
withdrawal={current}
onFinish={async (values) => {
if (!current) return false;
const hide = message.loading('处理中...');
try {
await guideApi.confirmTransfer(current.id, values.transferNo);
message.success('打款确认成功');
actionRef.current?.reload();
return true;
} catch {
message.error('操作失败');
return false;
} finally {
hide();
}
}}
/>
<TransferFailedModal
visible={failedOpen}
onVisibleChange={setFailedOpen}
withdrawal={current}
onFinish={async (values) => {
if (!current) return false;
const hide = message.loading('处理中...');
try {
await guideApi.transferFailed(current.id, values.failReason);
message.success('已记录失败');
actionRef.current?.reload();
return true;
} catch {
message.error('操作失败');
return false;
} finally {
hide();
}
}}
/>
</>
);
};
export default WithdrawalTab;
@@ -0,0 +1,327 @@
import React, { useEffect, useRef, useState } from 'react';
import { PageContainer, ProFormText, ProFormSelect, ProTable, type ActionType } from '@ant-design/pro-components';
import { Popconfirm, Space, Tag, message, Dropdown, Tabs } from 'antd';
import { ActionBar, GlassCard, GradientButton, SearchBarPlus } from '@/components/ui';
import { PlusOutlined, DownOutlined } from '@ant-design/icons';
import {
guideApi,
GuideProfile,
GuideStatusEnum,
GuideStatusMap,
} from '@/services/guide';
import { tenantApi } from '@/services/tenant';
import GuideForm, { GuideFormValues } from './components/GuideForm';
import GuideAuditModal, { GuideAuditFormValues } from './components/GuideAuditModal';
import CommissionRateModal from './components/CommissionRateModal';
import CommissionTab from './components/CommissionTab';
import WithdrawalTab from './components/WithdrawalTab';
const GuidePage: React.FC = () => {
const [createOpen, setCreateOpen] = useState(false);
const [auditOpen, setAuditOpen] = useState(false);
const [rateOpen, setRateOpen] = useState(false);
const [current, setCurrent] = useState<GuideProfile | undefined>(undefined);
const [params, setParams] = useState<Record<string, any>>({});
const [currentUserId, setCurrentUserId] = useState<number>(0);
const [activeTab, setActiveTab] = useState('guide');
const actionRef = useRef<ActionType>();
// 首次进入时,默认按"当前租户 + 包含下级租户"查询
useEffect(() => {
(async () => {
try {
let tenantId: string | undefined;
const cur: any = await tenantApi.getCurrentTenant();
tenantId = cur?.data?.tenantId ?? cur?.tenantId;
const userId = cur?.data?.userId ?? cur?.userId ?? 0;
setCurrentUserId(userId);
if (!tenantId) {
const stats: any = await tenantApi.getScopeStats();
tenantId = stats?.data?.currentTenantId ?? stats?.currentTenantId;
}
if (tenantId) setParams((prev) => ({ ...(prev || {}), tenantId, includeChildren: true }));
} catch {
// 忽略错误
}
})();
}, []);
const handleStatusChange = async (guide: GuideProfile, newStatus: number) => {
const hide = message.loading('处理中...');
try {
await guideApi.updateGuideStatus(guide.id, newStatus);
message.success('状态更新成功');
actionRef.current?.reload();
} catch {
message.error('状态更新失败');
} finally {
hide();
}
};
const columns: any[] = [
{ dataIndex: 'index', valueType: 'indexBorder', width: 48 },
{ title: '导游编号', dataIndex: 'guideNo', width: 120 },
{ title: '导游姓名', dataIndex: 'guideName', width: 100 },
{ title: '联系电话', dataIndex: 'guidePhone', width: 120 },
{
title: '身份证号',
dataIndex: 'idCard',
width: 150,
render: (v: string) => v ? `${v.substring(0, 6)}****${v.substring(14)}` : '-',
},
{
title: '状态',
dataIndex: 'status',
width: 90,
render: (v: number) => {
const status = GuideStatusMap[v];
return <Tag color={status?.color || 'default'}>{status?.text || '未知'}</Tag>;
},
},
{
title: '佣金比例',
dataIndex: 'commissionRate',
width: 100,
render: (v: number) => `${v}%`,
},
{
title: '累计佣金',
dataIndex: 'totalCommission',
width: 100,
render: (v: number) => `¥${(v / 100).toFixed(2)}`,
},
{
title: '可提现',
dataIndex: 'availableCommission',
width: 100,
render: (v: number) => <span style={{ color: '#52c41a' }}>¥{(v / 100).toFixed(2)}</span>,
},
{
title: '已提现',
dataIndex: 'withdrawnCommission',
width: 100,
render: (v: number) => `¥${(v / 100).toFixed(2)}`,
},
{ title: '创建时间', dataIndex: 'createTime', valueType: 'dateTime', width: 160 },
{
title: '操作',
key: 'action',
width: 180,
fixed: 'right',
render: (_: any, record: GuideProfile) => {
const menuItems = [];
// 待审核状态显示审核按钮
if (record.status === GuideStatusEnum.PENDING) {
menuItems.push({
key: 'audit',
label: '审核',
onClick: () => {
setCurrent(record);
setAuditOpen(true);
},
});
}
// 正常状态可以禁用
if (record.status === GuideStatusEnum.NORMAL) {
menuItems.push({
key: 'disable',
label: '禁用',
onClick: () => handleStatusChange(record, GuideStatusEnum.DISABLED),
});
}
// 禁用状态可以启用
if (record.status === GuideStatusEnum.DISABLED) {
menuItems.push({
key: 'enable',
label: '启用',
onClick: () => handleStatusChange(record, GuideStatusEnum.NORMAL),
});
}
// 设置佣金比例
menuItems.push({
key: 'rate',
label: '设置佣金',
onClick: () => {
setCurrent(record);
setRateOpen(true);
},
});
return (
<Space>
<a onClick={() => {
setCurrent(record);
setAuditOpen(true);
}}>查看</a>
{menuItems.length > 0 && (
<Dropdown menu={{ items: menuItems }}>
<a onClick={(e) => e.preventDefault()}>
更多 <DownOutlined />
</a>
</Dropdown>
)}
</Space>
);
},
},
];
// 导游列表Tab内容
const GuideListTab = (
<>
<SearchBarPlus
defaultCollapsed
split
span={6}
hideReset
onTenantChanged={(tenantId, includeChildren) => {
setParams((prev) => ({ ...(prev || {}), tenantId, includeChildren }));
actionRef.current?.reload();
}}
onFinish={async (values) => {
setParams((prev) => ({ ...(prev || {}), ...values }));
actionRef.current?.reload();
}}
>
<ProFormText name="guideName" label="导游姓名" placeholder="请输入导游姓名" />
<ProFormText name="guideNo" label="导游编号" placeholder="请输入导游编号" />
<ProFormSelect
name="status"
label="状态"
placeholder="请选择状态"
options={[
{ label: '全部', value: '' },
{ label: '待审核', value: GuideStatusEnum.PENDING },
{ label: '正常', value: GuideStatusEnum.NORMAL },
{ label: '禁用', value: GuideStatusEnum.DISABLED },
{ label: '审核拒绝', value: GuideStatusEnum.REJECTED },
]}
/>
</SearchBarPlus>
<ActionBar
left={
<GradientButton size="middle" type="primary" icon={<PlusOutlined />} onClick={() => setCreateOpen(true)}>
新增导游
</GradientButton>
}
/>
<GlassCard>
{params?.tenantId ? (
<ProTable<GuideProfile>
rowKey="id"
actionRef={actionRef}
params={params}
request={(p) => guideApi.getGuideList({ ...(p as any), ...params })}
columns={columns}
search={false}
scroll={{ x: 1400 }}
pagination={{ showSizeChanger: true, showQuickJumper: true }}
toolBarRender={false}
/>
) : null}
</GlassCard>
</>
);
const tabItems = [
{
key: 'guide',
label: '导游列表',
children: GuideListTab,
},
{
key: 'commission',
label: '佣金明细',
children: <CommissionTab params={params} />,
},
{
key: 'withdrawal',
label: '提现审核',
children: <WithdrawalTab params={params} currentUserId={currentUserId} />,
},
];
return (
<PageContainer header={{ title: '导游管理' }}>
<Tabs
activeKey={activeTab}
onChange={setActiveTab}
items={tabItems}
size="large"
style={{ marginBottom: 16 }}
/>
<GuideForm
title="新增导游"
visible={createOpen}
onVisibleChange={setCreateOpen}
onFinish={async (values: GuideFormValues) => {
const hide = message.loading('保存中...');
try {
await guideApi.createGuide(values);
message.success('新增成功');
actionRef.current?.reload();
return true;
} catch {
message.error('新增失败');
return false;
} finally {
hide();
}
}}
/>
<GuideAuditModal
visible={auditOpen}
onVisibleChange={setAuditOpen}
guide={current}
onFinish={async (values: GuideAuditFormValues) => {
if (!current) return false;
const hide = message.loading('处理中...');
try {
await guideApi.auditGuide(current.id, values);
message.success('审核完成');
actionRef.current?.reload();
return true;
} catch {
message.error('审核失败');
return false;
} finally {
hide();
}
}}
/>
<CommissionRateModal
visible={rateOpen}
onVisibleChange={setRateOpen}
guide={current}
onFinish={async (values) => {
if (!current) return false;
const hide = message.loading('保存中...');
try {
await guideApi.setCommissionRate(current.id, values.commissionRate);
message.success('设置成功');
actionRef.current?.reload();
return true;
} catch {
message.error('设置失败');
return false;
} finally {
hide();
}
}}
/>
</PageContainer>
);
};
export default GuidePage;
@@ -1,8 +1,10 @@
import React, { useEffect, useState } from 'react';
import { ModalForm, ProForm, ProFormDigit, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
import { TreeSelect, Checkbox } from 'antd';
import { ordersApi } from '@/services/orders';
import { deviceApi } from '@/services/device';
import { miniAppApi } from '@/services/miniapp';
import { tenantApi } from '@/services/tenant';
import type { QrcodeItem } from './QrcodeItem';
export interface QrcodeTourismFormProps {
@@ -34,32 +36,112 @@ const QrcodeTourismForm: React.FC<QrcodeTourismFormProps> = ({ open, title, init
? (Object.fromEntries(Object.entries(initialValues).filter(([, v]) => v !== undefined)) as any)
: {};
// 景区ID,用于素材查询
const tourismIdForFetch = (sanitizedInitial as any)?.tourismId ?? defaultTourismId;
// 判断是否为编辑模式
const isEditMode = !!(initialValues?.id);
const initialFileIds: number[] = (initialValues as any)?.tourismFileIds || [];
// 景区素材
// 租户树数据
interface TenantNode {
tenantId?: string;
tenantName?: string;
children?: TenantNode[];
}
const [tenantTree, setTenantTree] = useState<TenantNode[]>([]);
const [selectedTenantId, setSelectedTenantId] = useState<string | undefined>();
const [includeChildren, setIncludeChildren] = useState<boolean>(true);
// 景区素材(查询结果)
const [tourismFiles, setTourismFiles] = useState<any[]>([]);
const [loadingFiles, setLoadingFiles] = useState(false);
// 编辑模式:已选素材详情(用于初始显示)
const [selectedFiles, setSelectedFiles] = useState<any[]>([]);
// 弹窗关闭时重置状态
useEffect(() => {
// 仅在弹窗打开时才加载景区素材,避免在列表页无意义调用接口
if (!open) return;
if (!tourismIdForFetch) {
if (!open) {
setSelectedTenantId(undefined);
setTourismFiles([]);
setSelectedFiles([]);
}
}, [open]);
// 加载租户树(新增和编辑都需要)
useEffect(() => {
if (!open) return;
(async () => {
try {
const treeRes: any = await tenantApi.getAccessibleTenants();
let list: TenantNode[] = [];
if (Array.isArray(treeRes)) list = treeRes;
else if (Array.isArray(treeRes?.data)) list = treeRes.data;
setTenantTree(list || []);
} catch {
setTenantTree([]);
}
})();
}, [open]);
// 编辑模式:加载已选择的素材详情(仅用于初始显示)
useEffect(() => {
if (!open || !isEditMode || initialFileIds.length === 0) {
setSelectedFiles([]);
return;
}
let canceled = false;
(async () => {
try {
const { data = [] } = await ordersApi.tourismFileByTourism(tourismIdForFetch as any);
if (!canceled) setTourismFiles(Array.isArray(data) ? data : []);
// 直接根据ID列表查询,避免加载全部素材
const { data = [] } = await ordersApi.tourismFilesByIds(initialFileIds);
if (!canceled) setSelectedFiles(data || []);
} catch {
if (!canceled) setTourismFiles([]);
if (!canceled) setSelectedFiles([]);
}
})();
return () => {
canceled = true;
};
}, [open, tourismIdForFetch]);
return () => { canceled = true; };
}, [open, isEditMode, initialFileIds.join(',')]);
// 根据选择的租户加载景区素材(新增和编辑都可用)
useEffect(() => {
if (!open) return;
if (!selectedTenantId) {
setTourismFiles([]);
return;
}
let canceled = false;
(async () => {
setLoadingFiles(true);
try {
const { data = [] } = await ordersApi.tourismFilesGroupedByTenant({
tenantId: selectedTenantId,
includeChildren,
current: 1,
pageSize: 1000,
});
// data 是按景区分组的,需要展开为平铺列表
const allFiles: any[] = [];
(data || []).forEach((g: any) => {
(g.files || []).forEach((f: any) => {
allFiles.push({ ...f, tourismName: g.tourismName, tourismId: g.tourismId });
});
});
if (!canceled) setTourismFiles(allFiles);
} catch {
if (!canceled) setTourismFiles([]);
} finally {
if (!canceled) setLoadingFiles(false);
}
})();
return () => { canceled = true; };
}, [open, selectedTenantId, includeChildren]);
// 租户树转换为 TreeSelect 数据格式
const toTreeData = (nodes?: TenantNode[]): any[] =>
(nodes || []).map((n) => ({
title: n.tenantName && n.tenantId ? `${n.tenantName} (${n.tenantId})` : (n.tenantName || n.tenantId || '-'),
value: n.tenantId,
key: n.tenantId,
children: n.children ? toTreeData(n.children) : undefined,
}));
// 景区素材类型字典(按业务提供)
const TYPE_LABEL: Record<number, string> = {
@@ -268,90 +350,143 @@ const QrcodeTourismForm: React.FC<QrcodeTourismFormProps> = ({ open, title, init
<div />
</ProForm.Item>
{/* 景区素材(移除查询条件;支持多选;无上限;保留“全部选择/取消选择”) */}
<ProForm.Item label="景区素材" shouldUpdate>
{({ getFieldValue, setFieldsValue }) => {
const selected: number[] = getFieldValue('tourismFileIds') || [];
if (!tourismIdForFetch) {
return <div style={{ color: '#999' }}>请选择景区后加载素材</div>;
}
{/* 景区素材(按租户筛选;支持多选;无上限;保留"全部选择/取消选择") */}
<div style={{ gridColumn: '1 / -1' }}>
<ProForm.Item label="景区素材" shouldUpdate>
{({ getFieldValue, setFieldsValue }) => {
const selected: number[] = getFieldValue('tourismFileIds') || [];
const queryList = tourismFiles || [];
// 不再提供筛选与上限;全量展示可选择
const list = tourismFiles || [];
const onToggle = (id: number) => {
const exists = selected.includes(id);
setFieldsValue?.({ tourismFileIds: exists ? selected.filter((x) => x !== id) : [...selected, id] });
};
const onToggle = (id: number) => {
const exists = selected.includes(id);
setFieldsValue?.({ tourismFileIds: exists ? selected.filter((x) => x !== id) : [...selected, id] });
};
const selectAll = () => {
const ids = (queryList.map((f: any) => f?.id).filter(Boolean) as number[]);
const next = Array.from(new Set([...selected, ...ids]));
setFieldsValue?.({ tourismFileIds: next });
};
const selectAll = () => {
const ids = (list.map((f: any) => f?.id).filter(Boolean) as number[]);
const next = Array.from(new Set(ids));
setFieldsValue?.({ tourismFileIds: next });
};
const clearAll = () => setFieldsValue?.({ tourismFileIds: [] });
const clearAll = () => setFieldsValue?.({ tourismFileIds: [] });
return (
<div>
{/* 操作:全部选择 / 取消选择(左对齐,与“景区素材”同起点) */}
<div style={{ display: 'flex', gap: 12, alignItems: 'center', marginBottom: 8 }}>
<button type="button" onClick={selectAll} style={{ padding: '4px 10px', border: '1px solid #52c41a', background: '#52c41a', color: '#fff', borderRadius: 4, cursor: 'pointer' }}>全部选择</button>
<button type="button" onClick={clearAll} style={{ padding: '4px 10px', border: '1px solid #52c41a', background: '#fff', color: '#52c41a', borderRadius: 4, cursor: 'pointer' }}>取消选择</button>
</div>
{/* 统计信息 */}
<div style={{ marginBottom: 8, fontSize: 12, color: '#666' }}>
已选{selected.length} 个;共{list.length} 个
</div>
{/* 网格容器:自适应列 + 滚动 */}
<div style={{ maxHeight: 420, overflow: 'auto', padding: 8, background: '#fafafa', border: '1px solid #f0f0f0', borderRadius: 6 }}>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(140px, 1fr))', gap: 12 }}>
{list.map((f: any) => {
const id = f?.id;
const url = f?.imageUrl || f?.linkUrl || f?.url;
const isSel = selected.includes(id);
return (
<div
key={id}
onClick={() => onToggle(id)}
style={{
borderWidth: 2,
borderStyle: 'solid',
borderColor: isSel ? '#52c41a' : '#f0f0f0',
borderRadius: 6,
cursor: 'pointer',
background: '#fff',
boxShadow: isSel ? '0 0 0 2px rgba(82,196,26,0.12) inset' : 'none',
overflow: 'hidden',
display: 'flex',
flexDirection: 'column',
}}
>
<div style={{ position: 'relative', width: '100%', aspectRatio: '4 / 3', background: '#fafafa', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
{url ? (
<img src={url} alt={'素材-' + id} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
) : (
<div style={{ fontSize: 12, color: '#999' }}>无图片</div>
)}
{isSel ? (
<div style={{ position: 'absolute', top: 6, right: 6, width: 18, height: 18, borderRadius: '50%', background: '#52c41a' }} />
) : null}
</div>
<div style={{ padding: '6px 8px', fontSize: 12, color: '#555', display: 'flex', justifyContent: 'space-between' }}>
<span>ID:{id}</span>
<span style={{ color: '#888' }}>{typeName(f?.type)}</span>
</div>
// 渲染素材卡片
const renderCard = (f: any, canClick: boolean = true) => {
const id = f?.id;
const url = f?.imageUrl || f?.linkUrl || f?.url;
const isSel = selected.includes(id);
return (
<div
key={id}
onClick={canClick ? () => onToggle(id) : undefined}
style={{
borderWidth: 2,
borderStyle: 'solid',
borderColor: isSel ? '#52c41a' : '#f0f0f0',
borderRadius: 6,
cursor: canClick ? 'pointer' : 'default',
background: '#fff',
boxShadow: isSel ? '0 0 0 2px rgba(82,196,26,0.12) inset' : 'none',
overflow: 'hidden',
display: 'flex',
flexDirection: 'column',
}}
>
<div style={{ position: 'relative', width: '100%', aspectRatio: '4 / 3', background: '#fafafa', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
{url ? (
<img src={url} alt={'素材-' + id} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
) : (
<div style={{ fontSize: 12, color: '#999' }}>无图片</div>
)}
{isSel && (
<div style={{ position: 'absolute', top: 6, right: 6, width: 18, height: 18, borderRadius: '50%', background: '#52c41a' }} />
)}
</div>
<div style={{ padding: '6px 8px', fontSize: 12, color: '#555' }}>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<span>ID:{id}</span>
<span style={{ color: '#888' }}>{typeName(f?.type)}</span>
</div>
{f?.tourismName && (
<div style={{ color: '#1890ff', fontSize: 11, marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} title={f.tourismName}>
{f.tourismName}
</div>
);
})}
)}
</div>
</div>
);
};
return (
<div>
{/* 编辑模式:显示已选素材(可点击取消选择) */}
{isEditMode && selectedFiles.length > 0 && (
<div style={{ marginBottom: 16 }}>
<div style={{ marginBottom: 8, fontSize: 13, fontWeight: 500, color: '#333' }}>
已选素材(点击可取消选择)
</div>
<div style={{ maxHeight: 200, overflow: 'auto', padding: 8, background: '#f6ffed', border: '1px solid #b7eb8f', borderRadius: 6 }}>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(120px, 1fr))', gap: 10 }}>
{selectedFiles.map((f: any) => renderCard(f, true))}
</div>
</div>
</div>
)}
{/* 租户筛选条件 */}
<div style={{ display: 'flex', gap: 12, alignItems: 'center', marginBottom: 12, flexWrap: 'wrap' }}>
<TreeSelect
style={{ minWidth: 260 }}
showSearch
treeNodeFilterProp="title"
dropdownStyle={{ maxHeight: 400, overflow: 'auto', zIndex: 9999 }}
placeholder="选择租户加载素材"
value={selectedTenantId}
onChange={(val) => setSelectedTenantId(val)}
treeData={toTreeData(tenantTree)}
allowClear
/>
<Checkbox checked={includeChildren} onChange={(e) => setIncludeChildren(e.target.checked)}>包含子租户</Checkbox>
</div>
{/* 未选择租户时的提示 */}
{!selectedTenantId && (
<div style={{ color: '#999', padding: 16, background: '#fafafa', borderRadius: 6, textAlign: 'center' }}>
请选择租户以加载更多景区素材
</div>
)}
{/* 选择租户后显示素材列表 */}
{selectedTenantId && (
<>
{/* 操作按钮 */}
<div style={{ display: 'flex', gap: 12, alignItems: 'center', marginBottom: 8 }}>
<button type="button" onClick={selectAll} style={{ padding: '4px 10px', border: '1px solid #52c41a', background: '#52c41a', color: '#fff', borderRadius: 4, cursor: 'pointer' }}>全部选择</button>
<button type="button" onClick={clearAll} style={{ padding: '4px 10px', border: '1px solid #52c41a', background: '#fff', color: '#52c41a', borderRadius: 4, cursor: 'pointer' }}>取消全部</button>
</div>
{/* 统计信息 */}
<div style={{ marginBottom: 8, fontSize: 12, color: '#666' }}>
已选 {selected.length} 个;当前租户下共 {queryList.length} 个{loadingFiles && ' (加载中...)'}
</div>
{/* 素材网格 */}
<div style={{ maxHeight: 420, overflow: 'auto', padding: 8, background: '#fafafa', border: '1px solid #f0f0f0', borderRadius: 6 }}>
{queryList.length === 0 && !loadingFiles ? (
<div style={{ color: '#999', textAlign: 'center', padding: 20 }}>该租户下暂无景区素材</div>
) : (
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(140px, 1fr))', gap: 12 }}>
{queryList.map((f: any) => renderCard(f, true))}
</div>
)}
</div>
</>
)}
</div>
</div>
);
}}
</ProForm.Item>
);
}}
</ProForm.Item>
</div>
</ModalForm>
);
};
@@ -55,7 +55,10 @@ const TourismFilePage: React.FC = () => {
setLoading(true);
try {
const res = await ordersApi.tourismFilesGroupedByTenant(params as any);
setGroups(Array.isArray((res as any)?.data) ? (res as any).data : []);
const allGroups = Array.isArray((res as any)?.data) ? (res as any).data : [];
// 过滤掉没有素材的景区
const filteredGroups = allGroups.filter((g: any) => g.files && g.files.length > 0);
setGroups(filteredGroups);
setPagination((p) => ({ ...p, total: Number((res as any)?.total || 0) }));
} catch (e) {
setGroups([]);