feat: 可视化大屏展示
This commit is contained in:
@@ -0,0 +1,91 @@
|
||||
import './global.less';
|
||||
import React from 'react';
|
||||
import { ThemeProvider } from './theme';
|
||||
import { history } from 'umi';
|
||||
import { clearTenantCache, ensureTenantCacheTokenGuard } from '@/utils/tenantCache';
|
||||
|
||||
export function rootContainer(container: React.ReactNode, _args?: any) {
|
||||
return React.createElement(ThemeProvider, null, container);
|
||||
}
|
||||
|
||||
const API_PREFIX = process.env.API_PREFIX || '';
|
||||
export const request: any = {
|
||||
prefix: API_PREFIX,
|
||||
errorConfig: {
|
||||
errorHandler(error: any) {
|
||||
try {
|
||||
const status = (error?.response?.status ?? error?.data?.code ?? error?.data?.resp_code) as number | undefined;
|
||||
const unauthorized = status === 401 || status === 403;
|
||||
if (unauthorized) {
|
||||
try {
|
||||
sessionStorage.removeItem('access_token');
|
||||
sessionStorage.removeItem('current_user');
|
||||
clearTenantCache();
|
||||
} catch {}
|
||||
const pathname = typeof window !== 'undefined' ? window.location.pathname : '/';
|
||||
const search = typeof window !== 'undefined' ? window.location.search : '';
|
||||
const current = encodeURIComponent(`${pathname}${search}`);
|
||||
const to = `/user/login?redirect=${current}`;
|
||||
if (!String(pathname).startsWith('/user/login')) {
|
||||
history.push(to);
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
throw error;
|
||||
},
|
||||
},
|
||||
requestInterceptors: [
|
||||
(url: string, options: any) => {
|
||||
const token = sessionStorage.getItem('access_token');
|
||||
const headers: Record<string, string> = { ...(options?.headers as any) };
|
||||
if (token) headers['Authorization'] = `Bearer ${token}`;
|
||||
ensureTenantCacheTokenGuard();
|
||||
return { url, options: { ...options, headers } };
|
||||
},
|
||||
],
|
||||
responseInterceptors: [
|
||||
async (response: Response) => {
|
||||
try {
|
||||
const cloned = response.clone();
|
||||
const data = await cloned.json();
|
||||
if (data && typeof (data as any).resp_code !== 'undefined') {
|
||||
const mapped = {
|
||||
success: (data as any).resp_code === 0,
|
||||
code: (data as any).resp_code,
|
||||
msg: (data as any).resp_msg,
|
||||
data: (data as any).data,
|
||||
} as any;
|
||||
(response as any).data = mapped;
|
||||
}
|
||||
const httpUnauthorized = (response.status === 401 || response.status === 403);
|
||||
const bizCode = (data?.resp_code ?? data?.code) as number | undefined;
|
||||
const bizUnauthorized = bizCode === 401 || bizCode === 403 || bizCode === 40101 || bizCode === 40100;
|
||||
if (httpUnauthorized || bizUnauthorized) {
|
||||
try {
|
||||
sessionStorage.removeItem('access_token');
|
||||
sessionStorage.removeItem('current_user');
|
||||
clearTenantCache();
|
||||
} catch {}
|
||||
const pathname = typeof window !== 'undefined' ? window.location.pathname : '/';
|
||||
const search = typeof window !== 'undefined' ? window.location.search : '';
|
||||
const current = encodeURIComponent(`${pathname}${search}`);
|
||||
const to = `/user/login?redirect=${current}`;
|
||||
if (!String(pathname).startsWith('/user/login')) {
|
||||
history.push(to);
|
||||
}
|
||||
}
|
||||
} catch (e) {}
|
||||
return response;
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
export function onRouteChange({ location }: any) {
|
||||
try {
|
||||
const token = sessionStorage.getItem('access_token');
|
||||
const isLoginPath = String(location?.pathname || '').startsWith('/user/login');
|
||||
if (!token && !isLoginPath) {
|
||||
history.push('/user/login');
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 3.6 KiB |
@@ -0,0 +1,36 @@
|
||||
import React from 'react';
|
||||
import { Spin } from 'antd';
|
||||
import { LoadingOutlined } from '@ant-design/icons';
|
||||
|
||||
const PageLoading: React.FC = () => {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
height: '100vh',
|
||||
background: '#0a0e27',
|
||||
color: '#ffffff'
|
||||
}}
|
||||
>
|
||||
<div style={{ textAlign: 'center' }}>
|
||||
<Spin
|
||||
indicator={<LoadingOutlined style={{ fontSize: 32, color: '#00d4ff' }} spin />}
|
||||
size="large"
|
||||
/>
|
||||
<div
|
||||
style={{
|
||||
marginTop: 16,
|
||||
fontSize: 16,
|
||||
color: '#8b9dc3'
|
||||
}}
|
||||
>
|
||||
正在加载...
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default PageLoading;
|
||||
@@ -0,0 +1,113 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { Space, Button, TreeSelect, Checkbox, message } from 'antd';
|
||||
import { tenantApi } from '@/services/tenant';
|
||||
|
||||
interface TenantNode {
|
||||
tenantId?: string;
|
||||
tenantName?: string;
|
||||
children?: TenantNode[];
|
||||
status?: number | boolean;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
onChanged?: (tenantId: string, includeChildren: boolean) => void;
|
||||
useSwitchTenant?: boolean;
|
||||
autoApply?: boolean;
|
||||
size?: 'small' | 'middle' | 'large';
|
||||
}
|
||||
|
||||
// 简单的响应式检测
|
||||
const useIsMobile = () => {
|
||||
const [isMobile, setIsMobile] = useState(window.innerWidth < 768);
|
||||
useEffect(() => {
|
||||
const handler = () => setIsMobile(window.innerWidth < 768);
|
||||
window.addEventListener('resize', handler);
|
||||
return () => window.removeEventListener('resize', handler);
|
||||
}, []);
|
||||
return isMobile;
|
||||
};
|
||||
|
||||
const TenantScopeFilter: React.FC<Props> = ({ onChanged, useSwitchTenant = false, autoApply = false, size = 'middle' }) => {
|
||||
const isMobile = useIsMobile();
|
||||
const [tree, setTree] = useState<TenantNode[]>([]);
|
||||
const [tenantId, setTenantId] = useState<string | undefined>();
|
||||
const [includeChildren, setIncludeChildren] = useState<boolean>(true);
|
||||
const [loading, setLoading] = useState<boolean>(false);
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const treeRes: any = await tenantApi.getAccessibleTenants();
|
||||
let list: TenantNode[] = [];
|
||||
if (Array.isArray(treeRes)) list = treeRes as any;
|
||||
else if (Array.isArray(treeRes?.data)) list = treeRes.data as any;
|
||||
else if (treeRes?.resp_code === 0 && Array.isArray(treeRes?.data)) list = treeRes.data as any;
|
||||
setTree(list || []);
|
||||
|
||||
const curRes: any = await tenantApi.getCurrentTenant();
|
||||
const curId = curRes?.data?.tenantId || (curRes?.resp_code === 0 ? curRes?.data?.tenantId : undefined);
|
||||
if (curId) setTenantId(curId);
|
||||
} catch {
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
})();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!autoApply) return;
|
||||
if (!tenantId) return;
|
||||
onChanged?.(tenantId, includeChildren);
|
||||
}, [tenantId, includeChildren, autoApply]);
|
||||
|
||||
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 handleApply = async () => {
|
||||
if (!tenantId) return;
|
||||
try {
|
||||
if (useSwitchTenant) {
|
||||
const res: any = await tenantApi.switchTenant(tenantId);
|
||||
if (!(res?.success ?? res?.resp_code === 0)) {
|
||||
message.error(res?.msg || '切换失败');
|
||||
return;
|
||||
}
|
||||
message.success('租户范围已更新');
|
||||
}
|
||||
onChanged?.(tenantId, includeChildren);
|
||||
} catch {
|
||||
message.error('操作失败');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Space direction={isMobile ? 'vertical' : 'horizontal'} style={{ width: isMobile ? '100%' : 'auto' }}>
|
||||
<TreeSelect
|
||||
size={size}
|
||||
style={{ minWidth: isMobile ? 0 : 260, width: isMobile ? '100%' : undefined }}
|
||||
showSearch
|
||||
loading={loading}
|
||||
treeNodeFilterProp="title"
|
||||
listHeight={400}
|
||||
popupMatchSelectWidth
|
||||
getPopupContainer={() => document.body}
|
||||
placeholder="选择租户(含子租户)"
|
||||
value={tenantId}
|
||||
onChange={(val) => setTenantId(val)}
|
||||
treeData={toTreeData(tree)}
|
||||
/>
|
||||
<Checkbox checked={includeChildren} onChange={(e) => setIncludeChildren(e.target.checked)}>包含子租户</Checkbox>
|
||||
{!autoApply && (
|
||||
<Button type="primary" size={isMobile ? 'small' : 'middle'} onClick={handleApply}>应用</Button>
|
||||
)}
|
||||
</Space>
|
||||
);
|
||||
};
|
||||
|
||||
export default TenantScopeFilter;
|
||||
@@ -0,0 +1,140 @@
|
||||
/* 鹰眼管控平台 - 全局样式 */
|
||||
/* 深色科技主题 */
|
||||
|
||||
:root {
|
||||
--bg-primary: #0a0e27;
|
||||
--bg-secondary: #131a3d;
|
||||
--bg-card: rgba(19, 26, 61, 0.85);
|
||||
--border-color: #1e3a5f;
|
||||
--text-primary: #ffffff;
|
||||
--text-secondary: #8b9dc3;
|
||||
--accent-blue: #00d4ff;
|
||||
--accent-green: #00ff88;
|
||||
--accent-yellow: #ffb800;
|
||||
--accent-red: #ff4757;
|
||||
--shadow-card: 0 8px 32px rgba(0, 0, 0, 0.3);
|
||||
}
|
||||
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html, body, #root {
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--bg-primary);
|
||||
color: var(--text-primary);
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
/* 滚动条样式 */
|
||||
::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-track {
|
||||
background: var(--bg-secondary);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: var(--border-color);
|
||||
border-radius: 4px;
|
||||
&:hover {
|
||||
background: var(--accent-blue);
|
||||
}
|
||||
}
|
||||
|
||||
/* Ant Design 覆盖 */
|
||||
.ant-layout {
|
||||
background: var(--bg-primary) !important;
|
||||
}
|
||||
|
||||
.ant-layout-header {
|
||||
background: var(--bg-secondary) !important;
|
||||
}
|
||||
|
||||
.ant-card {
|
||||
background: var(--bg-card) !important;
|
||||
border-color: var(--border-color) !important;
|
||||
color: var(--text-primary) !important;
|
||||
}
|
||||
|
||||
.ant-card-head {
|
||||
color: var(--text-primary) !important;
|
||||
border-color: var(--border-color) !important;
|
||||
}
|
||||
|
||||
.ant-statistic-title {
|
||||
color: var(--text-secondary) !important;
|
||||
}
|
||||
|
||||
.ant-statistic-content {
|
||||
color: var(--text-primary) !important;
|
||||
}
|
||||
|
||||
.ant-select-selector {
|
||||
background: var(--bg-secondary) !important;
|
||||
border-color: var(--border-color) !important;
|
||||
color: var(--text-primary) !important;
|
||||
}
|
||||
|
||||
.ant-select-arrow {
|
||||
color: var(--text-secondary) !important;
|
||||
}
|
||||
|
||||
.ant-select-dropdown {
|
||||
background: var(--bg-secondary) !important;
|
||||
border-color: var(--border-color) !important;
|
||||
}
|
||||
|
||||
.ant-select-item {
|
||||
color: var(--text-primary) !important;
|
||||
}
|
||||
|
||||
.ant-select-item-option-active:not(.ant-select-item-option-disabled) {
|
||||
background: rgba(0, 212, 255, 0.1) !important;
|
||||
}
|
||||
|
||||
.ant-select-item-option-selected:not(.ant-select-item-option-disabled) {
|
||||
background: rgba(0, 212, 255, 0.2) !important;
|
||||
}
|
||||
|
||||
.ant-btn-primary {
|
||||
background: linear-gradient(135deg, #00d4ff 0%, #0099cc 100%) !important;
|
||||
border: none !important;
|
||||
&:hover {
|
||||
background: linear-gradient(135deg, #00e5ff 0%, #00aadd 100%) !important;
|
||||
}
|
||||
}
|
||||
|
||||
.ant-checkbox-wrapper {
|
||||
color: var(--text-secondary) !important;
|
||||
}
|
||||
|
||||
/* 树选择器 */
|
||||
.ant-tree-select-dropdown {
|
||||
background: var(--bg-secondary) !important;
|
||||
}
|
||||
|
||||
.ant-select-tree {
|
||||
background: transparent !important;
|
||||
color: var(--text-primary) !important;
|
||||
}
|
||||
|
||||
.ant-select-tree-node-content-wrapper:hover {
|
||||
background: rgba(0, 212, 255, 0.1) !important;
|
||||
}
|
||||
|
||||
.ant-select-tree-node-selected {
|
||||
background: rgba(0, 212, 255, 0.2) !important;
|
||||
}
|
||||
@@ -0,0 +1,383 @@
|
||||
.blank-layout {
|
||||
min-height: 100vh;
|
||||
background: var(--bg-primary);
|
||||
}
|
||||
|
||||
.blank-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 0 24px;
|
||||
height: 56px;
|
||||
line-height: 56px;
|
||||
background: linear-gradient(180deg, rgba(19, 26, 61, 0.98) 0%, rgba(10, 14, 39, 0.95) 100%) !important;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 100;
|
||||
}
|
||||
|
||||
.header-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.logo {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
cursor: pointer;
|
||||
transition: opacity 0.2s;
|
||||
|
||||
&:hover {
|
||||
opacity: 0.85;
|
||||
}
|
||||
}
|
||||
|
||||
.logo-icon {
|
||||
font-size: 24px;
|
||||
color: var(--accent-blue);
|
||||
margin-right: 10px;
|
||||
}
|
||||
|
||||
.logo-text {
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
background: linear-gradient(135deg, #00d4ff 0%, #00ff88 100%);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
background-clip: text;
|
||||
}
|
||||
|
||||
.header-center {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
padding: 0 24px;
|
||||
}
|
||||
|
||||
.header-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 24px;
|
||||
}
|
||||
|
||||
.current-time {
|
||||
color: var(--text-secondary);
|
||||
font-size: 14px;
|
||||
font-family: 'Courier New', monospace;
|
||||
}
|
||||
|
||||
.user-info {
|
||||
cursor: pointer;
|
||||
padding: 4px 12px;
|
||||
border-radius: 20px;
|
||||
transition: background 0.2s;
|
||||
|
||||
&:hover {
|
||||
background: rgba(0, 212, 255, 0.1);
|
||||
}
|
||||
}
|
||||
|
||||
.user-name {
|
||||
color: var(--text-primary);
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.blank-content {
|
||||
height: calc(100vh - 56px);
|
||||
overflow: auto;
|
||||
background: var(--bg-primary);
|
||||
}
|
||||
|
||||
.blank-content--dashboard {
|
||||
height: calc(100vh - 80px);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.blank-content--map3d {
|
||||
height: calc(100vh - 72px);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.blank-header--map3d {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr auto 1fr;
|
||||
height: 72px;
|
||||
line-height: 72px;
|
||||
padding: 0 16px;
|
||||
background: rgba(10, 20, 30, 0.88) !important;
|
||||
border-bottom: 1px solid rgba(0, 240, 255, 0.12);
|
||||
box-shadow: 0 2px 16px rgba(0, 0, 0, 0.45);
|
||||
backdrop-filter: blur(10px);
|
||||
|
||||
.header-left,
|
||||
.header-center,
|
||||
.header-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.header-left {
|
||||
min-width: 260px;
|
||||
}
|
||||
|
||||
.header-center {
|
||||
justify-content: center;
|
||||
padding: 0 10px;
|
||||
}
|
||||
|
||||
.header-right {
|
||||
justify-content: flex-end;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.map3d-header-slot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
min-height: 1px;
|
||||
}
|
||||
|
||||
#map3d-header-left {
|
||||
justify-content: flex-start;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
#map3d-header-center {
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
#map3d-header-right {
|
||||
justify-content: flex-end;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.user-info {
|
||||
padding: 4px 10px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid rgba(0, 240, 255, 0.14);
|
||||
background: rgba(255, 255, 255, 0.04);
|
||||
|
||||
&:hover {
|
||||
background: rgba(0, 240, 255, 0.10);
|
||||
border-color: rgba(0, 240, 255, 0.28);
|
||||
}
|
||||
}
|
||||
|
||||
.user-name {
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
}
|
||||
}
|
||||
|
||||
.blank-header--dashboard {
|
||||
height: 80px;
|
||||
line-height: 80px;
|
||||
padding: 0 22px;
|
||||
background: linear-gradient(180deg, rgba(7, 10, 26, 0.92) 0%, rgba(7, 10, 26, 0.66) 100%) !important;
|
||||
border-bottom: none;
|
||||
overflow: hidden;
|
||||
box-shadow:
|
||||
0 2px 12px rgba(0, 0, 0, 0.28),
|
||||
inset 0 -1px 0 rgba(0, 212, 255, 0.18);
|
||||
position: sticky;
|
||||
|
||||
&::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
top: 0;
|
||||
height: 1px;
|
||||
background: linear-gradient(90deg, transparent, rgba(0, 212, 255, 0.55), transparent);
|
||||
opacity: 0.45;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: -30%;
|
||||
width: 30%;
|
||||
height: 100%;
|
||||
background: linear-gradient(90deg, transparent, rgba(0, 212, 255, 0.12), transparent);
|
||||
transform: skewX(-18deg);
|
||||
animation: headerSweep 5.2s linear infinite;
|
||||
opacity: 0.65;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.header-left {
|
||||
flex: 1.2;
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
.header-center {
|
||||
flex: 1.6;
|
||||
justify-content: center;
|
||||
padding: 0 12px;
|
||||
}
|
||||
|
||||
.header-right {
|
||||
flex: 1.2;
|
||||
justify-content: flex-end;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.dashboard-title {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
max-width: 920px;
|
||||
padding: 0 18px;
|
||||
|
||||
&::before,
|
||||
&::after {
|
||||
content: '';
|
||||
flex: 1;
|
||||
height: 1px;
|
||||
background: linear-gradient(90deg, rgba(0, 212, 255, 0), rgba(0, 212, 255, 0.55));
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
&::after {
|
||||
background: linear-gradient(90deg, rgba(0, 212, 255, 0.55), rgba(0, 212, 255, 0));
|
||||
}
|
||||
|
||||
.dashboard-title__text {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 10px 28px;
|
||||
margin: 0 14px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid rgba(0, 212, 255, 0.28);
|
||||
background: rgba(19, 26, 61, 0.42);
|
||||
font-size: 28px;
|
||||
font-weight: 800;
|
||||
letter-spacing: 8px;
|
||||
line-height: 1.1;
|
||||
font-family: 'DIN Alternate', 'HarmonyOS Sans', 'Microsoft YaHei', 'PingFang SC', 'Segoe UI', sans-serif;
|
||||
color: #fff;
|
||||
text-shadow: 0 0 18px rgba(0, 212, 255, 0.35);
|
||||
background-image: linear-gradient(180deg, #ffffff 0%, #aeeeff 100%);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
background-clip: text;
|
||||
}
|
||||
|
||||
.dashboard-title__deco {
|
||||
position: absolute;
|
||||
bottom: 14px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
width: 320px;
|
||||
height: 2px;
|
||||
background: linear-gradient(90deg, transparent, rgba(0, 212, 255, 0.9), transparent);
|
||||
filter: drop-shadow(0 0 8px rgba(0, 212, 255, 0.35));
|
||||
opacity: 0.75;
|
||||
}
|
||||
}
|
||||
|
||||
.dashboard-filter {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 10px 12px;
|
||||
border-radius: 10px;
|
||||
border: 1px solid rgba(0, 212, 255, 0.22);
|
||||
background: rgba(19, 26, 61, 0.42);
|
||||
backdrop-filter: blur(8px);
|
||||
|
||||
.dashboard-filter__label {
|
||||
color: rgba(255, 255, 255, 0.72);
|
||||
font-size: 12px;
|
||||
letter-spacing: 2px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
:global(.ant-space) {
|
||||
gap: 8px !important;
|
||||
}
|
||||
|
||||
:global(.ant-checkbox-wrapper) {
|
||||
color: rgba(255, 255, 255, 0.68) !important;
|
||||
font-size: 12px;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
:global(.ant-tree-select) {
|
||||
min-width: 260px;
|
||||
}
|
||||
|
||||
:global(.ant-select-selector) {
|
||||
background: rgba(0, 212, 255, 0.04) !important;
|
||||
border: 1px solid rgba(0, 212, 255, 0.22) !important;
|
||||
color: #fff !important;
|
||||
border-radius: 8px !important;
|
||||
}
|
||||
|
||||
:global(.ant-select-arrow) {
|
||||
color: rgba(255, 255, 255, 0.55);
|
||||
}
|
||||
}
|
||||
|
||||
.dashboard-user--dashboard {
|
||||
padding: 6px 10px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid rgba(0, 212, 255, 0.22);
|
||||
background: rgba(19, 26, 61, 0.42);
|
||||
backdrop-filter: blur(8px);
|
||||
}
|
||||
|
||||
:global(.ant-tree-select) {
|
||||
:global(.ant-select-selector) {
|
||||
background: rgba(0, 212, 255, 0.05) !important;
|
||||
border: 1px solid rgba(0, 212, 255, 0.2) !important;
|
||||
color: #fff !important;
|
||||
border-radius: 6px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes headerSweep {
|
||||
0% { transform: translateX(0) skewX(-18deg); opacity: 0; }
|
||||
8% { opacity: 0.65; }
|
||||
55% { opacity: 0.35; }
|
||||
100% { transform: translateX(520%) skewX(-18deg); opacity: 0; }
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.blank-header {
|
||||
padding: 0 12px;
|
||||
}
|
||||
|
||||
.blank-header:not(.blank-header--map3d) .header-center {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.blank-header--map3d {
|
||||
padding: 0 12px;
|
||||
|
||||
.header-left {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.header-center {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
|
||||
.current-time {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.logo-text {
|
||||
font-size: 16px;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { history, useLocation } from 'umi';
|
||||
import { Layout, Space, Avatar, Dropdown, message } from 'antd';
|
||||
import { LogoutOutlined, UserOutlined, EnvironmentOutlined } from '@ant-design/icons';
|
||||
import type { MenuProps } from 'antd';
|
||||
import TenantScopeFilter from '@/components/TenantScopeFilter';
|
||||
import { outLogin, currentUser } from '@/services/login';
|
||||
import { clearTenantCache } from '@/utils/tenantCache';
|
||||
import './BlankLayout.less';
|
||||
|
||||
const { Header, Content } = Layout;
|
||||
|
||||
// UmiJS 3.x 使用 props.children 渲染子路由
|
||||
const BlankLayout: React.FC<{ children?: React.ReactNode }> = ({ children }) => {
|
||||
const location = useLocation();
|
||||
const isDashboard = location.pathname === '/dashboard';
|
||||
const isMap3d = location.pathname === '/map3d' || location.pathname.startsWith('/map3d/');
|
||||
const [currentTime, setCurrentTime] = useState<string>('');
|
||||
const [userName, setUserName] = useState<string>('');
|
||||
|
||||
useEffect(() => {
|
||||
if (isDashboard || isMap3d) return;
|
||||
// 更新时间
|
||||
const updateTime = () => {
|
||||
const now = new Date();
|
||||
setCurrentTime(now.toLocaleString('zh-CN', {
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
hour12: false
|
||||
}));
|
||||
};
|
||||
updateTime();
|
||||
const timer = setInterval(updateTime, 1000);
|
||||
return () => clearInterval(timer);
|
||||
}, [isDashboard]);
|
||||
|
||||
useEffect(() => {
|
||||
// 获取当前用户
|
||||
(async () => {
|
||||
try {
|
||||
const user = await currentUser();
|
||||
if (user?.username || user?.nickname) {
|
||||
setUserName(user.nickname || user.username);
|
||||
}
|
||||
} catch {}
|
||||
})();
|
||||
}, []);
|
||||
|
||||
const handleLogout = async () => {
|
||||
try {
|
||||
await outLogin();
|
||||
} catch {}
|
||||
sessionStorage.removeItem('access_token');
|
||||
sessionStorage.removeItem('current_user');
|
||||
clearTenantCache();
|
||||
message.success('已退出登录');
|
||||
history.push('/user/login');
|
||||
};
|
||||
|
||||
const userMenuItems: MenuProps['items'] = [
|
||||
{
|
||||
key: 'logout',
|
||||
icon: <LogoutOutlined />,
|
||||
label: '退出登录',
|
||||
onClick: handleLogout,
|
||||
},
|
||||
];
|
||||
|
||||
const handleTenantChange = (tenantId: string, includeChildren: boolean) => {
|
||||
// 租户变更后刷新页面数据(通过事件通知)
|
||||
window.dispatchEvent(new CustomEvent('tenant-change', {
|
||||
detail: { tenantId, includeChildren }
|
||||
}));
|
||||
};
|
||||
|
||||
return (
|
||||
<Layout className="blank-layout">
|
||||
<Header className={`blank-header${isDashboard ? ' blank-header--dashboard' : ''}${isMap3d ? ' blank-header--map3d' : ''}`}>
|
||||
<div className="header-left">
|
||||
{isDashboard ? (
|
||||
<div className="dashboard-filter">
|
||||
<div className="dashboard-filter__label">租户范围</div>
|
||||
<TenantScopeFilter onChanged={handleTenantChange} autoApply size="small" />
|
||||
</div>
|
||||
) : isMap3d ? (
|
||||
<div id="map3d-header-left" className="map3d-header-slot" />
|
||||
) : (
|
||||
<div className="logo" onClick={() => history.push('/dashboard')}>
|
||||
<EnvironmentOutlined className="logo-icon" />
|
||||
<span className="logo-text">鹰眼管控平台</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="header-center">
|
||||
{isDashboard ? (
|
||||
<div className="dashboard-title">
|
||||
<span className="dashboard-title__text">鹰眼管控平台 -运营总览</span>
|
||||
<span className="dashboard-title__deco" />
|
||||
</div>
|
||||
) : isMap3d ? (
|
||||
<div id="map3d-header-center" className="map3d-header-slot" />
|
||||
) : (
|
||||
<TenantScopeFilter onChanged={handleTenantChange} autoApply />
|
||||
)}
|
||||
</div>
|
||||
<div className="header-right">
|
||||
{!isDashboard && !isMap3d && <span className="current-time">{currentTime}</span>}
|
||||
{isMap3d && <div id="map3d-header-right" className="map3d-header-slot" />}
|
||||
<div className={`dashboard-user${isDashboard ? ' dashboard-user--dashboard' : ''}`}>
|
||||
<Dropdown menu={{ items: userMenuItems }} placement="bottomRight">
|
||||
<Space className="user-info">
|
||||
<Avatar size="small" icon={<UserOutlined />} />
|
||||
<span className="user-name">{userName || '用户'}</span>
|
||||
</Space>
|
||||
</Dropdown>
|
||||
</div>
|
||||
</div>
|
||||
</Header>
|
||||
<Content className={`blank-content${isDashboard ? ' blank-content--dashboard' : ''}${isMap3d ? ' blank-content--map3d' : ''}`}>
|
||||
{children}
|
||||
</Content>
|
||||
</Layout>
|
||||
);
|
||||
};
|
||||
|
||||
export default BlankLayout;
|
||||
@@ -0,0 +1,28 @@
|
||||
import React from 'react';
|
||||
import { Button, Result } from 'antd';
|
||||
import { history } from 'umi';
|
||||
|
||||
const NotFound: React.FC = () => {
|
||||
return (
|
||||
<div style={{
|
||||
height: '100vh',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
background: '#0a0e27'
|
||||
}}>
|
||||
<Result
|
||||
status="404"
|
||||
title={<span style={{ color: '#fff' }}>404</span>}
|
||||
subTitle={<span style={{ color: '#8b9dc3' }}>抱歉,您访问的页面不存在</span>}
|
||||
extra={
|
||||
<Button type="primary" onClick={() => history.push('/dashboard')}>
|
||||
返回首页
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default NotFound;
|
||||
@@ -0,0 +1,458 @@
|
||||
.dashboard-page {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: var(--bg-primary);
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
&::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background:
|
||||
radial-gradient(circle at 20% 20%, rgba(0, 212, 255, 0.12), transparent 45%),
|
||||
radial-gradient(circle at 80% 10%, rgba(0, 255, 136, 0.08), transparent 45%),
|
||||
radial-gradient(circle at 70% 80%, rgba(0, 212, 255, 0.08), transparent 55%);
|
||||
z-index: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.dashboard-bg-animation {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background-image:
|
||||
linear-gradient(rgba(0, 212, 255, 0.05) 1px, transparent 1px),
|
||||
linear-gradient(90deg, rgba(0, 212, 255, 0.05) 1px, transparent 1px);
|
||||
background-size: 40px 40px;
|
||||
animation: gridMove 32s linear infinite;
|
||||
z-index: 0;
|
||||
pointer-events: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* Main Content Grid */
|
||||
.dashboard-spin {
|
||||
height: 100%;
|
||||
:global(.ant-spin-container) {
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
|
||||
.dashboard-content {
|
||||
flex: 1;
|
||||
padding: 16px 18px;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.dashboard-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 25% 50% 25%;
|
||||
grid-template-rows: 100%;
|
||||
gap: 14px;
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.grid-col {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* Panel Card Styles */
|
||||
.panel-card {
|
||||
background: transparent !important;
|
||||
border-radius: 8px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
&.glass-panel {
|
||||
position: relative;
|
||||
background: rgba(19, 26, 61, 0.7) !important;
|
||||
border: 1px solid rgba(0, 212, 255, 0.15) !important;
|
||||
backdrop-filter: blur(8px);
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
|
||||
overflow: hidden;
|
||||
|
||||
&::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
pointer-events: none;
|
||||
background:
|
||||
linear-gradient(90deg, rgba(0, 212, 255, 0.6), transparent 60px) top left / 60px 2px no-repeat,
|
||||
linear-gradient(180deg, rgba(0, 212, 255, 0.6), transparent 60px) top left / 2px 60px no-repeat,
|
||||
linear-gradient(270deg, rgba(0, 212, 255, 0.6), transparent 60px) top right / 60px 2px no-repeat,
|
||||
linear-gradient(180deg, rgba(0, 212, 255, 0.6), transparent 60px) top right / 2px 60px no-repeat,
|
||||
linear-gradient(90deg, rgba(0, 212, 255, 0.6), transparent 60px) bottom left / 60px 2px no-repeat,
|
||||
linear-gradient(0deg, rgba(0, 212, 255, 0.6), transparent 60px) bottom left / 2px 60px no-repeat,
|
||||
linear-gradient(270deg, rgba(0, 212, 255, 0.6), transparent 60px) bottom right / 60px 2px no-repeat,
|
||||
linear-gradient(0deg, rgba(0, 212, 255, 0.6), transparent 60px) bottom right / 2px 60px no-repeat;
|
||||
opacity: 0.35;
|
||||
}
|
||||
}
|
||||
|
||||
:global(.ant-card-head) {
|
||||
min-height: 40px;
|
||||
padding: 0 12px;
|
||||
border-bottom: 1px solid rgba(0, 212, 255, 0.1);
|
||||
|
||||
.ant-card-head-title {
|
||||
font-size: 15px;
|
||||
color: #fff;
|
||||
padding: 8px 0;
|
||||
}
|
||||
}
|
||||
|
||||
:global(.ant-card-body) {
|
||||
flex: 1;
|
||||
padding: 12px;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
flex: 1;
|
||||
width: 100%;
|
||||
position: relative;
|
||||
min-height: 0; /* Important for flex child */
|
||||
|
||||
> div {
|
||||
height: 100% !important;
|
||||
}
|
||||
}
|
||||
|
||||
.flex-grow {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.fill-bottom {
|
||||
flex: 0.8; /* Slightly smaller than other sections if needed */
|
||||
}
|
||||
|
||||
/* Alert List */
|
||||
.alert-list-container {
|
||||
height: 100%;
|
||||
overflow-y: auto;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 4px;
|
||||
}
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background: rgba(0, 212, 255, 0.2);
|
||||
border-radius: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
.alert-item {
|
||||
padding: 8px 0 !important;
|
||||
border-bottom: 1px solid rgba(255,255,255,0.05) !important;
|
||||
|
||||
.alert-row {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
align-items: flex-start;
|
||||
|
||||
.alert-badge {
|
||||
margin-right: 8px;
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.alert-content {
|
||||
flex: 1;
|
||||
|
||||
.alert-head {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 2px;
|
||||
|
||||
.alert-name { color: #fff; font-weight: 500; font-size: 13px; }
|
||||
.alert-time { color: var(--accent-blue); font-size: 12px; font-family: monospace; }
|
||||
}
|
||||
|
||||
.alert-msg {
|
||||
color: rgba(255,255,255,0.6);
|
||||
font-size: 12px;
|
||||
line-height: 1.2;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Center Column Specifics */
|
||||
.kpi-row {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
gap: 12px;
|
||||
height: 80px;
|
||||
}
|
||||
|
||||
.kpi-card {
|
||||
background: rgba(19, 26, 61, 0.7);
|
||||
border: 1px solid rgba(0, 212, 255, 0.15);
|
||||
border-radius: 6px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 0 16px;
|
||||
|
||||
.kpi-icon {
|
||||
font-size: 24px;
|
||||
margin-right: 12px;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 50%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: rgba(255,255,255,0.05);
|
||||
|
||||
&.blue { color: #00d4ff; box-shadow: 0 0 10px rgba(0, 212, 255, 0.2); }
|
||||
&.green { color: #00ff88; box-shadow: 0 0 10px rgba(0, 255, 136, 0.2); }
|
||||
&.yellow { color: #ffb800; box-shadow: 0 0 10px rgba(255, 184, 0, 0.2); }
|
||||
&.purple { color: #9d4edd; box-shadow: 0 0 10px rgba(157, 78, 221, 0.2); }
|
||||
}
|
||||
|
||||
.kpi-info {
|
||||
.label { font-size: 12px; color: rgba(255,255,255,0.6); }
|
||||
.value { font-size: 24px; font-weight: bold; color: #fff; font-family: 'Segoe UI', sans-serif; line-height: 1.2; }
|
||||
small { font-size: 14px; margin-left: 2px; }
|
||||
}
|
||||
}
|
||||
|
||||
.map-portal-wrapper {
|
||||
flex: 2; /* Occupy most space */
|
||||
position: relative;
|
||||
background: rgba(0,0,0,0.2);
|
||||
border: 1px solid rgba(0, 212, 255, 0.3);
|
||||
border-radius: 12px;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
|
||||
/* Grid Background */
|
||||
.map-bg-grid {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background-image:
|
||||
linear-gradient(rgba(0, 212, 255, 0.2) 1px, transparent 1px),
|
||||
linear-gradient(90deg, rgba(0, 212, 255, 0.2) 1px, transparent 1px);
|
||||
background-size: 80px 80px;
|
||||
perspective: 1000px;
|
||||
transform: perspective(500px) rotateX(20deg) scale(1.5);
|
||||
opacity: 0.3;
|
||||
animation: gridMove 20s linear infinite;
|
||||
}
|
||||
|
||||
.map-content {
|
||||
position: relative;
|
||||
z-index: 3;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.radar-sweep {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 2;
|
||||
pointer-events: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
|
||||
&::before {
|
||||
content: '';
|
||||
width: 520px;
|
||||
height: 520px;
|
||||
border-radius: 50%;
|
||||
background:
|
||||
repeating-radial-gradient(circle, rgba(0, 212, 255, 0.22) 0 1px, transparent 1px 28px),
|
||||
radial-gradient(circle, rgba(0, 212, 255, 0.18), transparent 62%),
|
||||
radial-gradient(circle, rgba(0, 255, 136, 0.10), transparent 70%);
|
||||
filter: drop-shadow(0 0 18px rgba(0, 212, 255, 0.25));
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
width: 520px;
|
||||
height: 520px;
|
||||
border-radius: 50%;
|
||||
background: conic-gradient(
|
||||
from 0deg,
|
||||
rgba(0, 212, 255, 0.00) 0deg,
|
||||
rgba(0, 212, 255, 0.28) 18deg,
|
||||
rgba(0, 212, 255, 0.06) 45deg,
|
||||
rgba(0, 212, 255, 0.00) 75deg,
|
||||
rgba(0, 212, 255, 0.00) 360deg
|
||||
);
|
||||
mix-blend-mode: screen;
|
||||
animation: radarRotate 2.8s linear infinite;
|
||||
opacity: 0.9;
|
||||
}
|
||||
}
|
||||
|
||||
.portal-center {
|
||||
text-align: center;
|
||||
width: 340px;
|
||||
height: 340px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: rgba(10, 14, 39, 0.78);
|
||||
padding: 0 34px;
|
||||
border-radius: 50%;
|
||||
border: 1px solid var(--accent-blue);
|
||||
box-shadow: 0 0 30px rgba(0, 212, 255, 0.2);
|
||||
backdrop-filter: blur(5px);
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
|
||||
&::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 10px;
|
||||
border-radius: 50%;
|
||||
background:
|
||||
radial-gradient(circle at 30% 30%, rgba(0, 212, 255, 0.22), transparent 45%),
|
||||
radial-gradient(circle at 70% 70%, rgba(0, 255, 136, 0.12), transparent 50%);
|
||||
opacity: 0.6;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.portal-title {
|
||||
color: #fff;
|
||||
margin-bottom: 24px;
|
||||
font-size: 22px;
|
||||
letter-spacing: 2px;
|
||||
text-shadow: 0 0 10px var(--accent-blue);
|
||||
}
|
||||
|
||||
.portal-btn {
|
||||
height: 44px;
|
||||
padding: 0 32px;
|
||||
font-size: 16px;
|
||||
background: linear-gradient(90deg, #00d4ff, #007aff);
|
||||
border: none;
|
||||
box-shadow: 0 4px 15px rgba(0, 212, 255, 0.4);
|
||||
transition: all 0.3s;
|
||||
|
||||
&:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 8px 25px rgba(0, 212, 255, 0.6);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.task-filter {
|
||||
:global(.ant-segmented) {
|
||||
background: rgba(0, 212, 255, 0.06);
|
||||
border: 1px solid rgba(0, 212, 255, 0.18);
|
||||
}
|
||||
|
||||
:global(.ant-segmented-item-label) {
|
||||
color: rgba(255, 255, 255, 0.75);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
:global(.ant-segmented-item-selected) {
|
||||
background: rgba(0, 212, 255, 0.22) !important;
|
||||
}
|
||||
|
||||
:global(.ant-picker) {
|
||||
background: rgba(0, 212, 255, 0.06);
|
||||
border: 1px solid rgba(0, 212, 255, 0.18);
|
||||
color: rgba(255, 255, 255, 0.85);
|
||||
}
|
||||
|
||||
:global(.ant-picker-input > input) {
|
||||
color: rgba(255, 255, 255, 0.85);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
:global(.ant-picker-suffix) {
|
||||
color: rgba(255, 255, 255, 0.55);
|
||||
}
|
||||
}
|
||||
|
||||
/* Right Column */
|
||||
.task-overview-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 8px;
|
||||
|
||||
.task-stat-box {
|
||||
background: rgba(255,255,255,0.03);
|
||||
padding: 8px;
|
||||
text-align: center;
|
||||
border-radius: 4px;
|
||||
|
||||
.val { font-size: 18px; font-weight: bold; color: #fff; }
|
||||
.lbl { font-size: 11px; color: rgba(255,255,255,0.5); }
|
||||
|
||||
.val.pending { color: var(--accent-yellow); }
|
||||
.val.running { color: var(--accent-blue); }
|
||||
.val.completed { color: var(--accent-green); }
|
||||
.val.failed { color: var(--accent-red); }
|
||||
}
|
||||
}
|
||||
|
||||
/* Animation Keyframes */
|
||||
@keyframes gridMove {
|
||||
0% { background-position: 0 0; }
|
||||
100% { background-position: 0 80px; }
|
||||
}
|
||||
|
||||
@keyframes radarRotate {
|
||||
0% { transform: rotate(0deg); }
|
||||
100% { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
/* Media Queries for Responsive adjustments on smaller screens (if needed) */
|
||||
@media (max-width: 1400px) {
|
||||
.dashboard-grid {
|
||||
grid-template-columns: 28% 44% 28%;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 1200px) {
|
||||
.dashboard-page {
|
||||
height: auto;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.dashboard-content {
|
||||
height: auto;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.dashboard-grid {
|
||||
grid-template-columns: 1fr;
|
||||
grid-template-rows: auto;
|
||||
}
|
||||
|
||||
.grid-col {
|
||||
height: auto;
|
||||
min-height: 400px;
|
||||
}
|
||||
|
||||
.map-portal-wrapper {
|
||||
min-height: 300px;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,504 @@
|
||||
import React, { useState, useEffect, useCallback, useMemo } from 'react';
|
||||
import { Card, Button, List, Tag, Spin, message, DatePicker, Segmented, Space } from 'antd';
|
||||
import {
|
||||
DesktopOutlined,
|
||||
CheckCircleOutlined,
|
||||
WarningOutlined,
|
||||
RocketOutlined,
|
||||
EnvironmentOutlined,
|
||||
PieChartOutlined
|
||||
} from '@ant-design/icons';
|
||||
import { Line, Pie, Column, Area, Gauge, Rose } from '@ant-design/plots';
|
||||
import { history } from 'umi';
|
||||
import dayjs from 'dayjs';
|
||||
import {
|
||||
getDeviceStats,
|
||||
getTaskStats,
|
||||
getTrendData,
|
||||
getMockAlerts,
|
||||
DeviceStats,
|
||||
TaskStats,
|
||||
TrendItem,
|
||||
AlertItem,
|
||||
} from '@/services/dashboard';
|
||||
import './index.less';
|
||||
|
||||
const Dashboard: React.FC = () => {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [deviceStats, setDeviceStats] = useState<DeviceStats | null>(null);
|
||||
const [taskStats, setTaskStats] = useState<TaskStats | null>(null);
|
||||
const [taskTrend, setTaskTrend] = useState<TrendItem[]>([]);
|
||||
const [deviceTrend, setDeviceTrend] = useState<TrendItem[]>([]);
|
||||
const [alerts, setAlerts] = useState<AlertItem[]>([]);
|
||||
const [annualData, setAnnualData] = useState<any[]>([]);
|
||||
const [failureAnalysisData, setFailureAnalysisData] = useState<any[]>([]);
|
||||
const [taskStatType, setTaskStatType] = useState<'day' | 'month' | 'year'>('day');
|
||||
const [taskStatDate, setTaskStatDate] = useState(dayjs());
|
||||
const [tenantId, setTenantId] = useState<string | undefined>();
|
||||
const [includeChildren, setIncludeChildren] = useState<boolean>(true);
|
||||
|
||||
useEffect(() => {
|
||||
// 模拟年度数据
|
||||
const mockAnnual: any[] = [];
|
||||
for (let i = 1; i <= 12; i++) {
|
||||
mockAnnual.push({
|
||||
month: `${i}月`,
|
||||
value: Math.floor(Math.random() * 500) + 100,
|
||||
type: '任务总数',
|
||||
});
|
||||
mockAnnual.push({
|
||||
month: `${i}月`,
|
||||
value: Math.floor(Math.random() * 450) + 80,
|
||||
type: '成功任务',
|
||||
});
|
||||
}
|
||||
setAnnualData(mockAnnual);
|
||||
|
||||
// 模拟失败原因数据
|
||||
setFailureAnalysisData([
|
||||
{ type: '信号丢失', value: 27 },
|
||||
{ type: '电池不足', value: 25 },
|
||||
{ type: '天气原因', value: 18 },
|
||||
{ type: '机械故障', value: 15 },
|
||||
{ type: '人为取消', value: 10 },
|
||||
{ type: '其他', value: 5 },
|
||||
]);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const handler = (e: any) => {
|
||||
const nextTenantId = e?.detail?.tenantId as string | undefined;
|
||||
const nextIncludeChildren = !!e?.detail?.includeChildren;
|
||||
setTenantId(nextTenantId);
|
||||
setIncludeChildren(nextIncludeChildren);
|
||||
};
|
||||
window.addEventListener('tenant-change', handler as any);
|
||||
return () => window.removeEventListener('tenant-change', handler as any);
|
||||
}, []);
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [deviceRes, taskRes, trendRes] = await Promise.all([
|
||||
getDeviceStats({ tenantId, includeChildren }),
|
||||
getTaskStats({
|
||||
tenantId,
|
||||
includeChildren,
|
||||
statType: taskStatType,
|
||||
date:
|
||||
taskStatType === 'day'
|
||||
? taskStatDate.format('YYYY-MM-DD')
|
||||
: taskStatType === 'month'
|
||||
? taskStatDate.format('YYYY-MM')
|
||||
: taskStatDate.format('YYYY'),
|
||||
}),
|
||||
getTrendData(7),
|
||||
]);
|
||||
setDeviceStats(deviceRes);
|
||||
setTaskStats(taskRes);
|
||||
setTaskTrend(trendRes.taskTrend);
|
||||
setDeviceTrend(trendRes.deviceTrend);
|
||||
setAlerts(getMockAlerts());
|
||||
} catch (error) {
|
||||
console.error('获取数据失败:', error);
|
||||
message.error('数据加载异常');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [includeChildren, taskStatDate, taskStatType, tenantId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!tenantId) return;
|
||||
fetchData();
|
||||
}, [fetchData]);
|
||||
|
||||
// 定时刷新和时间更新
|
||||
useEffect(() => {
|
||||
const dataTimer = setInterval(fetchData, 30000);
|
||||
return () => {
|
||||
clearInterval(dataTimer);
|
||||
};
|
||||
}, [fetchData]);
|
||||
|
||||
const goTo3D = () => {
|
||||
history.push('/map3d');
|
||||
};
|
||||
|
||||
// --- 图表配置 ---
|
||||
|
||||
const taskTrendSeriesData = useMemo(() => {
|
||||
return taskTrend.flatMap((t) => [
|
||||
{ date: t.date, type: '创建', value: t.created || 0 },
|
||||
{ date: t.date, type: '完成', value: t.completed || 0 },
|
||||
{ date: t.date, type: '失败', value: t.failed || 0 },
|
||||
]);
|
||||
}, [taskTrend]);
|
||||
|
||||
const deviceOnlineRateTrendData = useMemo(() => {
|
||||
return deviceTrend.map((t) => {
|
||||
const total = t.total || 0;
|
||||
const online = t.online || 0;
|
||||
return {
|
||||
date: t.date,
|
||||
value: total > 0 ? Math.round((online / total) * 100) : 0,
|
||||
};
|
||||
});
|
||||
}, [deviceTrend]);
|
||||
|
||||
const taskTrendConfig: any = {
|
||||
data: taskTrendSeriesData,
|
||||
xField: 'date',
|
||||
yField: 'value',
|
||||
seriesField: 'type',
|
||||
smooth: true,
|
||||
color: ['#00d4ff', '#00ff88', '#ffb800'],
|
||||
areaStyle: {
|
||||
fill: 'l(270) 0:#ffffff 0.5:#7ec2f3 1:#1890ff',
|
||||
fillOpacity: 0.1,
|
||||
},
|
||||
xAxis: { label: { style: { fill: 'rgba(255,255,255,0.65)' } }, grid: null },
|
||||
yAxis: { label: { style: { fill: 'rgba(255,255,255,0.65)' } }, grid: { line: { style: { stroke: 'rgba(255,255,255,0.1)' } } } },
|
||||
tooltip: { showMarkers: true },
|
||||
height: 180,
|
||||
};
|
||||
|
||||
const pieConfig: any = {
|
||||
data: deviceStats?.byType || [],
|
||||
angleField: 'count',
|
||||
colorField: 'name',
|
||||
radius: 0.7,
|
||||
innerRadius: 0.5,
|
||||
label: {
|
||||
type: 'outer',
|
||||
content: '{name} {percentage}',
|
||||
style: { fill: 'rgba(255,255,255,0.65)' },
|
||||
},
|
||||
legend: { position: 'bottom', itemValue: { style: { fill: 'rgba(255,255,255,0.65)' } }, itemName: { style: { fill: 'rgba(255,255,255,0.65)' } } },
|
||||
height: 200,
|
||||
};
|
||||
|
||||
const columnConfig: any = {
|
||||
data: [
|
||||
{ type: '在线', value: deviceStats?.online || 0, color: '#00ff88' },
|
||||
{ type: '离线', value: deviceStats?.offline || 0, color: '#8b9dc3' },
|
||||
{ type: '故障', value: deviceStats?.fault || 0, color: '#ff4d4f' },
|
||||
],
|
||||
xField: 'type',
|
||||
yField: 'value',
|
||||
seriesField: 'type',
|
||||
color: ({ type }: any) => {
|
||||
if(type === '在线') return '#00ff88';
|
||||
if(type === '故障') return '#ff4d4f';
|
||||
return '#8b9dc3';
|
||||
},
|
||||
label: {
|
||||
position: 'middle',
|
||||
style: { fill: '#fff' },
|
||||
},
|
||||
xAxis: { label: { style: { fill: 'rgba(255,255,255,0.65)' } } },
|
||||
yAxis: { label: { style: { fill: 'rgba(255,255,255,0.65)' } }, grid: { line: { style: { stroke: 'rgba(255,255,255,0.1)' } } } },
|
||||
legend: false,
|
||||
height: 180,
|
||||
};
|
||||
|
||||
const deviceOnlineRateConfig: any = {
|
||||
data: deviceOnlineRateTrendData,
|
||||
xField: 'date',
|
||||
yField: 'value',
|
||||
smooth: true,
|
||||
color: '#00d4ff',
|
||||
areaStyle: { fillOpacity: 0.15 },
|
||||
xAxis: { label: { style: { fill: 'rgba(255,255,255,0.65)' } }, grid: null },
|
||||
yAxis: {
|
||||
label: { style: { fill: 'rgba(255,255,255,0.65)' } },
|
||||
grid: { line: { style: { stroke: 'rgba(255,255,255,0.08)' } } },
|
||||
},
|
||||
tooltip: { showMarkers: true },
|
||||
height: 160,
|
||||
};
|
||||
|
||||
const areaConfig: any = {
|
||||
data: annualData,
|
||||
xField: 'month',
|
||||
yField: 'value',
|
||||
seriesField: 'type',
|
||||
color: ['#00d4ff', '#00ff88'],
|
||||
areaStyle: { fillOpacity: 0.3 },
|
||||
xAxis: { label: { style: { fill: 'rgba(255,255,255,0.65)' } } },
|
||||
yAxis: { label: { style: { fill: 'rgba(255,255,255,0.65)' } }, grid: { line: { style: { stroke: 'rgba(255,255,255,0.1)' } } } },
|
||||
legend: { position: 'top-right', itemName: { style: { fill: '#fff' } } },
|
||||
smooth: true,
|
||||
height: 220,
|
||||
};
|
||||
|
||||
const roseConfig: any = {
|
||||
data: failureAnalysisData,
|
||||
xField: 'type',
|
||||
yField: 'value',
|
||||
seriesField: 'type',
|
||||
radius: 0.9,
|
||||
label: {
|
||||
offset: -15,
|
||||
content: '{name}',
|
||||
style: { fill: '#fff' },
|
||||
},
|
||||
legend: { position: 'bottom', itemName: { style: { fill: 'rgba(255,255,255,0.65)' } } },
|
||||
height: 200,
|
||||
};
|
||||
|
||||
const taskStatusPieConfig: any = {
|
||||
data: [
|
||||
{ name: '待执行', value: taskStats?.pending || 0 },
|
||||
{ name: '执行中', value: taskStats?.running || 0 },
|
||||
{ name: '已完成', value: taskStats?.completed || 0 },
|
||||
{ name: '已失败', value: taskStats?.failed || 0 },
|
||||
],
|
||||
angleField: 'value',
|
||||
colorField: 'name',
|
||||
radius: 0.85,
|
||||
innerRadius: 0.55,
|
||||
label: {
|
||||
type: 'outer',
|
||||
content: '{name} {percentage}',
|
||||
style: { fill: 'rgba(255,255,255,0.65)' },
|
||||
},
|
||||
legend: { position: 'bottom', itemValue: { style: { fill: 'rgba(255,255,255,0.65)' } }, itemName: { style: { fill: 'rgba(255,255,255,0.65)' } } },
|
||||
height: 190,
|
||||
};
|
||||
|
||||
const getAlertColor = (level: string) => {
|
||||
switch (level) {
|
||||
case 'critical': return 'red';
|
||||
case 'error': return 'orange';
|
||||
case 'warning': return 'gold';
|
||||
default: return 'blue';
|
||||
}
|
||||
};
|
||||
|
||||
const taskPeriodText = useMemo(() => {
|
||||
if (taskStatType === 'day') return '当日';
|
||||
if (taskStatType === 'month') return '当月';
|
||||
return '当年';
|
||||
}, [taskStatType]);
|
||||
|
||||
const taskNewLabel = useMemo(() => {
|
||||
if (taskStatType === 'day') return '当日任务';
|
||||
if (taskStatType === 'month') return '当月任务';
|
||||
return '当年任务';
|
||||
}, [taskStatType]);
|
||||
|
||||
const datePickerFormat = useMemo(() => {
|
||||
if (taskStatType === 'day') return 'YYYY-MM-DD';
|
||||
if (taskStatType === 'month') return 'YYYY-MM';
|
||||
return 'YYYY';
|
||||
}, [taskStatType]);
|
||||
|
||||
return (
|
||||
<div className="dashboard-page">
|
||||
<div className="dashboard-bg-animation"></div>
|
||||
|
||||
<Spin spinning={loading} wrapperClassName="dashboard-spin">
|
||||
<div className="dashboard-content">
|
||||
<div className="dashboard-grid">
|
||||
|
||||
{/* 左侧栏:设备态势 */}
|
||||
<div className="grid-col left-col">
|
||||
<Card title="设备类型分布" className="panel-card glass-panel" size="small">
|
||||
<div className="chart-wrapper">
|
||||
<Pie {...pieConfig} />
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<Card title="设备状态统计" className="panel-card glass-panel" size="small">
|
||||
<div className="chart-wrapper">
|
||||
<Column {...columnConfig} />
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<Card title="近7日在线率趋势" className="panel-card glass-panel" size="small">
|
||||
<div className="chart-wrapper">
|
||||
<Area {...deviceOnlineRateConfig} />
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title={<span><WarningOutlined className="icon-warning" /> 实时告警</span>}
|
||||
className="panel-card glass-panel flex-grow"
|
||||
size="small"
|
||||
extra={<Tag color="#f50">Live</Tag>}
|
||||
>
|
||||
<div className="alert-list-container">
|
||||
<List
|
||||
dataSource={alerts}
|
||||
split={false}
|
||||
renderItem={(item) => (
|
||||
<List.Item className="alert-item">
|
||||
<div className="alert-row">
|
||||
<div className="alert-badge">
|
||||
<Tag color={getAlertColor(item.level)}>{item.level.toUpperCase().slice(0,1)}</Tag>
|
||||
</div>
|
||||
<div className="alert-content">
|
||||
<div className="alert-head">
|
||||
<span className="alert-name">{item.deviceName || item.taskName}</span>
|
||||
<span className="alert-time">{dayjs(item.timestamp).format('HH:mm')}</span>
|
||||
</div>
|
||||
<div className="alert-msg">{item.message}</div>
|
||||
</div>
|
||||
</div>
|
||||
</List.Item>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* 中间栏:核心监控 */}
|
||||
<div className="grid-col center-col">
|
||||
{/* 顶部KPI */}
|
||||
<div className="kpi-row">
|
||||
<div className="kpi-card">
|
||||
<div className="kpi-icon blue"><DesktopOutlined /></div>
|
||||
<div className="kpi-info">
|
||||
<div className="label">设备总数</div>
|
||||
<div className="value">{deviceStats?.total || 0}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="kpi-card">
|
||||
<div className="kpi-icon green"><CheckCircleOutlined /></div>
|
||||
<div className="kpi-info">
|
||||
<div className="label">在线率</div>
|
||||
<div className="value">{deviceStats?.onlineRate || 0}<small>%</small></div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="kpi-card">
|
||||
<div className="kpi-icon yellow"><RocketOutlined /></div>
|
||||
<div className="kpi-info">
|
||||
<div className="label">{taskNewLabel}</div>
|
||||
<div className="value">{taskStats?.todayNew || 0}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="kpi-card">
|
||||
<div className="kpi-icon purple"><PieChartOutlined /></div>
|
||||
<div className="kpi-info">
|
||||
<div className="label">执行成功率</div>
|
||||
<div className="value">{taskStats?.successRate || 0}<small>%</small></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 地图/3D入口 */}
|
||||
<div className="map-portal-wrapper">
|
||||
<div className="map-bg-grid"></div>
|
||||
<div className="radar-sweep"></div>
|
||||
<div className="map-content">
|
||||
<div className="portal-center">
|
||||
<EnvironmentOutlined style={{ fontSize: 56, color: '#00d4ff', marginBottom: 20 }} />
|
||||
<h2 className="portal-title">全域数字孪生监控中心</h2>
|
||||
<Button type="primary" shape="round" size="large" onClick={goTo3D} className="portal-btn">
|
||||
立即进入监控视图
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 底部年度统计 */}
|
||||
<Card title="年度任务执行趋势分析" className="panel-card glass-panel fill-bottom" size="small">
|
||||
<div className="chart-wrapper">
|
||||
<Area {...areaConfig} />
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* 右侧栏:任务与运维 */}
|
||||
<div className="grid-col right-col">
|
||||
<Card
|
||||
title={`${taskPeriodText}任务统计`}
|
||||
className="panel-card glass-panel"
|
||||
size="small"
|
||||
extra={
|
||||
<Space size={8} className="task-filter">
|
||||
<Segmented
|
||||
size="small"
|
||||
options={[
|
||||
{ label: '日', value: 'day' },
|
||||
{ label: '月', value: 'month' },
|
||||
{ label: '年', value: 'year' },
|
||||
]}
|
||||
value={taskStatType}
|
||||
onChange={(v) => setTaskStatType(v as any)}
|
||||
/>
|
||||
<DatePicker
|
||||
size="small"
|
||||
value={taskStatDate}
|
||||
onChange={(v) => v && setTaskStatDate(v)}
|
||||
picker={taskStatType === 'day' ? 'date' : taskStatType}
|
||||
allowClear={false}
|
||||
format={datePickerFormat}
|
||||
disabledDate={(d) => !!d && d.isAfter(dayjs(), 'day')}
|
||||
/>
|
||||
</Space>
|
||||
}
|
||||
>
|
||||
<div className="task-overview-grid">
|
||||
<div className="task-stat-box">
|
||||
<div className="val pending">{taskStats?.pending || 0}</div>
|
||||
<div className="lbl">待执行</div>
|
||||
</div>
|
||||
<div className="task-stat-box">
|
||||
<div className="val running">{taskStats?.running || 0}</div>
|
||||
<div className="lbl">执行中</div>
|
||||
</div>
|
||||
<div className="task-stat-box">
|
||||
<div className="val completed">{taskStats?.completed || 0}</div>
|
||||
<div className="lbl">已完成</div>
|
||||
</div>
|
||||
<div className="task-stat-box">
|
||||
<div className="val failed">{taskStats?.failed || 0}</div>
|
||||
<div className="lbl">已失败</div>
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ marginTop: 16 }}>
|
||||
<Gauge
|
||||
percent={taskStats?.successRate ? taskStats.successRate / 100 : 0}
|
||||
range={{ color: 'l(0) 0:#bde8ff 1:#9ec9ff' }}
|
||||
startAngle={Math.PI}
|
||||
endAngle={2 * Math.PI}
|
||||
indicator={null}
|
||||
statistic={{
|
||||
content: {
|
||||
style: { fontSize: '20px', color: '#fff' },
|
||||
formatter: () => `${taskPeriodText}成功率`,
|
||||
},
|
||||
}}
|
||||
height={100}
|
||||
/>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<Card title="任务状态占比" className="panel-card glass-panel" size="small">
|
||||
<div className="chart-wrapper">
|
||||
<Pie {...taskStatusPieConfig} />
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<Card title="近7日任务趋势" className="panel-card glass-panel" size="small">
|
||||
<div className="chart-wrapper">
|
||||
<Line {...taskTrendConfig} />
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<Card title="异常原因分析" className="panel-card glass-panel flex-grow" size="small">
|
||||
<div className="chart-wrapper">
|
||||
<Rose {...roseConfig} />
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</Spin>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Dashboard;
|
||||
+1021
File diff suppressed because it is too large
Load Diff
+866
@@ -0,0 +1,866 @@
|
||||
import React, { useMemo, useState, useCallback, useEffect, useRef } from 'react';
|
||||
import {
|
||||
CloseOutlined,
|
||||
VideoCameraOutlined,
|
||||
StopOutlined,
|
||||
HomeOutlined,
|
||||
CameraOutlined,
|
||||
PauseCircleOutlined,
|
||||
CaretRightOutlined,
|
||||
FullscreenOutlined,
|
||||
FullscreenExitOutlined,
|
||||
ExpandOutlined,
|
||||
CompressOutlined,
|
||||
LoadingOutlined,
|
||||
ClockCircleOutlined,
|
||||
AimOutlined,
|
||||
DisconnectOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import { message, Modal, Tooltip, Spin } from 'antd';
|
||||
import { deviceApi } from '@/services/device';
|
||||
import { deviceControlWs } from '@/services/deviceControlWs';
|
||||
import { DroneData } from '../hooks/useDroneSSE';
|
||||
import WhepPlayer from './WhepPlayer';
|
||||
import styles from './LeftControlPanel.less';
|
||||
|
||||
interface LeftControlPanelProps {
|
||||
visible: boolean;
|
||||
onClose: () => void;
|
||||
device: any;
|
||||
realtimeData: any;
|
||||
videoStreamUrl?: string;
|
||||
droneData?: DroneData | null; // 从父组件接收无人机数据(SSE已在CesiumContainer中订阅)
|
||||
}
|
||||
|
||||
const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
|
||||
visible,
|
||||
onClose,
|
||||
device,
|
||||
realtimeData,
|
||||
videoStreamUrl,
|
||||
droneData, // 从父组件接收,无需自己订阅SSE
|
||||
}) => {
|
||||
const dockData = realtimeData?.rawData?.dockData;
|
||||
const rawDroneData = realtimeData?.rawData?.droneData;
|
||||
const deviceSn = device?.deviceSn;
|
||||
|
||||
const flightData = useMemo(() => {
|
||||
const data = droneData || rawDroneData;
|
||||
let gimbal: any = {};
|
||||
if (data) {
|
||||
['98-0-0','39-0-0','42-0-0','43-0-0','52-0-0','53-0-0'].some(k => {
|
||||
if (data[k]?.gimbal_pitch !== undefined) { gimbal = data[k]; return true; }
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
// 获取电池数据 - 兼容多种数据结构
|
||||
// 1. 直接结构: battery.capacity_percent, battery.voltage
|
||||
// 2. 数组结构: battery.batteries[0].capacity_percent, battery.batteries[0].voltage
|
||||
// 3. 机库数据: drone_battery_maintenance_info.batteries[0]
|
||||
let batteryPercent = 0;
|
||||
let batteryVoltage = 0;
|
||||
|
||||
if (data?.battery?.capacity_percent !== undefined) {
|
||||
batteryPercent = data.battery.capacity_percent;
|
||||
batteryVoltage = data.battery.voltage ?? 0;
|
||||
} else if (data?.battery?.batteries?.[0]) {
|
||||
batteryPercent = data.battery.batteries[0].capacity_percent ?? 0;
|
||||
batteryVoltage = data.battery.batteries[0].voltage ?? 0;
|
||||
} else if (data?.drone_battery_maintenance_info?.batteries?.[0]) {
|
||||
batteryPercent = data.drone_battery_maintenance_info.batteries[0].capacity_percent ?? 0;
|
||||
batteryVoltage = data.drone_battery_maintenance_info.batteries[0].voltage ?? 0;
|
||||
}
|
||||
|
||||
// 计算飞行剩余时间(基于电池百分比和平均消耗)
|
||||
// 假设满电可飞行约30分钟,根据剩余电量计算
|
||||
const remainMinutes = Math.floor((batteryPercent / 100) * 30);
|
||||
const remainSeconds = Math.floor(((batteryPercent / 100) * 30 - remainMinutes) * 60);
|
||||
|
||||
return {
|
||||
pitch: Number(data?.attitude_pitch ?? 0).toFixed(1),
|
||||
roll: Number(data?.attitude_roll ?? 0).toFixed(1),
|
||||
yaw: Number(data?.attitude_head ?? 0).toFixed(1),
|
||||
hSpeed: Number(data?.horizontal_speed ?? 0).toFixed(1),
|
||||
vSpeed: Number(data?.vertical_speed ?? 0).toFixed(1),
|
||||
alt: Number(data?.height ?? data?.elevation ?? 0).toFixed(1),
|
||||
dist: Number(data?.home_distance ?? 0).toFixed(1),
|
||||
sat: data?.position_state?.gps_number ?? 0,
|
||||
rtk: data?.position_state?.is_fixed === 2 ? 'FIX' : 'FLOAT',
|
||||
bat: batteryPercent,
|
||||
vol: (batteryVoltage / 1000).toFixed(1),
|
||||
mode: data?.mode_code === 6 ? '手动操控' : '自动航线',
|
||||
gimbalP: Number(gimbal?.gimbal_pitch ?? data?.gimbal_pitch ?? 0).toFixed(1),
|
||||
gimbalY: Number(gimbal?.gimbal_yaw ?? data?.gimbal_yaw ?? 0).toFixed(1),
|
||||
lat: Number(data?.latitude ?? 0).toFixed(6),
|
||||
lng: Number(data?.longitude ?? 0).toFixed(6),
|
||||
remainTime: `${remainMinutes}:${remainSeconds.toString().padStart(2, '0')}`,
|
||||
remainMinutes,
|
||||
};
|
||||
}, [droneData, rawDroneData]);
|
||||
|
||||
const [loading, setLoading] = useState<string | null>(null);
|
||||
const [isRecording, setIsRecording] = useState(false);
|
||||
const [wsConnected, setWsConnected] = useState(false);
|
||||
const [activeKeys, setActiveKeys] = useState<Set<string>>(new Set());
|
||||
const [drcMode, setDrcMode] = useState(false);
|
||||
const drcModeRef = useRef(false);
|
||||
const keyIntervalRef = useRef<NodeJS.Timeout | null>(null);
|
||||
const [drcLoading, setDrcLoading] = useState(false);
|
||||
|
||||
// 速度档位: 1=低速(偏移150), 2=高速(偏移300)
|
||||
// 低档: 1024±150 -> 874/1174
|
||||
// 高档: 1024±300 -> 724/1324
|
||||
const [speedLevel, setSpeedLevel] = useState<1 | 2>(1);
|
||||
const speedLevelRef = useRef<1 | 2>(1);
|
||||
|
||||
// 相机模式状态: 0=拍照模式, 1=录像模式, null=未知
|
||||
const [cameraMode, setCameraMode] = useState<number | null>(null);
|
||||
// 相机操作loading状态
|
||||
const [cameraLoading, setCameraLoading] = useState(false);
|
||||
|
||||
// 视频尺寸状态
|
||||
const [videoSize, setVideoSize] = useState<'normal' | 'large' | 'fullscreen'>('normal');
|
||||
|
||||
// 拖拽状态
|
||||
const [position, setPosition] = useState({ x: 0, y: 0 });
|
||||
const draggingRef = useRef(false);
|
||||
const lastPosRef = useRef({ x: 0, y: 0 });
|
||||
const containerRef = useRef<HTMLDivElement | null>(null);
|
||||
const panelRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (visible && deviceSn) {
|
||||
// 先注册状态监听,再连接(确保能收到连接成功的通知)
|
||||
const sub = deviceControlWs.onStatusChange(c => {
|
||||
setWsConnected(c);
|
||||
if(!c) { setDrcMode(false); drcModeRef.current = false; }
|
||||
});
|
||||
deviceControlWs.connect(deviceSn);
|
||||
// 注意:无人机SSE已在CesiumContainer中统一订阅,这里不再重复订阅
|
||||
return () => {
|
||||
sub();
|
||||
deviceControlWs.disconnect();
|
||||
};
|
||||
} else {
|
||||
setPosition({ x: 0, y: 0 });
|
||||
setVideoSize('normal');
|
||||
}
|
||||
}, [visible, deviceSn]);
|
||||
|
||||
// 全屏状态监听
|
||||
useEffect(() => {
|
||||
const handleFullscreenChange = () => {
|
||||
if (!document.fullscreenElement && videoSize === 'fullscreen') {
|
||||
setVideoSize('normal');
|
||||
}
|
||||
};
|
||||
document.addEventListener('fullscreenchange', handleFullscreenChange);
|
||||
return () => document.removeEventListener('fullscreenchange', handleFullscreenChange);
|
||||
}, [videoSize]);
|
||||
|
||||
// ESC退出放大模式
|
||||
useEffect(() => {
|
||||
const handleEsc = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape' && videoSize === 'large') {
|
||||
setVideoSize('normal');
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', handleEsc);
|
||||
return () => window.removeEventListener('keydown', handleEsc);
|
||||
}, [videoSize]);
|
||||
|
||||
// 自动聚焦面板,确保键盘事件能够响应
|
||||
useEffect(() => {
|
||||
if (!visible) return;
|
||||
|
||||
// 面板可见时自动聚焦
|
||||
const focusPanel = () => {
|
||||
if (panelRef.current && document.activeElement !== panelRef.current) {
|
||||
panelRef.current.focus();
|
||||
}
|
||||
};
|
||||
|
||||
// 初始聚焦
|
||||
setTimeout(focusPanel, 100);
|
||||
|
||||
// 窗口重新获得焦点时自动聚焦面板
|
||||
const handleWindowFocus = () => {
|
||||
setTimeout(focusPanel, 50);
|
||||
};
|
||||
|
||||
// 页面可见性变化时自动聚焦面板
|
||||
const handleVisibilityChange = () => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
setTimeout(focusPanel, 50);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('focus', handleWindowFocus);
|
||||
document.addEventListener('visibilitychange', handleVisibilityChange);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('focus', handleWindowFocus);
|
||||
document.removeEventListener('visibilitychange', handleVisibilityChange);
|
||||
};
|
||||
}, [visible]);
|
||||
|
||||
const cmd = async (func: Function, key: string, msg: string) => {
|
||||
if (!deviceSn) return;
|
||||
setLoading(key);
|
||||
try {
|
||||
await func(deviceSn);
|
||||
message.success(msg);
|
||||
} catch (e) {
|
||||
message.error('指令失败');
|
||||
} finally {
|
||||
setLoading(null);
|
||||
}
|
||||
};
|
||||
|
||||
// 等待一段时间(用于命令间隔)
|
||||
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
|
||||
|
||||
// 切换相机模式
|
||||
const switchCameraMode = async (targetMode: number): Promise<boolean> => {
|
||||
if (!deviceSn) return false;
|
||||
try {
|
||||
const res = await deviceApi.switchCameraMode(deviceSn, targetMode);
|
||||
if (res.code === 0 || res.resp_code === 0) {
|
||||
setCameraMode(targetMode);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
} catch (e) {
|
||||
console.error('切换相机模式失败:', e);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// 拍照(先切换到拍照模式,再拍照)
|
||||
const handleTakePhoto = async () => {
|
||||
if (!deviceSn || cameraLoading) return;
|
||||
setCameraLoading(true);
|
||||
|
||||
try {
|
||||
// 1. 先切换到拍照模式 (mode=0)
|
||||
message.loading({ content: '切换拍照模式...', key: 'photo', duration: 0 });
|
||||
const switchResult = await switchCameraMode(0);
|
||||
if (!switchResult) {
|
||||
message.error({ content: '切换拍照模式失败', key: 'photo' });
|
||||
return;
|
||||
}
|
||||
|
||||
// 2. 等待500ms让设备切换完成
|
||||
await delay(500);
|
||||
|
||||
// 3. 执行拍照
|
||||
message.loading({ content: '正在拍照...', key: 'photo', duration: 0 });
|
||||
const photoRes = await deviceApi.takePhoto(deviceSn);
|
||||
if (photoRes.code === 0 || photoRes.resp_code === 0) {
|
||||
message.success({ content: '拍照成功', key: 'photo' });
|
||||
} else {
|
||||
message.error({ content: '拍照失败', key: 'photo' });
|
||||
}
|
||||
} catch (e) {
|
||||
message.error({ content: '拍照失败', key: 'photo' });
|
||||
} finally {
|
||||
setCameraLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 开始录像(先切换到录像模式,再开始录像)
|
||||
const handleStartRecording = async () => {
|
||||
if (!deviceSn || cameraLoading) return;
|
||||
setCameraLoading(true);
|
||||
|
||||
try {
|
||||
// 1. 先切换到录像模式 (mode=1)
|
||||
message.loading({ content: '切换录像模式...', key: 'record', duration: 0 });
|
||||
const switchResult = await switchCameraMode(1);
|
||||
if (!switchResult) {
|
||||
message.error({ content: '切换录像模式失败', key: 'record' });
|
||||
return;
|
||||
}
|
||||
|
||||
// 2. 等待500ms让设备切换完成
|
||||
await delay(500);
|
||||
|
||||
// 3. 执行开始录像
|
||||
message.loading({ content: '开始录像...', key: 'record', duration: 0 });
|
||||
const recordRes = await deviceApi.startRecording(deviceSn);
|
||||
if (recordRes.code === 0 || recordRes.resp_code === 0) {
|
||||
setIsRecording(true);
|
||||
message.success({ content: '开始录像', key: 'record' });
|
||||
} else {
|
||||
message.error({ content: '开始录像失败', key: 'record' });
|
||||
}
|
||||
} catch (e) {
|
||||
message.error({ content: '开始录像失败', key: 'record' });
|
||||
} finally {
|
||||
setCameraLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 停止录像
|
||||
const handleStopRecording = async () => {
|
||||
if (!deviceSn || cameraLoading) return;
|
||||
setCameraLoading(true);
|
||||
|
||||
try {
|
||||
message.loading({ content: '停止录像...', key: 'record', duration: 0 });
|
||||
const res = await deviceApi.stopRecording(deviceSn);
|
||||
if (res.code === 0 || res.resp_code === 0) {
|
||||
setIsRecording(false);
|
||||
message.success({ content: '停止录像成功', key: 'record' });
|
||||
} else {
|
||||
message.error({ content: '停止录像失败', key: 'record' });
|
||||
}
|
||||
} catch (e) {
|
||||
message.error({ content: '停止录像失败', key: 'record' });
|
||||
} finally {
|
||||
setCameraLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 处理录像按钮点击
|
||||
const handleRecordClick = () => {
|
||||
if (isRecording) {
|
||||
handleStopRecording();
|
||||
} else {
|
||||
handleStartRecording();
|
||||
}
|
||||
};
|
||||
|
||||
// 进入指令飞行模式(DRC模式)
|
||||
const handleEnterDrcMode = async () => {
|
||||
if (!deviceSn || !wsConnected || drcLoading) return;
|
||||
|
||||
setDrcLoading(true);
|
||||
try {
|
||||
message.loading({ content: '正在进入指令飞行模式...', key: 'drc', duration: 0 });
|
||||
const res = await deviceApi.enterDrcMode(deviceSn);
|
||||
if (res.code === 0 || res.resp_code === 0) {
|
||||
setDrcMode(true);
|
||||
drcModeRef.current = true;
|
||||
message.success({ content: '已进入指令飞行模式,可使用键盘控制无人机', key: 'drc' });
|
||||
} else {
|
||||
message.error({ content: res.msg || '进入指令飞行模式失败', key: 'drc' });
|
||||
}
|
||||
} catch (e) {
|
||||
message.error({ content: '进入指令飞行模式失败', key: 'drc' });
|
||||
} finally {
|
||||
setDrcLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 退出指令飞行模式
|
||||
const handleExitDrcMode = () => {
|
||||
setDrcMode(false);
|
||||
drcModeRef.current = false;
|
||||
setActiveKeys(new Set());
|
||||
message.info('已退出指令飞行模式');
|
||||
};
|
||||
|
||||
// 根据速度档位获取偏移量
|
||||
// 低档: ±150 -> 874/1174
|
||||
// 高档: ±300 -> 724/1324
|
||||
const getSpeedOffset = useCallback(() => {
|
||||
return speedLevelRef.current === 1 ? 150 : 300;
|
||||
}, []);
|
||||
|
||||
// 切换速度档位 (X键)
|
||||
const cycleSpeedLevel = useCallback(() => {
|
||||
const nextLevel = speedLevelRef.current === 1 ? 2 : 1 as 1 | 2;
|
||||
speedLevelRef.current = nextLevel;
|
||||
setSpeedLevel(nextLevel);
|
||||
const speedNames = { 1: '低速', 2: '高速' };
|
||||
message.info(`速度切换: ${speedNames[nextLevel]}`);
|
||||
}, []);
|
||||
|
||||
const handleStick = useCallback(async (dir: string, type: 'stick'|'gimbal') => {
|
||||
if (!deviceSn || !wsConnected) return;
|
||||
// 必须先进入DRC模式才能控制
|
||||
if (!drcModeRef.current) {
|
||||
return;
|
||||
}
|
||||
const offset = getSpeedOffset();
|
||||
let p: any = { roll: 1024, pitch: 1024, throttle: 1024, yaw: 1024 };
|
||||
if (type === 'gimbal') {
|
||||
const s = 20;
|
||||
p = { pitchSpeed: 0, yawSpeed: 0 };
|
||||
if (dir === 'up') p.pitchSpeed = s; // 云台上仰
|
||||
if (dir === 'down') p.pitchSpeed = -s; // 云台下俯
|
||||
if (dir === 'left') p.yawSpeed = -s; // 云台左转
|
||||
if (dir === 'right') p.yawSpeed = s; // 云台右转
|
||||
deviceControlWs.sendGimbalControl(p);
|
||||
} else {
|
||||
// W/S - 前进/后退 (pitch)
|
||||
if (dir === 'fwd') p.pitch += offset;
|
||||
if (dir === 'back') p.pitch -= offset;
|
||||
// A/D - 向左/向右平移 (roll)
|
||||
if (dir === 'left') p.roll -= offset;
|
||||
if (dir === 'right') p.roll += offset;
|
||||
// Q/E - 机头向左/向右转 (yaw)
|
||||
if (dir === 'yawLeft') p.yaw -= offset;
|
||||
if (dir === 'yawRight') p.yaw += offset;
|
||||
// Z/C - 降低/升高 (throttle)
|
||||
if (dir === 'up') p.throttle += offset;
|
||||
if (dir === 'down') p.throttle -= offset;
|
||||
deviceControlWs.sendStickControl(p);
|
||||
}
|
||||
}, [deviceSn, wsConnected, getSpeedOffset]);
|
||||
|
||||
// 键盘控制映射
|
||||
// 飞行器控制: W前进 S后退 A左移 D右移 Q机头左转 E机头右转 Z降低 C升高 X切换速度
|
||||
// 云台控制: 上下左右箭头
|
||||
useEffect(() => {
|
||||
if (!visible) return;
|
||||
const map: Record<string, [string, 'stick' | 'gimbal']> = {
|
||||
// 飞行器控制
|
||||
'w': ['fwd', 'stick'], // 前进
|
||||
's': ['back', 'stick'], // 后退
|
||||
'a': ['left', 'stick'], // 向左平移
|
||||
'd': ['right', 'stick'], // 向右平移
|
||||
'q': ['yawLeft', 'stick'], // 机头向左转
|
||||
'e': ['yawRight', 'stick'], // 机头向右转
|
||||
'z': ['down', 'stick'], // 降低高度
|
||||
'c': ['up', 'stick'], // 升高高度
|
||||
// 云台控制
|
||||
'arrowup': ['up', 'gimbal'], // 云台上仰
|
||||
'arrowdown': ['down', 'gimbal'], // 云台下俯
|
||||
'arrowleft': ['left', 'gimbal'], // 云台左转
|
||||
'arrowright': ['right', 'gimbal'] // 云台右转
|
||||
};
|
||||
|
||||
const down = (e: KeyboardEvent) => {
|
||||
const k = e.key.toLowerCase();
|
||||
// X键切换速度档位 (只在按下时触发一次)
|
||||
if (k === 'x' && !e.repeat) {
|
||||
cycleSpeedLevel();
|
||||
return;
|
||||
}
|
||||
// 阻止方向键的默认滚动行为
|
||||
if (['arrowup', 'arrowdown', 'arrowleft', 'arrowright'].includes(k)) {
|
||||
e.preventDefault();
|
||||
}
|
||||
if (map[k] && !activeKeys.has(k)) {
|
||||
setActiveKeys(p => new Set(p).add(k));
|
||||
}
|
||||
};
|
||||
|
||||
const up = (e: KeyboardEvent) => {
|
||||
const k = e.key.toLowerCase();
|
||||
if (map[k]) {
|
||||
setActiveKeys(p => {
|
||||
const n = new Set(p);
|
||||
n.delete(k);
|
||||
return n;
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('keydown', down);
|
||||
window.addEventListener('keyup', up);
|
||||
|
||||
keyIntervalRef.current = setInterval(() => {
|
||||
activeKeys.forEach(k => {
|
||||
if (map[k]) {
|
||||
const [dir, type] = map[k];
|
||||
handleStick(dir, type);
|
||||
}
|
||||
});
|
||||
}, 100);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('keydown', down);
|
||||
window.removeEventListener('keyup', up);
|
||||
if (keyIntervalRef.current) clearInterval(keyIntervalRef.current);
|
||||
};
|
||||
}, [visible, activeKeys, wsConnected, handleStick, cycleSpeedLevel]);
|
||||
|
||||
// 拖拽处理 - 使用 RAF 优化性能
|
||||
const rafRef = useRef<number | null>(null);
|
||||
const pendingPosRef = useRef({ x: 0, y: 0 });
|
||||
|
||||
const handleMouseDown = (e: React.MouseEvent) => {
|
||||
if (videoSize !== 'normal') return;
|
||||
e.preventDefault();
|
||||
draggingRef.current = true;
|
||||
lastPosRef.current = { x: e.clientX, y: e.clientY };
|
||||
pendingPosRef.current = { ...position };
|
||||
document.body.style.userSelect = 'none';
|
||||
document.body.style.cursor = 'grabbing';
|
||||
document.addEventListener('mousemove', handleMouseMove);
|
||||
document.addEventListener('mouseup', handleMouseUp);
|
||||
};
|
||||
|
||||
const handleMouseMove = useCallback((e: MouseEvent) => {
|
||||
if (!draggingRef.current) return;
|
||||
const dx = e.clientX - lastPosRef.current.x;
|
||||
const dy = e.clientY - lastPosRef.current.y;
|
||||
lastPosRef.current = { x: e.clientX, y: e.clientY };
|
||||
pendingPosRef.current = {
|
||||
x: pendingPosRef.current.x + dx,
|
||||
y: pendingPosRef.current.y + dy
|
||||
};
|
||||
|
||||
if (rafRef.current) cancelAnimationFrame(rafRef.current);
|
||||
rafRef.current = requestAnimationFrame(() => {
|
||||
setPosition({ ...pendingPosRef.current });
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleMouseUp = useCallback(() => {
|
||||
draggingRef.current = false;
|
||||
document.body.style.userSelect = '';
|
||||
document.body.style.cursor = '';
|
||||
document.removeEventListener('mousemove', handleMouseMove);
|
||||
document.removeEventListener('mouseup', handleMouseUp);
|
||||
if (rafRef.current) {
|
||||
cancelAnimationFrame(rafRef.current);
|
||||
rafRef.current = null;
|
||||
}
|
||||
}, [handleMouseMove]);
|
||||
|
||||
// 关闭面板时,断开设备控制连接
|
||||
const handleClose = () => {
|
||||
// 1. 断开设备控制WebSocket服务
|
||||
deviceControlWs.disconnect();
|
||||
// 2. 退出DRC模式
|
||||
setDrcMode(false);
|
||||
drcModeRef.current = false;
|
||||
// 3. 调用父组件的关闭回调
|
||||
// 注意:无人机SSE由CesiumContainer统一管理,这里不处理
|
||||
onClose();
|
||||
};
|
||||
|
||||
// 视频尺寸切换
|
||||
const handleVideoSizeToggle = () => {
|
||||
if (videoSize === 'normal') {
|
||||
setVideoSize('large');
|
||||
} else {
|
||||
setVideoSize('normal');
|
||||
}
|
||||
};
|
||||
|
||||
// 全屏切换
|
||||
const handleFullscreen = async () => {
|
||||
if (videoSize === 'fullscreen') {
|
||||
if (document.fullscreenElement) {
|
||||
await document.exitFullscreen();
|
||||
}
|
||||
setVideoSize('normal');
|
||||
} else {
|
||||
if (containerRef.current) {
|
||||
await containerRef.current.requestFullscreen();
|
||||
setVideoSize('fullscreen');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 获取尺寸类名
|
||||
const getSizeClassName = () => {
|
||||
if (videoSize === 'large') return styles.large;
|
||||
if (videoSize === 'fullscreen') return styles.fullscreen;
|
||||
return '';
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={(el) => {
|
||||
containerRef.current = el;
|
||||
panelRef.current = el;
|
||||
}}
|
||||
tabIndex={-1}
|
||||
className={`${styles.controlPanelContainer} ${visible ? styles.visible : ''} ${getSizeClassName()}`}
|
||||
style={{
|
||||
transform: visible && videoSize === 'normal' ? `translate(${position.x}px, ${position.y}px)` : undefined,
|
||||
outline: 'none', // 移除聚焦时的默认轮廓
|
||||
}}
|
||||
>
|
||||
{/* 视频层 */}
|
||||
<div className={styles.videoLayer}>
|
||||
{videoStreamUrl ? (
|
||||
<WhepPlayer url={videoStreamUrl} autoPlay={true} muted={true} videoOnly={true} />
|
||||
) : (
|
||||
<div className={styles.videoPlaceholder}>
|
||||
<div className={styles.placeholderContent}>
|
||||
<VideoCameraOutlined className={styles.icon} />
|
||||
<span>等待视频信号...</span>
|
||||
<div className={styles.loadingDots}>
|
||||
<span></span><span></span><span></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 视频控制按钮组 */}
|
||||
<div className={styles.videoControls}>
|
||||
<Tooltip title={videoSize === 'large' ? '还原' : '放大'}>
|
||||
<button className={styles.videoBtn} onClick={handleVideoSizeToggle}>
|
||||
{videoSize === 'large' ? <CompressOutlined /> : <ExpandOutlined />}
|
||||
</button>
|
||||
</Tooltip>
|
||||
<Tooltip title={videoSize === 'fullscreen' ? '退出全屏' : '全屏'}>
|
||||
<button className={styles.videoBtn} onClick={handleFullscreen}>
|
||||
{videoSize === 'fullscreen' ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* UI 覆盖层 */}
|
||||
<div className={styles.uiOverlay}>
|
||||
{/* 顶部栏 */}
|
||||
<div className={styles.topBar} onMouseDown={handleMouseDown}>
|
||||
<div className={styles.topLeft}>
|
||||
<div className={`${styles.modeTag} ${drcMode ? styles.manual : ''}`}>
|
||||
<span className={styles.modeDot}></span>
|
||||
{drcMode ? '手动接管' : '自动巡航'}
|
||||
</div>
|
||||
<div className={styles.statusGroup}>
|
||||
<div className={`${styles.statusItem} ${wsConnected ? styles.online : styles.offline}`}>
|
||||
<span className={styles.dot}></span>
|
||||
<span>{wsConnected ? '控制链路' : '链路断开'}</span>
|
||||
</div>
|
||||
<div className={`${styles.statusItem} ${flightData.sat > 10 ? styles.good : styles.warn}`}>
|
||||
<span>GPS</span>
|
||||
<span className={styles.value}>{flightData.sat}</span>
|
||||
</div>
|
||||
<div className={styles.statusItem}>
|
||||
<span>RTK</span>
|
||||
<span className={`${styles.value} ${flightData.rtk === 'FIX' ? styles.fix : ''}`}>{flightData.rtk}</span>
|
||||
</div>
|
||||
</div>
|
||||
{/* 键盘快捷键提示 */}
|
||||
<Tooltip
|
||||
title={
|
||||
<div style={{ fontSize: '12px', lineHeight: '1.6' }}>
|
||||
{!drcMode ? (
|
||||
<div style={{ color: '#ffa502' }}>请先点击底部"手动控制"按钮进入指令飞行模式</div>
|
||||
) : (
|
||||
<>
|
||||
<div><b>飞行控制:</b></div>
|
||||
<div>W/S: 前进/后退</div>
|
||||
<div>A/D: 左移/右移</div>
|
||||
<div>Q/E: 机头左转/右转</div>
|
||||
<div>Z/C: 降低/升高</div>
|
||||
<div>X: 切换速度档位</div>
|
||||
<div style={{ marginTop: '4px' }}><b>云台控制:</b></div>
|
||||
<div>方向键: 上/下/左/右</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
placement="bottom"
|
||||
>
|
||||
<div className={`${styles.keyboardHint} ${drcMode ? styles.active : ''}`}>
|
||||
<span className={styles.keyIcon}>⌨</span>
|
||||
<span>{drcMode ? '键盘已启用' : '键盘操控'}</span>
|
||||
</div>
|
||||
</Tooltip>
|
||||
</div>
|
||||
<div className={styles.topRight}>
|
||||
<div className={styles.flightTime}>
|
||||
<ClockCircleOutlined />
|
||||
<span className={styles.time}>{flightData.remainTime}</span>
|
||||
</div>
|
||||
<div className={styles.batteryDisplay}>
|
||||
<div className={styles.batteryIcon}>
|
||||
<div className={styles.batteryLevel} style={{ width: `${flightData.bat}%` }}></div>
|
||||
</div>
|
||||
<div className={styles.batteryInfo}>
|
||||
<span className={styles.percent}>{flightData.bat}%</span>
|
||||
<span className={styles.voltage}>{flightData.vol}V</span>
|
||||
</div>
|
||||
</div>
|
||||
<button className={styles.closeBtn} onClick={handleClose} onMouseDown={e => e.stopPropagation()}>
|
||||
<CloseOutlined />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 中心HUD */}
|
||||
<div className={styles.centerHUD}>
|
||||
<div className={styles.crosshair}>
|
||||
<div className={styles.horizontalLine}></div>
|
||||
<div className={styles.verticalLine}></div>
|
||||
<div className={styles.centerDot}></div>
|
||||
<div className={styles.cornerBracket + ' ' + styles.topLeft}></div>
|
||||
<div className={styles.cornerBracket + ' ' + styles.topRight}></div>
|
||||
<div className={styles.cornerBracket + ' ' + styles.bottomLeft}></div>
|
||||
<div className={styles.cornerBracket + ' ' + styles.bottomRight}></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 左侧飞行数据 */}
|
||||
<div className={styles.leftDataPanel}>
|
||||
<div className={styles.dataCard}>
|
||||
<div className={styles.dataRow}>
|
||||
<span className={styles.label}>水平速度</span>
|
||||
<span className={styles.value}>{flightData.hSpeed}<span className={styles.unit}>m/s</span></span>
|
||||
</div>
|
||||
<div className={styles.dataRow}>
|
||||
<span className={styles.label}>垂直速度</span>
|
||||
<span className={styles.value}>{flightData.vSpeed}<span className={styles.unit}>m/s</span></span>
|
||||
</div>
|
||||
<div className={styles.divider}></div>
|
||||
<div className={styles.dataRow}>
|
||||
<span className={styles.label}>返航距离</span>
|
||||
<span className={styles.value}>{flightData.dist}<span className={styles.unit}>m</span></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 右侧姿态数据 */}
|
||||
<div className={styles.rightDataPanel}>
|
||||
<div className={styles.dataCard}>
|
||||
<div className={styles.dataRow}>
|
||||
<span className={styles.label}>高度</span>
|
||||
<span className={styles.value}>{flightData.alt}<span className={styles.unit}>m</span></span>
|
||||
</div>
|
||||
<div className={styles.divider}></div>
|
||||
<div className={styles.attitudeRow}>
|
||||
<div className={styles.attItem}>
|
||||
<span className={styles.attLabel}>P</span>
|
||||
<span className={styles.attValue}>{flightData.pitch}°</span>
|
||||
</div>
|
||||
<div className={styles.attItem}>
|
||||
<span className={styles.attLabel}>R</span>
|
||||
<span className={styles.attValue}>{flightData.roll}°</span>
|
||||
</div>
|
||||
<div className={styles.attItem}>
|
||||
<span className={styles.attLabel}>Y</span>
|
||||
<span className={styles.attValue}>{flightData.yaw}°</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 底部控制栏 */}
|
||||
<div className={styles.bottomControls}>
|
||||
{/* 左侧快捷操作 */}
|
||||
<div className={styles.quickActions}>
|
||||
<Tooltip title="一键返航" placement="top">
|
||||
<button
|
||||
className={styles.actionBtn}
|
||||
onClick={() => Modal.confirm({
|
||||
title: '确认返航?',
|
||||
content: '无人机将自动返回起飞点',
|
||||
okText: '确认',
|
||||
cancelText: '取消',
|
||||
onOk: () => cmd(deviceApi.returnHome, 'ret', '返航指令已发送')
|
||||
})}
|
||||
>
|
||||
<HomeOutlined />
|
||||
<span>返航</span>
|
||||
</button>
|
||||
</Tooltip>
|
||||
<Tooltip title="取消返航" placement="top">
|
||||
<button className={styles.actionBtn} onClick={() => cmd(deviceApi.cancelReturnHome, 'cret', '取消返航')}>
|
||||
<StopOutlined />
|
||||
<span>取消</span>
|
||||
</button>
|
||||
</Tooltip>
|
||||
<Tooltip title="紧急悬停" placement="top">
|
||||
<button className={`${styles.actionBtn} ${styles.danger}`} onClick={() => cmd(deviceApi.pause, 'p', '悬停')}>
|
||||
<PauseCircleOutlined />
|
||||
<span>悬停</span>
|
||||
</button>
|
||||
</Tooltip>
|
||||
<Tooltip title="恢复航线" placement="top">
|
||||
<button className={styles.actionBtn} onClick={() => cmd(deviceApi.resume, 'r', '恢复航线')}>
|
||||
<CaretRightOutlined />
|
||||
<span>继续</span>
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
{/* 中间坐标和控制显示 */}
|
||||
<div className={styles.centerInfo}>
|
||||
<div className={styles.coordsDisplay}>
|
||||
<span className={styles.coord}>
|
||||
<span className={styles.coordLabel}>经度</span>
|
||||
<span className={styles.coordValue}>{flightData.lng}</span>
|
||||
</span>
|
||||
<span className={styles.coord}>
|
||||
<span className={styles.coordLabel}>纬度</span>
|
||||
<span className={styles.coordValue}>{flightData.lat}</span>
|
||||
</span>
|
||||
</div>
|
||||
{/* 手动控制和速度切换 */}
|
||||
<div className={styles.controlRow}>
|
||||
{/* 手动控制按钮 */}
|
||||
<Tooltip
|
||||
title={
|
||||
!wsConnected
|
||||
? '控制链路未连接,无法进入指令飞行模式'
|
||||
: drcMode
|
||||
? '点击退出指令飞行模式'
|
||||
: '点击进入指令飞行模式,可使用键盘控制无人机'
|
||||
}
|
||||
placement="top"
|
||||
>
|
||||
<button
|
||||
className={`${styles.drcControlBtn} ${drcMode ? styles.active : ''} ${!wsConnected ? styles.disabled : ''}`}
|
||||
onClick={drcMode ? handleExitDrcMode : handleEnterDrcMode}
|
||||
disabled={!wsConnected || drcLoading}
|
||||
>
|
||||
{drcLoading ? <LoadingOutlined spin /> : (drcMode ? <DisconnectOutlined /> : <AimOutlined />)}
|
||||
<span>{drcMode ? '退出控制' : '手动控制'}</span>
|
||||
</button>
|
||||
</Tooltip>
|
||||
{/* 速度切换 */}
|
||||
<Tooltip title="按 X 键切换速度档位" placement="top">
|
||||
<div className={`${styles.speedIndicator} ${!drcMode ? styles.disabled : ''}`}>
|
||||
<span className={styles.speedLabel}>速度</span>
|
||||
<div className={styles.speedBars}>
|
||||
<span className={`${styles.speedBar} ${speedLevel >= 1 ? styles.active : ''}`}></span>
|
||||
<span className={`${styles.speedBar} ${speedLevel >= 2 ? styles.active : ''}`}></span>
|
||||
</div>
|
||||
<span className={styles.speedText}>
|
||||
{speedLevel === 1 ? '低' : '高'}
|
||||
</span>
|
||||
</div>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 右侧相机控制 */}
|
||||
<div className={styles.cameraControls}>
|
||||
<Tooltip title={isRecording ? '录像中,请先停止录像' : (cameraLoading ? '处理中...' : '拍照')} placement="top">
|
||||
<button
|
||||
className={`${styles.cameraBtn} ${(cameraLoading || isRecording) ? styles.disabled : ''}`}
|
||||
onClick={handleTakePhoto}
|
||||
disabled={cameraLoading || isRecording}
|
||||
>
|
||||
{cameraLoading && !isRecording ? (
|
||||
<LoadingOutlined spin />
|
||||
) : (
|
||||
<CameraOutlined />
|
||||
)}
|
||||
</button>
|
||||
</Tooltip>
|
||||
<Tooltip title={cameraLoading ? '处理中...' : (isRecording ? '停止录像' : '开始录像')} placement="top">
|
||||
<button
|
||||
className={`${styles.cameraBtn} ${styles.recordBtn} ${isRecording ? styles.recording : ''} ${cameraLoading ? styles.disabled : ''}`}
|
||||
onClick={handleRecordClick}
|
||||
disabled={cameraLoading}
|
||||
>
|
||||
{cameraLoading && (isRecording || cameraMode === 1) ? (
|
||||
<LoadingOutlined spin />
|
||||
) : (
|
||||
<div className={styles.recordDot}></div>
|
||||
)}
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default LeftControlPanel;
|
||||
+368
@@ -0,0 +1,368 @@
|
||||
// Ant Design 5.x 不再使用 Less 变量,使用自定义变量
|
||||
@primary-color: #1890ff;
|
||||
|
||||
@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: 360px; // 减小宽度避免滚动条
|
||||
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 {
|
||||
padding: 16px 0;
|
||||
margin-right: 24px;
|
||||
transition: all 0.3s;
|
||||
|
||||
.ant-tabs-tab-btn {
|
||||
color: #ffffff !important;
|
||||
font-weight: 600 !important;
|
||||
font-size: 14px !important;
|
||||
}
|
||||
|
||||
&:hover .ant-tabs-tab-btn {
|
||||
color: #ffdd00 !important;
|
||||
}
|
||||
}
|
||||
.ant-tabs-tab-active .ant-tabs-tab-btn {
|
||||
color: #ffdd00 !important;
|
||||
font-weight: 700 !important;
|
||||
}
|
||||
.ant-tabs-ink-bar {
|
||||
background: #ffdd00;
|
||||
height: 3px;
|
||||
}
|
||||
}
|
||||
|
||||
.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;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
|
||||
.takeoffBtn {
|
||||
padding: 4px 10px;
|
||||
font-size: 11px;
|
||||
background: linear-gradient(135deg, rgba(255, 77, 79, 0.25), rgba(0, 255, 136, 0.25));
|
||||
border: 1px solid @neon-green;
|
||||
color: @neon-green;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
text-transform: none;
|
||||
letter-spacing: 0;
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
|
||||
&::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: linear-gradient(90deg, @neon-red, @neon-green);
|
||||
opacity: 0.15;
|
||||
z-index: -1;
|
||||
}
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background: linear-gradient(135deg, rgba(255, 77, 79, 0.35), rgba(0, 255, 136, 0.35));
|
||||
box-shadow: 0 0 12px rgba(0, 255, 136, 0.4), 0 0 8px rgba(255, 77, 79, 0.3);
|
||||
border-color: @neon-green;
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
filter: grayscale(0.5);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.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: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
margin-top: 24px;
|
||||
|
||||
.actionRow {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
|
||||
button {
|
||||
flex: 1;
|
||||
}
|
||||
}
|
||||
|
||||
button {
|
||||
padding: 10px 12px;
|
||||
background: rgba(0, 240, 255, 0.1);
|
||||
border: 1px solid rgba(0, 240, 255, 0.3);
|
||||
color: @cyan;
|
||||
font-weight: 600;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
white-space: nowrap;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background: rgba(0, 240, 255, 0.2);
|
||||
box-shadow: 0 0 15px rgba(0, 240, 255, 0.2);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
&: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); }
|
||||
}
|
||||
|
||||
&.task {
|
||||
background: rgba(255, 170, 0, 0.15);
|
||||
border-color: @neon-orange;
|
||||
color: @neon-orange;
|
||||
&:hover:not(:disabled) {
|
||||
background: rgba(255, 170, 0, 0.25);
|
||||
box-shadow: 0 0 15px rgba(255, 170, 0, 0.2);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+384
@@ -0,0 +1,384 @@
|
||||
import React, { useState, useEffect, useMemo } from 'react';
|
||||
import { Spin, Empty, message, Tooltip, Tabs, Progress, Modal } from 'antd';
|
||||
import type { TabsProps } from 'antd';
|
||||
import {
|
||||
CloseOutlined,
|
||||
EnvironmentOutlined,
|
||||
RocketOutlined,
|
||||
VideoCameraOutlined,
|
||||
HomeOutlined,
|
||||
ThunderboltOutlined,
|
||||
DashboardOutlined,
|
||||
SignalFilled,
|
||||
LoadingOutlined,
|
||||
AimOutlined,
|
||||
UnorderedListOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import { deviceApi } from '@/services/device';
|
||||
import { ordersApi } from '@/services/orders';
|
||||
import { saveMission, MissionType } from '@/services/mission';
|
||||
import useDeviceSSE from '../hooks/useDeviceSSE';
|
||||
import styles from './RightPanel.less';
|
||||
|
||||
interface RightPanelProps {
|
||||
visible: boolean;
|
||||
tourism: any;
|
||||
onClose: () => void;
|
||||
onControlClick: (device: any, realtimeData: any) => void;
|
||||
onTaskPanelOpen?: (device: any, dockData: any, tourismId?: number) => void; // 打开任务管理面板回调
|
||||
viewer?: any; // Cesium Viewer 实例
|
||||
Cesium?: any; // Cesium 库
|
||||
}
|
||||
|
||||
const RightPanel: React.FC<RightPanelProps> = ({
|
||||
visible,
|
||||
tourism,
|
||||
onClose,
|
||||
onControlClick,
|
||||
onTaskPanelOpen,
|
||||
viewer,
|
||||
Cesium
|
||||
}) => {
|
||||
const [deviceList, setDeviceList] = useState<any[]>([]);
|
||||
const [selectedDeviceSn, setSelectedDeviceSn] = useState<string>('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [takeoffLoading, setTakeoffLoading] = 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);
|
||||
}
|
||||
};
|
||||
|
||||
// 关闭面板时,主动断开SSE连接
|
||||
const handleClose = () => {
|
||||
// 先断开SSE连接
|
||||
if (selectedDeviceSn) {
|
||||
disconnectSSE(selectedDeviceSn);
|
||||
}
|
||||
// 然后调用父组件的关闭回调
|
||||
onClose();
|
||||
};
|
||||
|
||||
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 handleTakeoff = () => {
|
||||
const dockData = realtimeData?.rawData?.dockData;
|
||||
|
||||
// 检查机库状态
|
||||
if (dockData?.mode_code !== 0) {
|
||||
message.warning('机库正在执行任务,无法起飞');
|
||||
return;
|
||||
}
|
||||
|
||||
// 只有明确知道无人机不在库时才阻止(值为0时)
|
||||
if (dockData?.drone_in_dock === 0) {
|
||||
message.warning('无人机不在库,无法起飞');
|
||||
return;
|
||||
}
|
||||
|
||||
// 获取机库位置信息
|
||||
const dockLatitude = dockData?.latitude || realtimeData?.gps?.latitude;
|
||||
const dockLongitude = dockData?.longitude || realtimeData?.gps?.longitude;
|
||||
const dockHeight = dockData?.height || realtimeData?.gps?.altitude || 0;
|
||||
|
||||
if (!dockLatitude || !dockLongitude) {
|
||||
message.error('无法获取机库位置信息');
|
||||
return;
|
||||
}
|
||||
|
||||
const targetHeight = dockHeight + 30;
|
||||
|
||||
// 弹窗确认
|
||||
Modal.confirm({
|
||||
title: '确认一键起飞',
|
||||
content: (
|
||||
<div>
|
||||
<p>无人机将自动开机并起飞到指定位置</p>
|
||||
<p style={{ fontSize: 12, color: '#666' }}>
|
||||
目标坐标: {dockLatitude.toFixed(6)}, {dockLongitude.toFixed(6)}<br />
|
||||
目标高度: {targetHeight.toFixed(1)}m (机库高度+30m)
|
||||
</p>
|
||||
</div>
|
||||
),
|
||||
okText: '确认起飞',
|
||||
cancelText: '取消',
|
||||
onOk: async () => {
|
||||
setTakeoffLoading(true);
|
||||
try {
|
||||
// 创建一键起飞任务(后端会自动执行起飞命令)
|
||||
const res = await saveMission({
|
||||
deviceSn: selectedDeviceSn,
|
||||
missionType: MissionType.TAKEOFF,
|
||||
missionName: '一键起飞任务',
|
||||
tourismId: tourism?.id,
|
||||
targetLatitude: dockLatitude,
|
||||
targetLongitude: dockLongitude,
|
||||
targetHeight: targetHeight,
|
||||
});
|
||||
|
||||
// 兼容两种响应格式:resp_code/resp_msg 或 code/msg
|
||||
const code = res.resp_code !== undefined ? res.resp_code : res.resp_code;
|
||||
const msg = res.resp_msg !== undefined ? res.resp_msg : res.resp_msg;
|
||||
|
||||
if (code === 0) {
|
||||
message.success('一键起飞任务已创建,无人机将自动开机并起飞');
|
||||
} else {
|
||||
message.error(msg || '一键起飞任务创建失败');
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error('一键起飞任务创建失败:', error);
|
||||
// 更详细的错误信息
|
||||
let errorMsg = '一键起飞任务创建失败';
|
||||
if (error.response) {
|
||||
const data = error.response.data;
|
||||
errorMsg = data?.resp_msg || data?.msg || error.response.statusText || errorMsg;
|
||||
} else if (error.message) {
|
||||
errorMsg = error.message;
|
||||
} else if (error.msg) {
|
||||
errorMsg = error.msg;
|
||||
} else if (error.resp_msg) {
|
||||
errorMsg = error.resp_msg;
|
||||
}
|
||||
message.error(errorMsg);
|
||||
} finally {
|
||||
setTakeoffLoading(false);
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
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={handleClose}><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}
|
||||
items={[
|
||||
{
|
||||
key: '1',
|
||||
label: <span><DashboardOutlined />综合状态</span>,
|
||||
children: (
|
||||
<div className={styles.detailContainer}>
|
||||
{/* Block A: 机库信息 */}
|
||||
<div className={styles.section}>
|
||||
<div className={styles.sectionHeader}>
|
||||
<span>机库信息 / DOCK INFO</span>
|
||||
<button
|
||||
className={styles.takeoffBtn}
|
||||
disabled={takeoffLoading || dockData?.mode_code === 1 || dockData?.drone_in_dock === 0}
|
||||
onClick={handleTakeoff}
|
||||
>
|
||||
{takeoffLoading ? <LoadingOutlined /> : <RocketOutlined />} 一键起飞
|
||||
</button>
|
||||
</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}>
|
||||
<div className={styles.actionRow}>
|
||||
<button className={styles.primary} onClick={() => onControlClick(selectedDevice, realtimeData)}>
|
||||
<VideoCameraOutlined /> 进入操控台
|
||||
</button>
|
||||
<button className={styles.task} onClick={() => onTaskPanelOpen?.(selectedDevice, dockData, tourism?.id)}>
|
||||
<UnorderedListOutlined /> 任务管理
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: '2',
|
||||
label: <span><ThunderboltOutlined />详细状态</span>,
|
||||
children: (
|
||||
<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>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
</Spin>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default RightPanel;
|
||||
+575
@@ -0,0 +1,575 @@
|
||||
@cyan: #00f0ff;
|
||||
@neon-green: #00ff88;
|
||||
@neon-orange: #ffaa00;
|
||||
@neon-red: #ff4d4f;
|
||||
|
||||
.taskPanel {
|
||||
position: absolute;
|
||||
bottom: 160px;
|
||||
left: 20px;
|
||||
width: 360px;
|
||||
max-height: 500px;
|
||||
background: linear-gradient(
|
||||
135deg,
|
||||
rgba(6, 12, 20, 0.96) 0%,
|
||||
rgba(10, 25, 40, 0.94) 100%
|
||||
);
|
||||
backdrop-filter: blur(12px);
|
||||
border: 1px solid rgba(0, 240, 255, 0.2);
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4), 0 0 20px rgba(0, 240, 255, 0.1);
|
||||
color: #fff;
|
||||
z-index: 1001;
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
transition: all 0.3s ease;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
&.visible {
|
||||
opacity: 1;
|
||||
visibility: visible;
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 12px 14px;
|
||||
background: rgba(0, 20, 40, 0.5);
|
||||
border-bottom: 1px solid rgba(0, 240, 255, 0.15);
|
||||
border-radius: 8px 8px 0 0;
|
||||
cursor: move;
|
||||
user-select: none;
|
||||
flex-shrink: 0;
|
||||
|
||||
.title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: @cyan;
|
||||
|
||||
.deviceTag {
|
||||
font-size: 10px;
|
||||
font-weight: normal;
|
||||
background: rgba(0, 240, 255, 0.15);
|
||||
padding: 2px 6px;
|
||||
border-radius: 3px;
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
}
|
||||
}
|
||||
|
||||
.headerActions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.iconBtn, .closeBtn {
|
||||
background: none;
|
||||
border: none;
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
padding: 5px;
|
||||
border-radius: 4px;
|
||||
transition: all 0.2s;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
color: @cyan;
|
||||
}
|
||||
}
|
||||
|
||||
.closeBtn:hover {
|
||||
background: rgba(255, 77, 79, 0.2);
|
||||
color: @neon-red;
|
||||
}
|
||||
}
|
||||
|
||||
.content {
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.tabs {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
|
||||
:global {
|
||||
.ant-tabs-nav {
|
||||
margin: 0;
|
||||
padding: 0 12px;
|
||||
background: rgba(0, 20, 40, 0.5);
|
||||
|
||||
.ant-tabs-tab {
|
||||
padding: 8px 12px;
|
||||
|
||||
.ant-tabs-tab-btn {
|
||||
color: #ffffff !important;
|
||||
font-size: 14px !important;
|
||||
font-weight: 600 !important;
|
||||
}
|
||||
|
||||
&:hover .ant-tabs-tab-btn {
|
||||
color: #ffdd00 !important;
|
||||
}
|
||||
|
||||
&.ant-tabs-tab-active .ant-tabs-tab-btn {
|
||||
color: #ffdd00 !important;
|
||||
font-weight: 700 !important;
|
||||
}
|
||||
}
|
||||
|
||||
.ant-tabs-ink-bar {
|
||||
background: #ffdd00;
|
||||
height: 3px;
|
||||
}
|
||||
}
|
||||
|
||||
.ant-tabs-content-holder {
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.ant-tabs-content {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.ant-tabs-tabpane {
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.tabContent {
|
||||
padding: 12px;
|
||||
height: 100%;
|
||||
overflow-y: auto;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 4px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-track {
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background: rgba(0, 240, 255, 0.2);
|
||||
border-radius: 2px;
|
||||
|
||||
&:hover {
|
||||
background: rgba(0, 240, 255, 0.3);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.section {
|
||||
margin-bottom: 14px;
|
||||
|
||||
&:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.sectionTitle {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
margin-bottom: 8px;
|
||||
color: #00f0ff;
|
||||
padding-left: 8px;
|
||||
border-left: 2px solid @cyan;
|
||||
}
|
||||
|
||||
.infoGrid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 8px;
|
||||
background: rgba(0, 20, 40, 0.4);
|
||||
border-radius: 6px;
|
||||
padding: 10px;
|
||||
border: 1px solid rgba(0, 240, 255, 0.15);
|
||||
|
||||
.infoItem {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
|
||||
.label {
|
||||
font-size: 10px;
|
||||
color: #88ccff;
|
||||
}
|
||||
|
||||
.value {
|
||||
font-size: 13px;
|
||||
color: #00ffcc;
|
||||
font-family: 'Consolas', monospace;
|
||||
font-weight: 600;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.dockStatus {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 8px 10px;
|
||||
background: rgba(0, 0, 0, 0.2);
|
||||
border-radius: 6px;
|
||||
|
||||
.modeCode {
|
||||
font-size: 11px;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
font-family: 'Consolas', monospace;
|
||||
}
|
||||
}
|
||||
|
||||
.createBtn {
|
||||
background: linear-gradient(135deg, rgba(0, 240, 255, 0.2), rgba(0, 100, 255, 0.2)) !important;
|
||||
border: 1px solid rgba(0, 240, 255, 0.4) !important;
|
||||
color: @cyan !important;
|
||||
font-weight: 600;
|
||||
height: 36px;
|
||||
transition: all 0.3s;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background: linear-gradient(135deg, rgba(0, 240, 255, 0.3), rgba(0, 100, 255, 0.3)) !important;
|
||||
border-color: @cyan !important;
|
||||
box-shadow: 0 0 15px rgba(0, 240, 255, 0.2);
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.5;
|
||||
}
|
||||
}
|
||||
|
||||
.taskList {
|
||||
max-height: 180px;
|
||||
overflow-y: auto;
|
||||
background: rgba(0, 0, 0, 0.2);
|
||||
border-radius: 6px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.05);
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
width: 3px;
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background: rgba(0, 240, 255, 0.2);
|
||||
border-radius: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
.taskItem {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 10px;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
|
||||
|
||||
&:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
background: rgba(0, 240, 255, 0.05);
|
||||
}
|
||||
|
||||
&.selected {
|
||||
background: rgba(0, 240, 255, 0.1);
|
||||
border-left: 3px solid @cyan;
|
||||
}
|
||||
|
||||
.taskInfo {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
|
||||
.taskHeader {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin-bottom: 3px;
|
||||
|
||||
.taskCode {
|
||||
font-size: 11px;
|
||||
color: #00ffcc;
|
||||
font-family: 'Consolas', monospace;
|
||||
font-weight: 600;
|
||||
}
|
||||
}
|
||||
|
||||
.taskName {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: #00f0ff;
|
||||
margin-bottom: 3px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.taskMeta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
font-size: 10px;
|
||||
color: #aaddff;
|
||||
|
||||
.taskTime {
|
||||
font-size: 10px;
|
||||
color: #88ccff;
|
||||
}
|
||||
|
||||
.status {
|
||||
padding: 1px 5px;
|
||||
border-radius: 3px;
|
||||
|
||||
&.status0 {
|
||||
background: rgba(255, 170, 0, 0.2);
|
||||
color: @neon-orange;
|
||||
}
|
||||
&.status1 {
|
||||
background: rgba(0, 240, 255, 0.2);
|
||||
color: @cyan;
|
||||
}
|
||||
&.status2 {
|
||||
background: rgba(0, 255, 136, 0.2);
|
||||
color: @neon-green;
|
||||
}
|
||||
&.status3 {
|
||||
background: rgba(255, 77, 79, 0.2);
|
||||
color: @neon-red;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.taskActions {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
margin-left: 8px;
|
||||
}
|
||||
|
||||
.actionBtn {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
||||
color: rgba(255, 255, 255, 0.6);
|
||||
width: 26px;
|
||||
height: 26px;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: all 0.2s;
|
||||
|
||||
&:hover {
|
||||
background: rgba(0, 240, 255, 0.1);
|
||||
border-color: rgba(0, 240, 255, 0.3);
|
||||
color: @cyan;
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
&.danger:hover {
|
||||
background: rgba(255, 77, 79, 0.1);
|
||||
border-color: rgba(255, 77, 79, 0.3);
|
||||
color: @neon-red;
|
||||
}
|
||||
|
||||
&.execute {
|
||||
background: rgba(0, 255, 136, 0.1);
|
||||
border-color: rgba(0, 255, 136, 0.3);
|
||||
color: @neon-green;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background: rgba(0, 255, 136, 0.2);
|
||||
border-color: @neon-green;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.loading {
|
||||
padding: 20px;
|
||||
text-align: center;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.emptyState {
|
||||
padding: 20px 0;
|
||||
|
||||
:global {
|
||||
.ant-empty-description {
|
||||
color: rgba(255, 255, 255, 0.4);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.ant-empty-image svg {
|
||||
fill: rgba(255, 255, 255, 0.2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.legend {
|
||||
display: flex;
|
||||
gap: 16px;
|
||||
padding: 8px 10px;
|
||||
background: rgba(0, 0, 0, 0.2);
|
||||
border-radius: 6px;
|
||||
|
||||
.legendItem {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 11px;
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
|
||||
.legendLine {
|
||||
width: 20px;
|
||||
height: 3px;
|
||||
border-radius: 2px;
|
||||
|
||||
&.blue {
|
||||
background: #1890ff;
|
||||
box-shadow: 0 0 4px rgba(24, 144, 255, 0.5);
|
||||
}
|
||||
|
||||
&.green {
|
||||
background: #52c41a;
|
||||
box-shadow: 0 0 4px rgba(82, 196, 26, 0.5);
|
||||
}
|
||||
}
|
||||
|
||||
.legendPoint {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: @neon-red;
|
||||
box-shadow: 0 0 4px rgba(255, 77, 79, 0.5);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.realtimeInfo {
|
||||
padding: 10px 12px;
|
||||
background: rgba(0, 0, 0, 0.3);
|
||||
border-top: 1px solid rgba(0, 240, 255, 0.1);
|
||||
flex-shrink: 0;
|
||||
|
||||
.realtimeTitle {
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
margin-bottom: 6px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
|
||||
.locateBtn {
|
||||
margin-left: auto;
|
||||
background: rgba(0, 240, 255, 0.15);
|
||||
border: 1px solid rgba(0, 240, 255, 0.3);
|
||||
color: @cyan;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
transition: all 0.2s;
|
||||
|
||||
&:hover {
|
||||
background: rgba(0, 240, 255, 0.3);
|
||||
border-color: @cyan;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.coordsGrid {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
font-size: 11px;
|
||||
color: @cyan;
|
||||
font-family: 'Consolas', monospace;
|
||||
}
|
||||
}
|
||||
|
||||
// Select 组件样式覆盖
|
||||
:global {
|
||||
.ant-select {
|
||||
.ant-select-selector {
|
||||
background: rgba(0, 0, 0, 0.3) !important;
|
||||
border-color: rgba(0, 240, 255, 0.2) !important;
|
||||
color: #fff !important;
|
||||
height: 34px !important;
|
||||
|
||||
.ant-select-selection-placeholder {
|
||||
color: rgba(255, 255, 255, 0.4);
|
||||
}
|
||||
|
||||
.ant-select-selection-item {
|
||||
color: #fff;
|
||||
}
|
||||
}
|
||||
|
||||
&:hover .ant-select-selector {
|
||||
border-color: @cyan !important;
|
||||
}
|
||||
|
||||
&.ant-select-focused .ant-select-selector {
|
||||
border-color: @cyan !important;
|
||||
box-shadow: 0 0 8px rgba(0, 240, 255, 0.2) !important;
|
||||
}
|
||||
|
||||
.ant-select-arrow {
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
}
|
||||
|
||||
.ant-select-clear {
|
||||
background: transparent;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
|
||||
&:hover {
|
||||
color: @neon-red;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.ant-select-dropdown {
|
||||
background: rgba(10, 20, 40, 0.98) !important;
|
||||
border: 1px solid rgba(0, 240, 255, 0.2);
|
||||
|
||||
.ant-select-item {
|
||||
color: rgba(255, 255, 255, 0.8);
|
||||
|
||||
&:hover {
|
||||
background: rgba(0, 240, 255, 0.1);
|
||||
}
|
||||
|
||||
&.ant-select-item-option-selected {
|
||||
background: rgba(0, 240, 255, 0.2);
|
||||
color: @cyan;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+1163
File diff suppressed because it is too large
Load Diff
+75
@@ -0,0 +1,75 @@
|
||||
.whepPlayer {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: #000;
|
||||
border-radius: 4px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.video {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: contain;
|
||||
background: #000;
|
||||
}
|
||||
|
||||
.overlay {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: rgba(0, 0, 0, 0.85);
|
||||
color: rgba(255, 255, 255, 0.85);
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.icon {
|
||||
font-size: 48px;
|
||||
color: rgba(255, 255, 255, 0.3);
|
||||
}
|
||||
|
||||
.errorIcon {
|
||||
font-size: 48px;
|
||||
color: #ff4d4f;
|
||||
}
|
||||
|
||||
.text {
|
||||
font-size: 14px;
|
||||
color: rgba(255, 255, 255, 0.65);
|
||||
}
|
||||
|
||||
.subText {
|
||||
font-size: 12px;
|
||||
color: rgba(255, 255, 255, 0.45);
|
||||
font-family: monospace;
|
||||
}
|
||||
|
||||
.retryBtn {
|
||||
margin-top: 8px;
|
||||
padding: 6px 16px;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
border-radius: 4px;
|
||||
color: rgba(255, 255, 255, 0.85);
|
||||
cursor: pointer;
|
||||
font-size: 13px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
transition: all 0.2s;
|
||||
|
||||
&:hover {
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
border-color: rgba(255, 255, 255, 0.3);
|
||||
}
|
||||
|
||||
&:active {
|
||||
background: rgba(255, 255, 255, 0.15);
|
||||
}
|
||||
}
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
import React, { useRef, useEffect, useState, useCallback } from 'react';
|
||||
import { Spin } from 'antd';
|
||||
import {
|
||||
LoadingOutlined,
|
||||
ReloadOutlined,
|
||||
VideoCameraOutlined,
|
||||
ExclamationCircleOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import { srsApi } from '@/services/srs';
|
||||
import styles from './WhepPlayer.less';
|
||||
|
||||
interface WhepPlayerProps {
|
||||
/** 视频流完整地址(WHEP URL) */
|
||||
url: string;
|
||||
/** 是否自动播放 */
|
||||
autoPlay?: boolean;
|
||||
/** 是否静音(用于自动播放) */
|
||||
muted?: boolean;
|
||||
/** 只播放视频 */
|
||||
videoOnly?: boolean;
|
||||
/** 只播放音频 */
|
||||
audioOnly?: boolean;
|
||||
/** 样式类名 */
|
||||
className?: string;
|
||||
/** 播放成功回调 */
|
||||
onPlaySuccess?: () => void;
|
||||
/** 播放失败回调 */
|
||||
onPlayError?: (error: string) => void;
|
||||
/** 连接状态变化回调 */
|
||||
onConnectionChange?: (connected: boolean) => void;
|
||||
}
|
||||
|
||||
type PlayerStatus = 'idle' | 'connecting' | 'playing' | 'error';
|
||||
|
||||
const WhepPlayer: React.FC<WhepPlayerProps> = ({
|
||||
url,
|
||||
autoPlay = true,
|
||||
muted = true,
|
||||
videoOnly = false,
|
||||
audioOnly = false,
|
||||
className,
|
||||
onPlaySuccess,
|
||||
onPlayError,
|
||||
onConnectionChange,
|
||||
}) => {
|
||||
const videoRef = useRef<HTMLVideoElement>(null);
|
||||
const pcRef = useRef<RTCPeerConnection | null>(null);
|
||||
const streamRef = useRef<MediaStream | null>(null);
|
||||
|
||||
const [status, setStatus] = useState<PlayerStatus>('idle');
|
||||
const [errorMsg, setErrorMsg] = useState<string>('');
|
||||
const [retryCount, setRetryCount] = useState(0);
|
||||
|
||||
// 清理资源
|
||||
const cleanup = useCallback(() => {
|
||||
if (streamRef.current) {
|
||||
streamRef.current.getTracks().forEach(track => track.stop());
|
||||
streamRef.current = null;
|
||||
}
|
||||
if (pcRef.current) {
|
||||
pcRef.current.close();
|
||||
pcRef.current = null;
|
||||
}
|
||||
if (videoRef.current) {
|
||||
videoRef.current.srcObject = null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 开始播放
|
||||
const startPlay = useCallback(async () => {
|
||||
if (!url) {
|
||||
setStatus('error');
|
||||
setErrorMsg('未配置视频流地址');
|
||||
return;
|
||||
}
|
||||
|
||||
cleanup();
|
||||
setStatus('connecting');
|
||||
setErrorMsg('');
|
||||
|
||||
const result = await srsApi.playWhepByUrl(url, videoRef.current!, {
|
||||
videoOnly,
|
||||
audioOnly,
|
||||
});
|
||||
|
||||
if (result.success && result.pc && result.stream) {
|
||||
pcRef.current = result.pc;
|
||||
streamRef.current = result.stream;
|
||||
setStatus('playing');
|
||||
setRetryCount(0);
|
||||
onPlaySuccess?.();
|
||||
onConnectionChange?.(true);
|
||||
|
||||
// 监听连接状态
|
||||
result.pc.onconnectionstatechange = () => {
|
||||
const state = result.pc?.connectionState;
|
||||
|
||||
if (state === 'disconnected' || state === 'failed' || state === 'closed') {
|
||||
setStatus('error');
|
||||
setErrorMsg('连接已断开');
|
||||
onConnectionChange?.(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 监听 ICE 连接状态(静默)
|
||||
result.pc.oniceconnectionstatechange = () => {};
|
||||
} else {
|
||||
setStatus('error');
|
||||
setErrorMsg(result.error || '连接失败');
|
||||
onPlayError?.(result.error || '连接失败');
|
||||
onConnectionChange?.(false);
|
||||
}
|
||||
}, [url, videoOnly, audioOnly, cleanup, onPlaySuccess, onPlayError, onConnectionChange]);
|
||||
|
||||
// 重试播放
|
||||
const retry = useCallback(() => {
|
||||
setRetryCount(prev => prev + 1);
|
||||
startPlay();
|
||||
}, [startPlay]);
|
||||
|
||||
// 自动播放
|
||||
useEffect(() => {
|
||||
if (autoPlay && url) {
|
||||
startPlay();
|
||||
}
|
||||
|
||||
return () => {
|
||||
cleanup();
|
||||
};
|
||||
}, [url, autoPlay]); // 不要把 startPlay 和 cleanup 加入依赖
|
||||
|
||||
// 渲染状态覆盖层
|
||||
const renderOverlay = () => {
|
||||
switch (status) {
|
||||
case 'connecting':
|
||||
return (
|
||||
<div className={styles.overlay}>
|
||||
<Spin indicator={<LoadingOutlined style={{ fontSize: 32 }} spin />} />
|
||||
<span className={styles.text}>正在连接视频流...</span>
|
||||
</div>
|
||||
);
|
||||
case 'error':
|
||||
return (
|
||||
<div className={styles.overlay}>
|
||||
<ExclamationCircleOutlined className={styles.errorIcon} />
|
||||
<span className={styles.text}>{errorMsg}</span>
|
||||
<button className={styles.retryBtn} onClick={retry}>
|
||||
<ReloadOutlined /> 重试 {retryCount > 0 ? `(${retryCount})` : ''}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
case 'idle':
|
||||
return (
|
||||
<div className={styles.overlay}>
|
||||
<VideoCameraOutlined className={styles.icon} />
|
||||
<span className={styles.text}>等待图传信号...</span>
|
||||
</div>
|
||||
);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={`${styles.whepPlayer} ${className || ''}`}>
|
||||
<video
|
||||
ref={videoRef}
|
||||
autoPlay
|
||||
playsInline
|
||||
muted={muted}
|
||||
controls={false}
|
||||
className={styles.video}
|
||||
/>
|
||||
{status !== 'playing' && renderOverlay()}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default WhepPlayer;
|
||||
@@ -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,227 @@
|
||||
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)',
|
||||
},
|
||||
}}
|
||||
>
|
||||
<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,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,466 @@
|
||||
import { useState, useRef, useEffect, useCallback } from 'react';
|
||||
import { notification } from 'antd';
|
||||
|
||||
// 空闲超时时间:1分钟(测试用,正式环境改为30分钟)
|
||||
const IDLE_TIMEOUT_MS = 30 * 60 * 1000;
|
||||
|
||||
// GPS信息
|
||||
interface GpsData {
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
altitude: number;
|
||||
}
|
||||
|
||||
// 机库数据接口定义 (省略部分详细字段以节省空间,保持原有定义)
|
||||
export interface DockData {
|
||||
// ... (保持原有字段定义不变,此处省略展示)
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
// 无人机遥测数据接口定义
|
||||
export interface DroneData {
|
||||
// 飞行姿态
|
||||
attitude_pitch?: number; // 俯仰角 (度)
|
||||
attitude_roll?: number; // 横滚角 (度)
|
||||
attitude_head?: number; // 偏航角/航向 (度)
|
||||
|
||||
// 速度
|
||||
horizontal_speed?: number; // 水平速度 (m/s)
|
||||
vertical_speed?: number; // 垂直速度 (m/s)
|
||||
ground_speed?: number; // 地面速度 (m/s)
|
||||
|
||||
// 位置
|
||||
latitude?: number; // 纬度
|
||||
longitude?: number; // 经度
|
||||
height?: number; // 高度 (m)
|
||||
elevation?: number; // 海拔高度 (m)
|
||||
home_distance?: number; // 距Home点距离 (m)
|
||||
|
||||
// 电池
|
||||
battery?: {
|
||||
capacity_percent?: number; // 电量百分比
|
||||
voltage?: number; // 电压 (mV)
|
||||
temperature?: number; // 温度 (°C)
|
||||
remain_flight_time?: number; // 剩余飞行时间 (s)
|
||||
};
|
||||
|
||||
// 飞行模式
|
||||
mode_code?: number; // 飞行模式代码
|
||||
gear?: number; // 档位
|
||||
|
||||
// RTK/GPS
|
||||
position_state?: {
|
||||
rtk_number?: number; // RTK 卫星数
|
||||
gps_number?: number; // GPS 卫星数
|
||||
is_fixed?: number; // 是否固定 (1=FIX)
|
||||
};
|
||||
|
||||
// 云台
|
||||
gimbal_pitch?: number; // 云台俯仰角
|
||||
gimbal_roll?: number; // 云台横滚角
|
||||
gimbal_yaw?: number; // 云台偏航角
|
||||
|
||||
// 其他
|
||||
wind_speed?: number; // 风速 (m/s)
|
||||
wind_direction?: number; // 风向 (度)
|
||||
storage?: {
|
||||
total?: number; // 存储总容量
|
||||
used?: number; // 已使用容量
|
||||
};
|
||||
|
||||
[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; // 机库状态数据 (fire_alarm)
|
||||
droneData?: DroneData; // 无人机遥测数据 (msg_alarm)
|
||||
msgAlarmData?: any; // msg_alarm 完整数据
|
||||
[key: string]: any;
|
||||
};
|
||||
}
|
||||
|
||||
interface UseDeviceSSEResult {
|
||||
realtimeData: RealtimeData | null;
|
||||
sseConnected: boolean;
|
||||
isIdleDisconnected: 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 [isIdleDisconnected, setIsIdleDisconnected] = 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 reconnectTimerRef = useRef<NodeJS.Timeout | null>(null);
|
||||
const reconnectAttemptsRef = useRef<number>(0);
|
||||
const maxReconnectAttempts = 10;
|
||||
const shouldReconnectRef = useRef<boolean>(true);
|
||||
const idleTimerRef = useRef<NodeJS.Timeout | null>(null); // 空闲定时器
|
||||
|
||||
// 核心断开逻辑 - 使用 fetch DELETE 请求(正常关闭时调用)
|
||||
const performDisconnect = (deviceSn: string, sessionId: string, token: string | null) => {
|
||||
if (!deviceSn || !token) return;
|
||||
|
||||
const deleteUrl = `/api-device/sse/device-status/${deviceSn}`;
|
||||
|
||||
// 使用 fetch DELETE 请求(带 Authorization header)
|
||||
fetch(deleteUrl, {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`,
|
||||
'X-Client-Session-Id': sessionId,
|
||||
},
|
||||
keepalive: true,
|
||||
}).then(() => {
|
||||
console.log('[DeviceSSE] DELETE 断开请求成功:', deviceSn);
|
||||
}).catch((e) => {
|
||||
console.warn('[DeviceSSE] DELETE 断开请求失败:', e);
|
||||
});
|
||||
};
|
||||
|
||||
// beforeunload 专用断开逻辑(浏览器刷新/关闭时用 sendBeacon)
|
||||
const performBeaconDisconnect = (deviceSn: string, sessionId: string) => {
|
||||
if (!deviceSn) return;
|
||||
|
||||
const beaconUrl = `/api-device/sse/device-status/${deviceSn}/disconnect`;
|
||||
|
||||
if (navigator.sendBeacon) {
|
||||
const blob = new Blob(
|
||||
[JSON.stringify({ sessionId })],
|
||||
{ type: 'application/json' }
|
||||
);
|
||||
navigator.sendBeacon(beaconUrl, blob);
|
||||
console.log('[DeviceSSE] sendBeacon 断开请求已发送:', deviceSn);
|
||||
}
|
||||
};
|
||||
|
||||
// 断开SSE连接
|
||||
const disconnectSSE = useCallback(async (deviceSn?: string) => {
|
||||
const snToDisconnect = deviceSn || currentDeviceSnRef.current;
|
||||
|
||||
// 禁止自动重连
|
||||
shouldReconnectRef.current = false;
|
||||
|
||||
// 清除重连定时器
|
||||
if (reconnectTimerRef.current) {
|
||||
clearTimeout(reconnectTimerRef.current);
|
||||
reconnectTimerRef.current = null;
|
||||
}
|
||||
|
||||
// 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 = '';
|
||||
reconnectAttemptsRef.current = 0;
|
||||
console.log('[DeviceSSE] 连接已断开');
|
||||
}, []);
|
||||
|
||||
// 因空闲断开连接并显示提醒
|
||||
const disconnectDueToIdle = useCallback(() => {
|
||||
console.log('[DeviceSSE] 页面空闲超过1分钟,断开SSE连接');
|
||||
setIsIdleDisconnected(true);
|
||||
// 禁止自动重连
|
||||
shouldReconnectRef.current = false;
|
||||
// 断开连接
|
||||
disconnectSSE();
|
||||
// 显示提醒,使用统一的 key 避免重复
|
||||
notification.warning({
|
||||
message: '页面长时间未操作',
|
||||
description: '已断开实时数据连接,请刷新页面重新连接',
|
||||
duration: 0,
|
||||
key: 'page-idle-warning',
|
||||
});
|
||||
}, [disconnectSSE]);
|
||||
|
||||
// 重置空闲定时器
|
||||
const resetIdleTimer = useCallback(() => {
|
||||
// 如果已经因空闲断开,不再重置定时器
|
||||
if (isIdleDisconnected) return;
|
||||
|
||||
// 清除旧定时器
|
||||
if (idleTimerRef.current) {
|
||||
clearTimeout(idleTimerRef.current);
|
||||
}
|
||||
|
||||
// 只有在有 SSE 连接时才启动空闲定时器
|
||||
if (currentDeviceSnRef.current) {
|
||||
idleTimerRef.current = setTimeout(() => {
|
||||
disconnectDueToIdle();
|
||||
}, IDLE_TIMEOUT_MS);
|
||||
}
|
||||
}, [isIdleDisconnected, disconnectDueToIdle]);
|
||||
|
||||
// 监听用户活动事件,重置空闲定时器
|
||||
useEffect(() => {
|
||||
const activityEvents = ['mousedown', 'mousemove', 'keydown', 'scroll', 'touchstart', 'click'];
|
||||
|
||||
const handleActivity = () => {
|
||||
resetIdleTimer();
|
||||
};
|
||||
|
||||
// 添加事件监听
|
||||
activityEvents.forEach(event => {
|
||||
window.addEventListener(event, handleActivity, { passive: true });
|
||||
});
|
||||
|
||||
// 初始启动定时器
|
||||
resetIdleTimer();
|
||||
|
||||
return () => {
|
||||
// 移除事件监听
|
||||
activityEvents.forEach(event => {
|
||||
window.removeEventListener(event, handleActivity);
|
||||
});
|
||||
|
||||
// 清除定时器
|
||||
if (idleTimerRef.current) {
|
||||
clearTimeout(idleTimerRef.current);
|
||||
idleTimerRef.current = null;
|
||||
}
|
||||
};
|
||||
}, [resetIdleTimer]);
|
||||
|
||||
// 处理SSE事件
|
||||
const handleSSEEvent = useCallback((eventName: string, data: string) => {
|
||||
try {
|
||||
if (eventName === 'connected') {
|
||||
console.log('[DeviceSSE] 连接确认:', data);
|
||||
setSSEConnected(true);
|
||||
} else if (eventName === 'device-data-update') {
|
||||
const parsedData = JSON.parse(data);
|
||||
setRealtimeData(parsedData);
|
||||
} else if (eventName === 'heartbeat') {
|
||||
// 心跳 - 静默处理
|
||||
}
|
||||
} catch (error) {
|
||||
// 静默处理解析错误
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 自动重连调度
|
||||
const scheduleReconnect = useCallback((deviceSn: string) => {
|
||||
if (!shouldReconnectRef.current) {
|
||||
console.log('[DeviceSSE] 已禁用自动重连');
|
||||
return;
|
||||
}
|
||||
|
||||
if (reconnectAttemptsRef.current >= maxReconnectAttempts) {
|
||||
console.error('[DeviceSSE] 重连次数超限,停止重连');
|
||||
return;
|
||||
}
|
||||
|
||||
reconnectAttemptsRef.current++;
|
||||
const delay = Math.min(2000 * Math.pow(1.5, reconnectAttemptsRef.current - 1), 30000);
|
||||
console.log(`[DeviceSSE] ${delay}ms后重连 (${reconnectAttemptsRef.current}/${maxReconnectAttempts})`);
|
||||
|
||||
reconnectTimerRef.current = setTimeout(() => {
|
||||
if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) {
|
||||
console.log('[DeviceSSE] 执行自动重连...');
|
||||
doConnect(deviceSn);
|
||||
}
|
||||
}, delay);
|
||||
}, []);
|
||||
|
||||
// 实际连接逻辑
|
||||
const doConnect = useCallback(async (deviceSn: string) => {
|
||||
if (!deviceSn) return;
|
||||
|
||||
try {
|
||||
const token = sessionStorage.getItem('access_token');
|
||||
const url = `/api-device/sse/device-status/${deviceSn}`;
|
||||
|
||||
const abortController = new AbortController();
|
||||
abortControllerRef.current = abortController;
|
||||
|
||||
console.log('[DeviceSSE] 正在建立连接:', 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}`);
|
||||
}
|
||||
|
||||
// 重连成功,重置计数
|
||||
reconnectAttemptsRef.current = 0;
|
||||
|
||||
const reader = response.body?.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
if (!reader) throw new Error('无法读取响应流');
|
||||
|
||||
let buffer = '';
|
||||
|
||||
// 持续读取SSE流
|
||||
const readStream = async () => {
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
|
||||
if (done) {
|
||||
console.log('[DeviceSSE] 流结束');
|
||||
setSSEConnected(false);
|
||||
// 流结束时尝试重连
|
||||
if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) {
|
||||
scheduleReconnect(deviceSn);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
|
||||
const lines = buffer.split('\n');
|
||||
buffer = lines.pop() || '';
|
||||
|
||||
let currentEvent = 'message';
|
||||
let currentData = '';
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('event:')) {
|
||||
currentEvent = line.substring(6).trim();
|
||||
} else if (line.startsWith('data:')) {
|
||||
currentData = line.substring(5).trim();
|
||||
} else if (line === '') {
|
||||
if (currentData) {
|
||||
handleSSEEvent(currentEvent, currentData);
|
||||
}
|
||||
currentEvent = 'message';
|
||||
currentData = '';
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
if (error?.name === 'AbortError') {
|
||||
console.log('[DeviceSSE] 连接被主动取消');
|
||||
return;
|
||||
}
|
||||
console.error('[DeviceSSE] 读取流错误:', error);
|
||||
setSSEConnected(false);
|
||||
// 错误时尝试重连
|
||||
if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) {
|
||||
scheduleReconnect(deviceSn);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
readStream();
|
||||
|
||||
} catch (error: any) {
|
||||
if (error?.name === 'AbortError') {
|
||||
console.log('[DeviceSSE] 连接被主动取消');
|
||||
return;
|
||||
}
|
||||
console.error('[DeviceSSE] 连接失败:', error);
|
||||
setSSEConnected(false);
|
||||
// 连接失败时尝试重连
|
||||
if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) {
|
||||
scheduleReconnect(deviceSn);
|
||||
}
|
||||
}
|
||||
}, [handleSSEEvent, scheduleReconnect]);
|
||||
|
||||
// 连接SSE(对外暴露的方法)
|
||||
const connectSSE = useCallback(async (deviceSn: string) => {
|
||||
// 如果已经连接了同一个设备,先断开旧的
|
||||
if (currentDeviceSnRef.current && currentDeviceSnRef.current !== deviceSn) {
|
||||
await disconnectSSE(currentDeviceSnRef.current);
|
||||
}
|
||||
|
||||
if (!deviceSn) return;
|
||||
|
||||
// 重置状态
|
||||
currentDeviceSnRef.current = deviceSn;
|
||||
shouldReconnectRef.current = true; // 启用自动重连
|
||||
reconnectAttemptsRef.current = 0;
|
||||
setIsIdleDisconnected(false); // 重置空闲断开状态
|
||||
|
||||
// 执行连接
|
||||
doConnect(deviceSn);
|
||||
|
||||
// 启动空闲定时器
|
||||
resetIdleTimer();
|
||||
}, [disconnectSSE, doConnect, resetIdleTimer]);
|
||||
|
||||
// 监听浏览器刷新/关闭事件 (beforeunload) - 使用 sendBeacon
|
||||
useEffect(() => {
|
||||
const handleBeforeUnload = () => {
|
||||
if (currentDeviceSnRef.current) {
|
||||
// 浏览器刷新/关闭时用 sendBeacon(不需要 token,后端需要配置允许匿名访问)
|
||||
performBeaconDisconnect(currentDeviceSnRef.current, clientSessionIdRef.current);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('beforeunload', handleBeforeUnload);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('beforeunload', handleBeforeUnload);
|
||||
};
|
||||
}, []);
|
||||
|
||||
// 组件卸载清理 (React Unmount)
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
// 清理重连定时器
|
||||
if (reconnectTimerRef.current) {
|
||||
clearTimeout(reconnectTimerRef.current);
|
||||
reconnectTimerRef.current = null;
|
||||
}
|
||||
shouldReconnectRef.current = false;
|
||||
|
||||
// 在组件卸载时,也尝试发送断开请求
|
||||
if (currentDeviceSnRef.current) {
|
||||
const token = sessionStorage.getItem('access_token');
|
||||
performDisconnect(currentDeviceSnRef.current, clientSessionIdRef.current, token);
|
||||
}
|
||||
if (abortControllerRef.current) {
|
||||
abortControllerRef.current.abort();
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
return {
|
||||
realtimeData,
|
||||
sseConnected,
|
||||
isIdleDisconnected,
|
||||
connectSSE,
|
||||
disconnectSSE,
|
||||
};
|
||||
}
|
||||
|
||||
export default useDeviceSSE;
|
||||
@@ -0,0 +1,353 @@
|
||||
import { useState, useRef, useEffect, useCallback } from 'react';
|
||||
import { notification } from 'antd';
|
||||
|
||||
const IDLE_TIMEOUT_MS = 30 * 60 * 1000;
|
||||
|
||||
export interface DroneData {
|
||||
attitude_pitch?: number;
|
||||
attitude_roll?: number;
|
||||
attitude_head?: number;
|
||||
horizontal_speed?: number;
|
||||
vertical_speed?: number;
|
||||
ground_speed?: number;
|
||||
latitude?: number;
|
||||
longitude?: number;
|
||||
height?: number;
|
||||
elevation?: number;
|
||||
home_distance?: number;
|
||||
battery?: {
|
||||
capacity_percent?: number;
|
||||
voltage?: number;
|
||||
temperature?: number;
|
||||
remain_flight_time?: number;
|
||||
remain_job_time?: number;
|
||||
landing_power?: number;
|
||||
return_home_power?: number;
|
||||
batteries?: Array<{
|
||||
capacity_percent?: number;
|
||||
voltage?: number;
|
||||
temperature?: number;
|
||||
sn?: string;
|
||||
index?: number;
|
||||
}>;
|
||||
};
|
||||
mode_code?: number;
|
||||
gear?: number;
|
||||
position_state?: {
|
||||
rtk_number?: number;
|
||||
gps_number?: number;
|
||||
gps_level?: number;
|
||||
};
|
||||
flight_status?: number;
|
||||
is_flying?: number;
|
||||
flight_time?: number;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
export interface UseDroneSSEReturn {
|
||||
droneData: DroneData | null;
|
||||
sseConnected: boolean;
|
||||
loading: boolean;
|
||||
hasData: boolean;
|
||||
isIdleDisconnected: boolean;
|
||||
connectDroneSSE: (deviceSn: string) => Promise<void>;
|
||||
disconnectDroneSSE: (deviceSn?: string) => Promise<void>;
|
||||
resetDroneData: () => void;
|
||||
}
|
||||
|
||||
export const useDroneSSE = (): UseDroneSSEReturn => {
|
||||
const [droneData, setDroneData] = useState<DroneData | null>(null);
|
||||
const [sseConnected, setSSEConnected] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [hasData, setHasData] = useState(false);
|
||||
const [isIdleDisconnected, setIsIdleDisconnected] = useState(false);
|
||||
|
||||
const abortControllerRef = useRef<AbortController | null>(null);
|
||||
const currentDeviceSnRef = useRef<string>('');
|
||||
const clientSessionIdRef = useRef<string>(
|
||||
`drone_client_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`
|
||||
);
|
||||
const dataReceivedRef = useRef<boolean>(false);
|
||||
const reconnectTimerRef = useRef<NodeJS.Timeout | null>(null);
|
||||
const reconnectAttemptsRef = useRef<number>(0);
|
||||
const maxReconnectAttempts = 10;
|
||||
const shouldReconnectRef = useRef<boolean>(true);
|
||||
const idleTimerRef = useRef<NodeJS.Timeout | null>(null);
|
||||
|
||||
const performDisconnect = (deviceSn: string, sessionId: string, token: string | null) => {
|
||||
if (!deviceSn || !token) return;
|
||||
const deleteUrl = `/api-device/sse/drone-telemetry/${deviceSn}`;
|
||||
fetch(deleteUrl, {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`,
|
||||
'X-Client-Session-Id': sessionId,
|
||||
},
|
||||
keepalive: true,
|
||||
}).catch(() => {});
|
||||
};
|
||||
|
||||
const performBeaconDisconnect = (deviceSn: string, sessionId: string) => {
|
||||
if (!deviceSn) return;
|
||||
const beaconUrl = `/api-device/sse/drone-telemetry/${deviceSn}/disconnect`;
|
||||
if (navigator.sendBeacon) {
|
||||
const blob = new Blob([JSON.stringify({ sessionId })], { type: 'application/json' });
|
||||
navigator.sendBeacon(beaconUrl, blob);
|
||||
}
|
||||
};
|
||||
|
||||
const disconnectDroneSSE = useCallback(async (deviceSn?: string) => {
|
||||
const snToDisconnect = deviceSn || currentDeviceSnRef.current;
|
||||
shouldReconnectRef.current = false;
|
||||
|
||||
if (reconnectTimerRef.current) {
|
||||
clearTimeout(reconnectTimerRef.current);
|
||||
reconnectTimerRef.current = null;
|
||||
}
|
||||
|
||||
if (abortControllerRef.current) {
|
||||
abortControllerRef.current.abort();
|
||||
abortControllerRef.current = null;
|
||||
}
|
||||
|
||||
if (snToDisconnect) {
|
||||
const token = sessionStorage.getItem('access_token');
|
||||
performDisconnect(snToDisconnect, clientSessionIdRef.current, token);
|
||||
}
|
||||
|
||||
setSSEConnected(false);
|
||||
setLoading(false);
|
||||
setHasData(false);
|
||||
dataReceivedRef.current = false;
|
||||
currentDeviceSnRef.current = '';
|
||||
reconnectAttemptsRef.current = 0;
|
||||
}, []);
|
||||
|
||||
const disconnectDueToIdle = useCallback(() => {
|
||||
setIsIdleDisconnected(true);
|
||||
shouldReconnectRef.current = false;
|
||||
disconnectDroneSSE();
|
||||
notification.warning({
|
||||
message: '页面长时间未操作',
|
||||
description: '已断开实时数据连接,请刷新页面重新连接',
|
||||
duration: 0,
|
||||
key: 'page-idle-warning',
|
||||
});
|
||||
}, [disconnectDroneSSE]);
|
||||
|
||||
const resetIdleTimer = useCallback(() => {
|
||||
if (isIdleDisconnected) return;
|
||||
if (idleTimerRef.current) {
|
||||
clearTimeout(idleTimerRef.current);
|
||||
}
|
||||
if (currentDeviceSnRef.current) {
|
||||
idleTimerRef.current = setTimeout(() => {
|
||||
disconnectDueToIdle();
|
||||
}, IDLE_TIMEOUT_MS);
|
||||
}
|
||||
}, [isIdleDisconnected, disconnectDueToIdle]);
|
||||
|
||||
useEffect(() => {
|
||||
const activityEvents = ['mousedown', 'mousemove', 'keydown', 'scroll', 'touchstart', 'click'];
|
||||
const handleActivity = () => resetIdleTimer();
|
||||
activityEvents.forEach(event => {
|
||||
window.addEventListener(event, handleActivity, { passive: true });
|
||||
});
|
||||
resetIdleTimer();
|
||||
return () => {
|
||||
activityEvents.forEach(event => {
|
||||
window.removeEventListener(event, handleActivity);
|
||||
});
|
||||
if (idleTimerRef.current) {
|
||||
clearTimeout(idleTimerRef.current);
|
||||
}
|
||||
};
|
||||
}, [resetIdleTimer]);
|
||||
|
||||
const handleSSEEvent = useCallback((eventName: string, data: string) => {
|
||||
try {
|
||||
if (eventName === 'connected') {
|
||||
setSSEConnected(true);
|
||||
setLoading(false);
|
||||
} else if (eventName === 'drone-data-update') {
|
||||
const parsedData = JSON.parse(data) as DroneData;
|
||||
setDroneData(parsedData);
|
||||
if (!dataReceivedRef.current) {
|
||||
dataReceivedRef.current = true;
|
||||
setHasData(true);
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
}, []);
|
||||
|
||||
const scheduleReconnect = useCallback((deviceSn: string) => {
|
||||
if (!shouldReconnectRef.current) return;
|
||||
if (reconnectAttemptsRef.current >= maxReconnectAttempts) return;
|
||||
|
||||
reconnectAttemptsRef.current++;
|
||||
const delay = Math.min(2000 * Math.pow(1.5, reconnectAttemptsRef.current - 1), 30000);
|
||||
|
||||
reconnectTimerRef.current = setTimeout(() => {
|
||||
if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) {
|
||||
doConnect(deviceSn);
|
||||
}
|
||||
}, delay);
|
||||
}, []);
|
||||
|
||||
const doConnect = useCallback(async (deviceSn: string) => {
|
||||
if (!deviceSn) return;
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const token = sessionStorage.getItem('access_token');
|
||||
const url = `/api-device/sse/drone-telemetry/${deviceSn}`;
|
||||
|
||||
const abortController = new AbortController();
|
||||
abortControllerRef.current = abortController;
|
||||
|
||||
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}`);
|
||||
}
|
||||
|
||||
reconnectAttemptsRef.current = 0;
|
||||
|
||||
const reader = response.body?.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
if (!reader) {
|
||||
throw new Error('无法获取SSE流读取器');
|
||||
}
|
||||
|
||||
let buffer = '';
|
||||
|
||||
const readStream = async () => {
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
|
||||
if (done) {
|
||||
setSSEConnected(false);
|
||||
if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) {
|
||||
scheduleReconnect(deviceSn);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
const lines = buffer.split('\n');
|
||||
buffer = lines.pop() || '';
|
||||
|
||||
let eventName = 'message';
|
||||
let data = '';
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('event:')) {
|
||||
eventName = line.substring(6).trim();
|
||||
} else if (line.startsWith('data:')) {
|
||||
data = line.substring(5).trim();
|
||||
} else if (line === '') {
|
||||
if (data) {
|
||||
handleSSEEvent(eventName, data);
|
||||
}
|
||||
eventName = 'message';
|
||||
data = '';
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
if (error?.name === 'AbortError') return;
|
||||
setSSEConnected(false);
|
||||
setLoading(false);
|
||||
if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) {
|
||||
scheduleReconnect(deviceSn);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
readStream();
|
||||
} catch (error: any) {
|
||||
if (error?.name === 'AbortError') return;
|
||||
setSSEConnected(false);
|
||||
setLoading(false);
|
||||
if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) {
|
||||
scheduleReconnect(deviceSn);
|
||||
}
|
||||
}
|
||||
}, [handleSSEEvent, scheduleReconnect]);
|
||||
|
||||
const connectDroneSSE = useCallback(async (deviceSn: string) => {
|
||||
if (currentDeviceSnRef.current && currentDeviceSnRef.current !== deviceSn) {
|
||||
await disconnectDroneSSE(currentDeviceSnRef.current);
|
||||
}
|
||||
|
||||
if (!deviceSn) return;
|
||||
|
||||
setDroneData(null);
|
||||
setHasData(false);
|
||||
dataReceivedRef.current = false;
|
||||
currentDeviceSnRef.current = deviceSn;
|
||||
shouldReconnectRef.current = true;
|
||||
reconnectAttemptsRef.current = 0;
|
||||
setIsIdleDisconnected(false);
|
||||
|
||||
doConnect(deviceSn);
|
||||
resetIdleTimer();
|
||||
}, [disconnectDroneSSE, doConnect, resetIdleTimer]);
|
||||
|
||||
const resetDroneData = useCallback(() => {
|
||||
setDroneData(null);
|
||||
setHasData(false);
|
||||
dataReceivedRef.current = false;
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const handleBeforeUnload = () => {
|
||||
if (currentDeviceSnRef.current) {
|
||||
performBeaconDisconnect(currentDeviceSnRef.current, clientSessionIdRef.current);
|
||||
}
|
||||
};
|
||||
window.addEventListener('beforeunload', handleBeforeUnload);
|
||||
return () => {
|
||||
window.removeEventListener('beforeunload', handleBeforeUnload);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (reconnectTimerRef.current) {
|
||||
clearTimeout(reconnectTimerRef.current);
|
||||
}
|
||||
shouldReconnectRef.current = false;
|
||||
if (currentDeviceSnRef.current) {
|
||||
const token = sessionStorage.getItem('access_token');
|
||||
performDisconnect(currentDeviceSnRef.current, clientSessionIdRef.current, token);
|
||||
}
|
||||
if (abortControllerRef.current) {
|
||||
abortControllerRef.current.abort();
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
return {
|
||||
droneData,
|
||||
sseConnected,
|
||||
loading,
|
||||
hasData,
|
||||
isIdleDisconnected,
|
||||
connectDroneSSE,
|
||||
disconnectDroneSSE,
|
||||
resetDroneData,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,359 @@
|
||||
/**
|
||||
* 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; // 高度偏移(通用)
|
||||
cesiumHeight?: number; // Cesium Ion地形对应的高度偏移
|
||||
arcgisHeight?: number; // ArcGIS地形对应的高度偏移
|
||||
terrainType?: string; // 高度标定时使用的地形服务: cesium_ion/arcgis/ellipsoid
|
||||
};
|
||||
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, currentTerrainType?: string) => 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模型
|
||||
* @param config 模型配置
|
||||
* @param viewer Cesium Viewer实例
|
||||
* @param Cesium Cesium模块
|
||||
* @param currentTerrainType 当前使用的地形类型,用于选择对应的高度偏移
|
||||
*/
|
||||
const loadTileset = useCallback(async (
|
||||
config: TilesetConfig,
|
||||
viewer: any,
|
||||
Cesium: any,
|
||||
currentTerrainType?: string
|
||||
): 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 {
|
||||
// 处理跨域问题:非 localhost 访问时将 CDN URL 转换为代理路径
|
||||
let tilesetUrl = config.url;
|
||||
const isLocalhost = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
|
||||
if (!isLocalhost && tilesetUrl.includes('minicdn.goflytec.com')) {
|
||||
tilesetUrl = tilesetUrl.replace('https://minicdn.goflytec.com', '');
|
||||
console.log('[Tileset] 使用代理路径:', tilesetUrl);
|
||||
}
|
||||
|
||||
// 创建3DTileset - 高清晰度渲染配置
|
||||
const tileset = await Cesium.Cesium3DTileset.fromUrl(tilesetUrl, {
|
||||
// 核心清晰度控制 - 值越小越清晰(大疆司空使用约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;
|
||||
});
|
||||
});
|
||||
|
||||
// 模型位置调整 - 根据当前地形类型选择对应的高度偏移
|
||||
if (config.position) {
|
||||
const { longitude = 0, latitude = 0, cesiumHeight, arcgisHeight } = config.position;
|
||||
|
||||
// 根据当前地形类型选择对应的高度偏移
|
||||
let height = config.position.height || 0; // 默认使用通用高度
|
||||
if (currentTerrainType === 'cesium_ion' && cesiumHeight !== undefined && cesiumHeight !== null) {
|
||||
height = cesiumHeight;
|
||||
console.log(`模型 [${config.name}] 使用 Cesium Ion 高度偏移: ${height}`);
|
||||
} else if (currentTerrainType === 'arcgis' && arcgisHeight !== undefined && arcgisHeight !== null) {
|
||||
height = arcgisHeight;
|
||||
console.log(`模型 [${config.name}] 使用 ArcGIS 高度偏移: ${height}`);
|
||||
} else {
|
||||
console.log(`模型 [${config.name}] 使用通用高度偏移: ${height}`);
|
||||
}
|
||||
|
||||
// 只有当有非零偏移时才应用位置调整
|
||||
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;
|
||||
@@ -0,0 +1,181 @@
|
||||
import React, { useEffect, useRef } from 'react';
|
||||
import { message } from 'antd';
|
||||
|
||||
// 扩展Window类型,添加AMap全局变量
|
||||
declare global {
|
||||
interface Window {
|
||||
AMap: any;
|
||||
}
|
||||
}
|
||||
|
||||
interface AmapContainerProps {
|
||||
tourismList: any[];
|
||||
onTourismClick: (tourism: any) => void;
|
||||
}
|
||||
|
||||
const AmapContainer: React.FC<AmapContainerProps> = (props) => {
|
||||
const { tourismList, onTourismClick } = 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(() => {
|
||||
const initMap = () => {
|
||||
if (!window.AMap) {
|
||||
console.error('window.AMap 未定义');
|
||||
message.error('地图SDK未加载');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!mapRef.current) {
|
||||
console.error('地图容器未找到');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
console.log('开始初始化高德地图...');
|
||||
mapInstanceRef.current = new window.AMap.Map(mapRef.current, {
|
||||
zoom: 5, // 缩放级别5可以看到整个中国
|
||||
center: [104.195397, 35.86166], // 中国地理中心
|
||||
mapStyle: 'amap://styles/normal',
|
||||
viewMode: '2D',
|
||||
features: ['bg', 'road', 'building'],
|
||||
resizeEnable: true,
|
||||
});
|
||||
|
||||
// 标记地图已就绪
|
||||
setMapReady(true);
|
||||
|
||||
console.log('地图初始化成功,开始加载控件插件...');
|
||||
// 添加地图控件 - 使用 AMap.plugin 异步加载
|
||||
window.AMap.plugin(['AMap.Scale', 'AMap.ToolBar'], () => {
|
||||
if (mapInstanceRef.current) {
|
||||
try {
|
||||
const scale = new window.AMap.Scale();
|
||||
const toolBar = new window.AMap.ToolBar();
|
||||
mapInstanceRef.current.addControl(scale);
|
||||
mapInstanceRef.current.addControl(toolBar);
|
||||
console.log('地图控件加载成功');
|
||||
} catch (err: any) {
|
||||
console.error('地图控件加载失败:', err);
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (error: any) {
|
||||
console.error('地图初始化失败:', error);
|
||||
message.error('地图初始化失败: ' + error.message);
|
||||
}
|
||||
};
|
||||
|
||||
// 加载高德地图SDK
|
||||
if (!window.AMap) {
|
||||
const apiKey = process.env.REACT_APP_AMAP_KEY || 'YOUR_AMAP_KEY';
|
||||
console.log('开始加载高德地图SDK, API Key:', apiKey);
|
||||
|
||||
const script = document.createElement('script');
|
||||
script.type = 'text/javascript';
|
||||
script.src = `https://webapi.amap.com/maps?v=1.4.15&key=${apiKey}`;
|
||||
script.async = true;
|
||||
script.crossOrigin = 'anonymous';
|
||||
|
||||
script.onload = () => {
|
||||
console.log('高德地图SDK加载成功');
|
||||
initMap();
|
||||
};
|
||||
|
||||
script.onerror = (error) => {
|
||||
console.error('高德地图SDK加载失败:', error);
|
||||
message.error('地图SDK加载失败,请检查网络连接和API Key');
|
||||
};
|
||||
|
||||
document.head.appendChild(script);
|
||||
} else {
|
||||
console.log('高德地图SDK已存在,直接初始化');
|
||||
initMap();
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (mapInstanceRef.current) {
|
||||
try {
|
||||
mapInstanceRef.current.destroy();
|
||||
} catch (error) {
|
||||
console.error('地图销毁失败:', error);
|
||||
}
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
// 更新景区标记
|
||||
useEffect(() => {
|
||||
if (!mapInstanceRef.current || !tourismList.length) return;
|
||||
|
||||
// 清除旧标记
|
||||
markersRef.current.forEach((marker, key) => {
|
||||
if (key.startsWith('tourism_')) {
|
||||
marker.setMap(null);
|
||||
markersRef.current.delete(key);
|
||||
}
|
||||
});
|
||||
|
||||
// 验证并过滤有效的景区坐标(只显示有经纬度的景区)
|
||||
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;
|
||||
}
|
||||
|
||||
// 添加景区标记
|
||||
validTourisms.forEach((tourism) => {
|
||||
const lng = parseFloat(tourism.longitude);
|
||||
const lat = parseFloat(tourism.latitude);
|
||||
|
||||
// 根据 status 状态设置颜色:1=绿色(启用),0=红色(禁用)
|
||||
const fillColor = tourism.status === 1 ? '#52c41a' : '#ff4d4f';
|
||||
|
||||
const marker = new window.AMap.CircleMarker({
|
||||
center: [lng, lat],
|
||||
radius: 15,
|
||||
fillColor: fillColor,
|
||||
fillOpacity: 0.8,
|
||||
strokeColor: '#fff',
|
||||
strokeWeight: 3,
|
||||
zIndex: 10,
|
||||
cursor: 'pointer',
|
||||
});
|
||||
|
||||
// 添加点击事件
|
||||
marker.on('click', () => onTourismClick(tourism));
|
||||
|
||||
// 添加信息窗体
|
||||
const infoWindow = new window.AMap.InfoWindow({
|
||||
content: `<div style="padding: 8px;">
|
||||
<h4 style="margin: 0 0 8px 0;">${tourism.tourismName || '景区'}</h4>
|
||||
<p style="margin: 0; color: #666;">${tourism.tourismAddress || ''}</p>
|
||||
</div>`,
|
||||
offset: new window.AMap.Pixel(0, -30),
|
||||
});
|
||||
|
||||
marker.on('mouseover', () => {
|
||||
infoWindow.open(mapInstanceRef.current, marker.getCenter());
|
||||
});
|
||||
|
||||
marker.on('mouseout', () => {
|
||||
infoWindow.close();
|
||||
});
|
||||
|
||||
marker.setMap(mapInstanceRef.current);
|
||||
markersRef.current.set(`tourism_${tourism.id}`, marker);
|
||||
});
|
||||
}, [tourismList, onTourismClick, mapReady]);
|
||||
|
||||
return <div ref={mapRef} style={{ width: '100%', height: '100%' }} />;
|
||||
};
|
||||
|
||||
export default AmapContainer;
|
||||
@@ -0,0 +1,968 @@
|
||||
import React, { useEffect, useRef, useState, useCallback, useMemo } 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 TaskPanel from './3d/BottomPanel/TaskPanel';
|
||||
import TilesetPanel from './3d/TilesetPanel';
|
||||
import { useTilesetLoader, TilesetConfig } from './3d/hooks/useTilesetLoader';
|
||||
import { useDroneSSE } from './3d/hooks/useDroneSSE';
|
||||
import { getModelsByTourismId, convertToTilesetConfig } from '@/services/threeDModel';
|
||||
|
||||
// 动态导入Cesium
|
||||
let Cesium: any = null;
|
||||
|
||||
const DEFAULT_GLOBAL_VIEW = {
|
||||
lon: 104.195397,
|
||||
lat: 35.86166,
|
||||
height: 19000000,
|
||||
};
|
||||
|
||||
interface CesiumContainerProps {
|
||||
tourismList: any[];
|
||||
externalSelectedTourism?: any; // 接收外部选择的景区
|
||||
onClearSelection?: () => void; // 清空选择的回调
|
||||
}
|
||||
|
||||
const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
|
||||
const { tourismList, externalSelectedTourism, onClearSelection } = 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);
|
||||
|
||||
// 任务管理面板状态
|
||||
const [taskPanelVisible, setTaskPanelVisible] = useState(false);
|
||||
const [taskPanelDevice, setTaskPanelDevice] = useState<any>(null);
|
||||
const [taskPanelDockData, setTaskPanelDockData] = useState<any>(null);
|
||||
const [taskPanelTourismId, setTaskPanelTourismId] = useState<number | undefined>(undefined);
|
||||
|
||||
// 无人机SSE订阅(用于在3D地球上显示无人机位置)
|
||||
const [droneDeviceSn, setDroneDeviceSn] = useState<string>('');
|
||||
const { droneData, connectDroneSSE, disconnectDroneSSE, resetDroneData } = useDroneSSE();
|
||||
|
||||
// 无人机位置渲染相关引用
|
||||
const droneEntityRef = useRef<any>(null);
|
||||
const flightTrackEntityRef = useRef<any>(null);
|
||||
const trackPositionsRef = useRef<any[]>([]);
|
||||
const hasFlownToDroneRef = useRef<boolean>(false);
|
||||
const lastDroneUpdateTimeRef = useRef<number>(0);
|
||||
const lastDronePositionRef = useRef<{ lon: number; lat: number; height: number } | null>(null);
|
||||
|
||||
// 3D Tiles 模型管理
|
||||
const [tilesetPanelVisible, setTilesetPanelVisible] = useState(false);
|
||||
const [currentTourismModels, setCurrentTourismModels] = useState<TilesetConfig[]>([]); // 当前景区的所有模型配置
|
||||
const [modelLoading, setModelLoading] = useState(false);
|
||||
const [terrainLoading, setTerrainLoading] = useState(false); // 是否正在加载高程地形
|
||||
const terrainLoadedRef = useRef(false); // 是否已加载高程地形
|
||||
const {
|
||||
tilesets,
|
||||
loadTileset,
|
||||
unloadTileset,
|
||||
unloadAllTilesets,
|
||||
flyToTileset,
|
||||
setTilesetVisible,
|
||||
} = useTilesetLoader();
|
||||
|
||||
// 相机飞到景区
|
||||
const flyToTourism = useCallback((tourism: any) => {
|
||||
if (!viewerRef.current || !Cesium) return;
|
||||
// 检查 viewer 是否已销毁
|
||||
if (viewerRef.current.isDestroyed?.()) 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;
|
||||
// 检查 viewer 是否已销毁
|
||||
if (viewerRef.current.isDestroyed?.()) return;
|
||||
|
||||
viewerRef.current.camera.flyTo({
|
||||
destination: Cesium.Cartesian3.fromDegrees(DEFAULT_GLOBAL_VIEW.lon, DEFAULT_GLOBAL_VIEW.lat, DEFAULT_GLOBAL_VIEW.height),
|
||||
orientation: {
|
||||
heading: 0,
|
||||
pitch: Cesium.Math.toRadians(-90),
|
||||
roll: 0,
|
||||
},
|
||||
duration: 1.5,
|
||||
});
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* 动态切换到高程地形
|
||||
* 在进入景区详情、加载3D模型时调用
|
||||
* @param preferredTerrainType 优先使用的地形类型(从模型配置中获取)
|
||||
*/
|
||||
const switchToElevationTerrain = useCallback(async (preferredTerrainType?: string): Promise<string> => {
|
||||
if (!viewerRef.current || !Cesium) {
|
||||
return 'ellipsoid';
|
||||
}
|
||||
|
||||
// 如果已加载且地形类型匹配,跳过
|
||||
if (terrainLoadedRef.current && !preferredTerrainType) {
|
||||
return 'loaded';
|
||||
}
|
||||
|
||||
setTerrainLoading(true);
|
||||
console.log('开始加载高程地形...', preferredTerrainType ? `优先使用: ${preferredTerrainType}` : '');
|
||||
|
||||
let loadedTerrainType = 'ellipsoid';
|
||||
|
||||
// 根据优先地形类型决定加载顺序
|
||||
if (preferredTerrainType === 'arcgis') {
|
||||
// 优先尝试 ArcGIS
|
||||
try {
|
||||
const terrainProvider = await Cesium.ArcGISTiledElevationTerrainProvider.fromUrl(
|
||||
'https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer'
|
||||
);
|
||||
console.log('高程地形加载成功: ArcGIS World Elevation (根据模型配置)');
|
||||
viewerRef.current.terrainProvider = terrainProvider;
|
||||
viewerRef.current.scene.globe.depthTestAgainstTerrain = true;
|
||||
terrainLoadedRef.current = true;
|
||||
loadedTerrainType = 'arcgis';
|
||||
} catch (arcgisError) {
|
||||
console.warn('ArcGIS 加载失败,尝试 Cesium Ion:', arcgisError);
|
||||
try {
|
||||
const terrainProvider = await Cesium.CesiumTerrainProvider.fromIonAssetId(1, {
|
||||
requestVertexNormals: true,
|
||||
requestWaterMask: true,
|
||||
});
|
||||
console.log('高程地形加载成功: Cesium World Terrain (备用)');
|
||||
viewerRef.current.terrainProvider = terrainProvider;
|
||||
viewerRef.current.scene.globe.depthTestAgainstTerrain = true;
|
||||
terrainLoadedRef.current = true;
|
||||
loadedTerrainType = 'cesium_ion';
|
||||
message.warning('ArcGIS地形加载失败,已切换到Cesium Ion,模型高度可能有偏差');
|
||||
} catch (cesiumError) {
|
||||
console.warn('Cesium Ion 也加载失败,保持椭球地形:', cesiumError);
|
||||
loadedTerrainType = 'ellipsoid';
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 默认优先尝试 Cesium Ion
|
||||
try {
|
||||
const terrainProvider = await Cesium.CesiumTerrainProvider.fromIonAssetId(1, {
|
||||
requestVertexNormals: true,
|
||||
requestWaterMask: true,
|
||||
});
|
||||
console.log('高程地形加载成功: Cesium World Terrain');
|
||||
viewerRef.current.terrainProvider = terrainProvider;
|
||||
viewerRef.current.scene.globe.depthTestAgainstTerrain = true;
|
||||
terrainLoadedRef.current = true;
|
||||
loadedTerrainType = 'cesium_ion';
|
||||
} catch (cesiumError) {
|
||||
console.warn('Cesium World Terrain 加载失败,尝试 ArcGIS:', cesiumError);
|
||||
try {
|
||||
const terrainProvider = await Cesium.ArcGISTiledElevationTerrainProvider.fromUrl(
|
||||
'https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer'
|
||||
);
|
||||
console.log('高程地形加载成功: ArcGIS World Elevation');
|
||||
viewerRef.current.terrainProvider = terrainProvider;
|
||||
viewerRef.current.scene.globe.depthTestAgainstTerrain = true;
|
||||
terrainLoadedRef.current = true;
|
||||
loadedTerrainType = 'arcgis';
|
||||
if (preferredTerrainType === 'cesium_ion') {
|
||||
message.warning('Cesium Ion地形加载失败,已切换到ArcGIS,模型高度可能有偏差');
|
||||
}
|
||||
} catch (arcgisError) {
|
||||
console.warn('ArcGIS World Elevation 也加载失败,保持椭球地形:', arcgisError);
|
||||
loadedTerrainType = 'ellipsoid';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setTerrainLoading(false);
|
||||
return loadedTerrainType;
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* 加载景区绑定的模型
|
||||
* 【优化】采用"先飞后加载"策略,用户点击后立即飞行,模型异步加载
|
||||
* 策略:
|
||||
* 1. 相机飞行已在 handleTourismSelect 中执行,此处专注于加载
|
||||
* 2. 高程和模型并行准备,减少等待时间
|
||||
* 3. 模型加载完成后,平滑调整到最佳观察视角
|
||||
*/
|
||||
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);
|
||||
|
||||
// 【优化】并行执行:高程加载和模型配置准备
|
||||
const firstModelTerrainType = configs[0]?.position?.terrainType;
|
||||
console.log('第一个模型的地形类型配置:', firstModelTerrainType);
|
||||
|
||||
// 启动高程加载(不阻塞,让用户先看到地形变化)
|
||||
const terrainPromise = switchToElevationTerrain(firstModelTerrainType);
|
||||
|
||||
// 确定要自动加载的模型数量
|
||||
const autoLoadCount = configs.length <= 2 ? configs.length : 1;
|
||||
const configsToLoad = configs.slice(0, autoLoadCount);
|
||||
|
||||
if (configs.length > autoLoadCount) {
|
||||
message.info(`景区共有 ${configs.length} 个模型,已自动加载第 1 个,其他可通过模型面板加载`);
|
||||
}
|
||||
|
||||
// 等待高程加载完成(通常很快,或者已缓存)
|
||||
const loadedTerrainType = await terrainPromise;
|
||||
console.log('实际加载的地形类型:', loadedTerrainType);
|
||||
|
||||
let loadedCount = 0;
|
||||
let firstTileset: any = null;
|
||||
|
||||
// 加载指定数量的模型,传入实际加载的地形类型
|
||||
for (const config of configsToLoad) {
|
||||
console.log('准备加载模型:', config.name, 'URL:', config.url);
|
||||
if (config.url) {
|
||||
const tileset = await loadTileset(config, viewerRef.current, Cesium, loadedTerrainType);
|
||||
if (tileset) {
|
||||
loadedCount++;
|
||||
if (loadedCount === 1) {
|
||||
firstTileset = tileset;
|
||||
}
|
||||
message.success(`模型 [${config.name}] 加载成功`);
|
||||
}
|
||||
} else {
|
||||
console.warn('模型URL为空,跳过加载:', config.name);
|
||||
}
|
||||
}
|
||||
|
||||
// 【优化】模型加载完成后,平滑调整到最佳观察视角
|
||||
// 使用较短的动画时间,因为相机已经在景区附近了
|
||||
if (firstTileset && viewerRef.current && !viewerRef.current.isDestroyed?.()) {
|
||||
try {
|
||||
viewerRef.current.flyTo(firstTileset, {
|
||||
duration: 1.0, // 缩短动画时间,因为已经在附近
|
||||
offset: new Cesium.HeadingPitchRange(
|
||||
Cesium.Math.toRadians(0),
|
||||
Cesium.Math.toRadians(-45),
|
||||
0
|
||||
),
|
||||
});
|
||||
} catch (e) {
|
||||
console.warn('微调视角失败:', e);
|
||||
}
|
||||
}
|
||||
|
||||
setModelLoading(false);
|
||||
return loadedCount > 0;
|
||||
} else {
|
||||
console.log('该景区没有绑定模型或查询结果为空');
|
||||
setModelLoading(false);
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载景区模型失败:', error);
|
||||
setModelLoading(false);
|
||||
return false;
|
||||
}
|
||||
}, [loadTileset, unloadAllTilesets, switchToElevationTerrain]);
|
||||
|
||||
// 处理景区点击
|
||||
// 优化策略:先飞行后加载,提升用户体验
|
||||
const handleTourismSelect = useCallback((tourism: any) => {
|
||||
setSelectedTourism(tourism);
|
||||
setRightPanelVisible(true);
|
||||
// 切换景区时,关闭左侧操控台
|
||||
setLeftPanelVisible(false);
|
||||
|
||||
// 【优化】立即飞到景区位置,不等待模型加载
|
||||
// 这样用户点击后立刻能看到视角变化,体验更流畅
|
||||
flyToTourism(tourism);
|
||||
|
||||
// 【优化】异步加载模型,不阻塞飞行动画
|
||||
// 模型加载完成后会自动调整到最佳视角
|
||||
if (tourism.id) {
|
||||
loadTourismModels(tourism.id);
|
||||
}
|
||||
}, [flyToTourism, loadTourismModels]);
|
||||
|
||||
// 处理外部选择变化
|
||||
useEffect(() => {
|
||||
if (externalSelectedTourism && !loading) {
|
||||
handleTourismSelect(externalSelectedTourism);
|
||||
}
|
||||
}, [externalSelectedTourism, loading, handleTourismSelect]);
|
||||
|
||||
// 清除无人机图层
|
||||
const clearDroneLayers = useCallback(() => {
|
||||
if (!viewerRef.current || viewerRef.current.isDestroyed?.()) return;
|
||||
|
||||
if (droneEntityRef.current) {
|
||||
try {
|
||||
viewerRef.current.entities.remove(droneEntityRef.current);
|
||||
} catch (e) {}
|
||||
droneEntityRef.current = null;
|
||||
}
|
||||
|
||||
if (flightTrackEntityRef.current) {
|
||||
try {
|
||||
viewerRef.current.entities.remove(flightTrackEntityRef.current);
|
||||
} catch (e) {}
|
||||
flightTrackEntityRef.current = null;
|
||||
}
|
||||
|
||||
trackPositionsRef.current = [];
|
||||
hasFlownToDroneRef.current = false;
|
||||
lastDroneUpdateTimeRef.current = 0;
|
||||
lastDronePositionRef.current = null;
|
||||
}, []);
|
||||
|
||||
// 处理从右侧面板点击"操控" - 打开操控台并订阅无人机SSE
|
||||
const handleOpenControl = useCallback((device: any, realtimeData: any) => {
|
||||
setControlDevice(device);
|
||||
setControlRealtimeData(realtimeData);
|
||||
setLeftPanelVisible(true);
|
||||
|
||||
// 打开操控台时开始订阅无人机SSE(msg_alarm)
|
||||
const deviceSn = device?.deviceSn;
|
||||
if (deviceSn && deviceSn !== droneDeviceSn) {
|
||||
// 断开旧的SSE连接
|
||||
if (droneDeviceSn) {
|
||||
disconnectDroneSSE(droneDeviceSn);
|
||||
}
|
||||
// 清除旧的无人机图层
|
||||
clearDroneLayers();
|
||||
// 开始新的SSE订阅
|
||||
setDroneDeviceSn(deviceSn);
|
||||
connectDroneSSE(deviceSn);
|
||||
}
|
||||
}, [droneDeviceSn, disconnectDroneSSE, connectDroneSSE, clearDroneLayers]);
|
||||
|
||||
// 关闭操控台 - 断开无人机SSE
|
||||
const handleCloseControl = useCallback(() => {
|
||||
setLeftPanelVisible(false);
|
||||
|
||||
// 关闭操控台时断开无人机SSE(取消msg_alarm订阅)
|
||||
if (droneDeviceSn) {
|
||||
disconnectDroneSSE(droneDeviceSn);
|
||||
setDroneDeviceSn('');
|
||||
}
|
||||
resetDroneData();
|
||||
clearDroneLayers();
|
||||
}, [droneDeviceSn, disconnectDroneSSE, resetDroneData, clearDroneLayers]);
|
||||
|
||||
// 处理从右侧面板点击"任务管理"
|
||||
const handleOpenTaskPanel = useCallback((device: any, dockData: any, tourismId?: number) => {
|
||||
setTaskPanelDevice(device);
|
||||
setTaskPanelDockData(dockData);
|
||||
setTaskPanelTourismId(tourismId);
|
||||
setTaskPanelVisible(true);
|
||||
}, []);
|
||||
|
||||
// 计算无人机实时位置
|
||||
const realtimePosition = useMemo(() => {
|
||||
if (!droneData) return null;
|
||||
return {
|
||||
longitude: droneData.longitude,
|
||||
latitude: droneData.latitude,
|
||||
height: droneData.height, // 相对高度(相对于起飞点)
|
||||
elevation: droneData.elevation, // 海拔高度(椭球高度)
|
||||
// 3D地图显示用 height(相对高度),与航线的 height 对应
|
||||
altitude: droneData.height,
|
||||
heading: droneData.attitude_head,
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
}, [droneData]);
|
||||
|
||||
// 飞到无人机位置
|
||||
const flyToDrone = useCallback(() => {
|
||||
if (!viewerRef.current || !Cesium || !realtimePosition) return;
|
||||
if (!realtimePosition.longitude || !realtimePosition.latitude) return;
|
||||
|
||||
const droneHeight = realtimePosition.altitude ?? 50;
|
||||
|
||||
viewerRef.current.camera.flyTo({
|
||||
destination: Cesium.Cartesian3.fromDegrees(
|
||||
realtimePosition.longitude,
|
||||
realtimePosition.latitude,
|
||||
droneHeight + 100 // 视角高度比无人机高100米
|
||||
),
|
||||
orientation: {
|
||||
heading: 0,
|
||||
pitch: Cesium.Math.toRadians(-90), // 垂直俯视
|
||||
roll: 0,
|
||||
},
|
||||
duration: 1.5,
|
||||
});
|
||||
}, [realtimePosition]);
|
||||
|
||||
// 无人机位置渲染(当收到SSE数据时在地图上显示无人机位置)
|
||||
useEffect(() => {
|
||||
if (!viewerRef.current || !Cesium || !realtimePosition) return;
|
||||
if (viewerRef.current.isDestroyed?.()) return;
|
||||
if (!realtimePosition.longitude || !realtimePosition.latitude) return;
|
||||
|
||||
const now = Date.now();
|
||||
const currentPos = {
|
||||
lon: realtimePosition.longitude,
|
||||
lat: realtimePosition.latitude,
|
||||
height: realtimePosition.altitude ?? 0,
|
||||
};
|
||||
|
||||
// 节流:1秒内且位置没变化则跳过
|
||||
const timeSinceLastUpdate = now - lastDroneUpdateTimeRef.current;
|
||||
const lastPos = lastDronePositionRef.current;
|
||||
|
||||
if (lastPos && timeSinceLastUpdate < 1000) {
|
||||
const posChanged =
|
||||
Math.abs(currentPos.lon - lastPos.lon) > 0.00001 ||
|
||||
Math.abs(currentPos.lat - lastPos.lat) > 0.00001 ||
|
||||
Math.abs(currentPos.height - lastPos.height) > 0.5;
|
||||
|
||||
if (!posChanged) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 更新时间和位置记录
|
||||
lastDroneUpdateTimeRef.current = now;
|
||||
lastDronePositionRef.current = currentPos;
|
||||
|
||||
const displayHeight = realtimePosition.height ?? 50;
|
||||
|
||||
try {
|
||||
const pos = Cesium.Cartesian3.fromDegrees(
|
||||
realtimePosition.longitude,
|
||||
realtimePosition.latitude,
|
||||
displayHeight
|
||||
);
|
||||
|
||||
const labelText = `无人机 H:${realtimePosition.height != null ? realtimePosition.height.toFixed(0) : '--'}m`;
|
||||
|
||||
// 更新或创建无人机entity
|
||||
if (droneEntityRef.current) {
|
||||
droneEntityRef.current.position = pos;
|
||||
if (droneEntityRef.current.label) {
|
||||
droneEntityRef.current.label.text = labelText;
|
||||
}
|
||||
} else {
|
||||
droneEntityRef.current = viewerRef.current.entities.add({
|
||||
name: '无人机实时位置',
|
||||
position: pos,
|
||||
point: {
|
||||
pixelSize: 16,
|
||||
color: Cesium.Color.RED,
|
||||
outlineColor: Cesium.Color.WHITE,
|
||||
outlineWidth: 3,
|
||||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||
},
|
||||
label: {
|
||||
text: labelText,
|
||||
font: '14px sans-serif',
|
||||
fillColor: Cesium.Color.WHITE,
|
||||
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
|
||||
outlineWidth: 2,
|
||||
outlineColor: Cesium.Color.BLACK,
|
||||
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
|
||||
pixelOffset: new Cesium.Cartesian2(0, -20),
|
||||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||
},
|
||||
});
|
||||
console.log('[CesiumContainer] 创建无人机entity');
|
||||
}
|
||||
|
||||
// 添加航迹点
|
||||
trackPositionsRef.current.push(pos);
|
||||
|
||||
// 绘制飞行轨迹
|
||||
if (trackPositionsRef.current.length >= 2) {
|
||||
if (flightTrackEntityRef.current) {
|
||||
flightTrackEntityRef.current.polyline.positions = [...trackPositionsRef.current];
|
||||
} else {
|
||||
flightTrackEntityRef.current = viewerRef.current.entities.add({
|
||||
name: '飞行轨迹',
|
||||
polyline: {
|
||||
positions: [...trackPositionsRef.current],
|
||||
width: 4,
|
||||
material: new Cesium.PolylineGlowMaterialProperty({
|
||||
glowPower: 0.3,
|
||||
color: Cesium.Color.LIME,
|
||||
}),
|
||||
clampToGround: false,
|
||||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||
},
|
||||
});
|
||||
console.log('[CesiumContainer] 创建飞行轨迹entity');
|
||||
}
|
||||
}
|
||||
|
||||
// 强制渲染
|
||||
viewerRef.current.scene.requestRender();
|
||||
|
||||
// 首次收到位置数据时,自动飞到无人机位置
|
||||
if (!hasFlownToDroneRef.current && trackPositionsRef.current.length === 1) {
|
||||
hasFlownToDroneRef.current = true;
|
||||
flyToDrone();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[CesiumContainer] 更新无人机位置出错:', error);
|
||||
}
|
||||
}, [realtimePosition, flyToDrone]);
|
||||
|
||||
// 获取设备的视频流地址(从设备数据中获取)
|
||||
const getVideoStreamUrl = useCallback((device: any): string | undefined => {
|
||||
// 从设备配置获取视频流地址
|
||||
return device?.videoStreamUrl || undefined;
|
||||
}, []);
|
||||
|
||||
// 关闭右侧面板
|
||||
const handleRightPanelClose = useCallback(() => {
|
||||
setRightPanelVisible(false);
|
||||
setSelectedTourism(null);
|
||||
setLeftPanelVisible(false); // 同时也关闭左侧
|
||||
|
||||
// 【修复】断开无人机SSE连接并清除图层
|
||||
if (droneDeviceSn) {
|
||||
disconnectDroneSSE(droneDeviceSn);
|
||||
setDroneDeviceSn('');
|
||||
}
|
||||
resetDroneData();
|
||||
clearDroneLayers();
|
||||
|
||||
// 【修复】卸载所有3D模型,避免返回地球时出现渲染问题(黑洞)
|
||||
if (viewerRef.current) {
|
||||
unloadAllTilesets(viewerRef.current);
|
||||
}
|
||||
setCurrentTourismModels([]);
|
||||
setTilesetPanelVisible(false);
|
||||
|
||||
// 【修复】重置地形为椭球地形(快速响应,避免地形问题)
|
||||
if (viewerRef.current && Cesium) {
|
||||
viewerRef.current.terrainProvider = new Cesium.EllipsoidTerrainProvider();
|
||||
viewerRef.current.scene.globe.depthTestAgainstTerrain = false;
|
||||
terrainLoadedRef.current = false;
|
||||
}
|
||||
|
||||
// 【修复】通知父组件清空景区选择框
|
||||
onClearSelection?.();
|
||||
|
||||
flyToGlobal();
|
||||
}, [flyToGlobal, unloadAllTilesets, onClearSelection, droneDeviceSn, disconnectDroneSSE, resetDroneData, clearDroneLayers]);
|
||||
|
||||
// ========== 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 {
|
||||
if (!Cesium) {
|
||||
const cesiumModule = await import('cesium');
|
||||
Cesium = cesiumModule;
|
||||
const cesiumBaseUrl = process.env.CESIUM_BASE_URL || '/';
|
||||
Cesium.buildModuleUrl.setBaseUrl(`${cesiumBaseUrl}cesium/`);
|
||||
|
||||
// 设置 Cesium Ion Access Token(用于加载 Cesium World Terrain)
|
||||
const cesiumToken = process.env.REACT_APP_CESIUM_TOKEN;
|
||||
if (cesiumToken) {
|
||||
Cesium.Ion.defaultAccessToken = cesiumToken;
|
||||
}
|
||||
|
||||
if (!document.querySelector('link[href*="cesium"]')) {
|
||||
const link = document.createElement('link');
|
||||
link.rel = 'stylesheet';
|
||||
link.href = `${cesiumBaseUrl}cesium/Widgets/widgets.css`;
|
||||
document.head.appendChild(link);
|
||||
}
|
||||
}
|
||||
|
||||
if (!containerRef.current) return;
|
||||
|
||||
// 【重要】初始化时使用椭球地形(无高程),快速加载
|
||||
// 原因:
|
||||
// 1. 全球地形加载较慢,影响首屏体验
|
||||
// 2. Cesium World Terrain 精度约30m,与大疆建图的厘米级精度差异大
|
||||
// 会导致模型部分贴合、部分悬浮、部分嵌入地面的问题
|
||||
// 3. 大疆建图的模型本身包含了高精度的地形信息,不需要额外的地形数据
|
||||
// 解决方案:使用椭球地形 + 模型高度偏移微调
|
||||
const terrainProvider = new Cesium.EllipsoidTerrainProvider();
|
||||
console.log('地图仪表盘: 使用椭球地形(快速加载,模型自带高程)');
|
||||
|
||||
viewerRef.current = new Cesium.Viewer(containerRef.current, {
|
||||
terrainProvider: terrainProvider,
|
||||
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.scene.globe.depthTestAgainstTerrain = true;
|
||||
|
||||
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(DEFAULT_GLOBAL_VIEW.lon, DEFAULT_GLOBAL_VIEW.lat, DEFAULT_GLOBAL_VIEW.height),
|
||||
orientation: {
|
||||
heading: 0,
|
||||
pitch: Cesium.Math.toRadians(-90),
|
||||
roll: 0,
|
||||
},
|
||||
});
|
||||
|
||||
// 重写 Home 按钮行为
|
||||
viewerRef.current.homeButton.viewModel.command.beforeExecute.addEventListener((e: any) => {
|
||||
e.cancel = true; // 取消默认行为
|
||||
viewerRef.current.camera.flyTo({
|
||||
destination: Cesium.Cartesian3.fromDegrees(DEFAULT_GLOBAL_VIEW.lon, DEFAULT_GLOBAL_VIEW.lat, DEFAULT_GLOBAL_VIEW.height),
|
||||
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';
|
||||
}
|
||||
|
||||
setLoading(false);
|
||||
message.success('3D地图加载完成');
|
||||
} catch (error) {
|
||||
console.error('Cesium初始化失败:', error);
|
||||
message.error('3D地图加载失败');
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
initCesium();
|
||||
|
||||
return () => {
|
||||
if (viewerRef.current && !viewerRef.current.isDestroyed()) {
|
||||
viewerRef.current.destroy();
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
// 更新景区标记
|
||||
useEffect(() => {
|
||||
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);
|
||||
entitiesRef.current.delete(key);
|
||||
}
|
||||
});
|
||||
|
||||
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;
|
||||
|
||||
validTourisms.forEach((tourism) => {
|
||||
const lon = parseFloat(tourism.longitude);
|
||||
const lat = parseFloat(tourism.latitude);
|
||||
const pointColor = tourism.status === 1 ? '#52c41a' : '#ff4d4f';
|
||||
|
||||
const entity = viewer.entities.add({
|
||||
id: `tourism_${tourism.id}`,
|
||||
position: Cesium.Cartesian3.fromDegrees(lon, lat, 0),
|
||||
point: {
|
||||
pixelSize: 20,
|
||||
color: Cesium.Color.fromCssColorString(pointColor),
|
||||
outlineColor: Cesium.Color.WHITE,
|
||||
outlineWidth: 3,
|
||||
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
|
||||
},
|
||||
label: {
|
||||
text: tourism.tourismName || '景区',
|
||||
font: '14px sans-serif',
|
||||
fillColor: Cesium.Color.WHITE,
|
||||
outlineColor: Cesium.Color.BLACK,
|
||||
outlineWidth: 2,
|
||||
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
|
||||
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
|
||||
pixelOffset: new Cesium.Cartesian2(0, -25),
|
||||
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
|
||||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||
},
|
||||
properties: {
|
||||
tourismData: tourism,
|
||||
},
|
||||
});
|
||||
|
||||
entitiesRef.current.set(`tourism_${tourism.id}`, entity);
|
||||
});
|
||||
}, [tourismList, loading]);
|
||||
|
||||
// 点击事件
|
||||
useEffect(() => {
|
||||
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) {
|
||||
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;
|
||||
}
|
||||
});
|
||||
document.body.style.cursor = 'default';
|
||||
}
|
||||
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
|
||||
|
||||
return () => {
|
||||
handler.destroy();
|
||||
document.body.style.cursor = 'default';
|
||||
};
|
||||
}, [loading, handleTourismSelect]);
|
||||
|
||||
return (
|
||||
<div style={{ width: '100%', height: '100%', position: 'relative' }}>
|
||||
<div ref={containerRef} style={{ width: '100%', height: '100%' }} />
|
||||
|
||||
{loading && (
|
||||
<div
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: '50%',
|
||||
left: '50%',
|
||||
transform: 'translate(-50%, -50%)',
|
||||
color: '#fff',
|
||||
fontSize: 16,
|
||||
background: 'rgba(0,0,0,0.5)',
|
||||
padding: '10px 20px',
|
||||
borderRadius: 4,
|
||||
}}
|
||||
>
|
||||
加载3D地图中...
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 地形/模型加载中提示 - 优化为不阻塞视觉的提示 */}
|
||||
{(terrainLoading || modelLoading) && (
|
||||
<div
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: 60,
|
||||
left: '50%',
|
||||
transform: 'translateX(-50%)',
|
||||
color: '#fff',
|
||||
fontSize: 14,
|
||||
background: 'linear-gradient(135deg, rgba(0,100,150,0.85) 0%, rgba(0,60,100,0.85) 100%)',
|
||||
padding: '10px 20px',
|
||||
borderRadius: 20,
|
||||
zIndex: 800,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 10,
|
||||
boxShadow: '0 4px 15px rgba(0,0,0,0.3)',
|
||||
border: '1px solid rgba(0,240,255,0.3)',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
width: 16,
|
||||
height: 16,
|
||||
border: '2px solid rgba(255,255,255,0.3)',
|
||||
borderTopColor: '#00f0ff',
|
||||
borderRadius: '50%',
|
||||
animation: 'spin 1s linear infinite',
|
||||
}}
|
||||
/>
|
||||
<span>
|
||||
{terrainLoading ? '正在加载高程地形...' : '正在加载3D模型...'}
|
||||
</span>
|
||||
<style>{`
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
`}</style>
|
||||
</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={handleCloseControl}
|
||||
device={controlDevice}
|
||||
realtimeData={controlRealtimeData}
|
||||
videoStreamUrl={getVideoStreamUrl(controlDevice)}
|
||||
droneData={droneData}
|
||||
/>
|
||||
|
||||
{/* 右侧数据面板 */}
|
||||
<RightPanel
|
||||
visible={rightPanelVisible}
|
||||
tourism={selectedTourism}
|
||||
onClose={handleRightPanelClose}
|
||||
onControlClick={handleOpenControl}
|
||||
onTaskPanelOpen={handleOpenTaskPanel}
|
||||
viewer={viewerRef.current}
|
||||
Cesium={Cesium}
|
||||
/>
|
||||
|
||||
{/* 任务管理面板 - 左下角独立渲染 */}
|
||||
<TaskPanel
|
||||
visible={taskPanelVisible}
|
||||
onClose={() => setTaskPanelVisible(false)}
|
||||
device={taskPanelDevice}
|
||||
viewer={viewerRef.current}
|
||||
Cesium={Cesium}
|
||||
droneData={droneData}
|
||||
dockData={taskPanelDockData}
|
||||
tourismId={taskPanelTourismId}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default CesiumContainer;
|
||||
@@ -0,0 +1,5 @@
|
||||
.mapContainer {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
position: relative;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import React from 'react';
|
||||
import AmapContainer from './AmapContainer';
|
||||
import CesiumContainer from './CesiumContainer';
|
||||
import styles from './index.less';
|
||||
|
||||
interface MapContainerProps {
|
||||
mode: '2d' | '3d';
|
||||
tourismList: any[];
|
||||
onTourismClick: (tourism: any) => void;
|
||||
selectedTourism?: any;
|
||||
onClearSelection?: () => void; // 清空选择的回调
|
||||
}
|
||||
|
||||
const MapContainer: React.FC<MapContainerProps> = (props) => {
|
||||
const { mode, tourismList, onTourismClick, selectedTourism, onClearSelection } = props;
|
||||
|
||||
return (
|
||||
<div className={styles.mapContainer}>
|
||||
{/* 2D地图 - 高德 */}
|
||||
{mode === '2d' && (
|
||||
<AmapContainer tourismList={tourismList} onTourismClick={onTourismClick} />
|
||||
)}
|
||||
|
||||
{/* 3D地图 - Cesium(内部处理点击,显示底部面板) */}
|
||||
{mode === '3d' && (
|
||||
<CesiumContainer
|
||||
tourismList={tourismList}
|
||||
externalSelectedTourism={selectedTourism}
|
||||
onClearSelection={onClearSelection}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default MapContainer;
|
||||
@@ -0,0 +1,203 @@
|
||||
.mapDashboard {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
background: #000;
|
||||
|
||||
.mapWrapper {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.headerLeft {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.backIconBtn {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 50%;
|
||||
background: linear-gradient(135deg, rgba(0, 240, 255, 0.18), rgba(0, 120, 255, 0.06));
|
||||
border: 1px solid rgba(0, 240, 255, 0.34);
|
||||
color: #eaffff;
|
||||
box-shadow: 0 0 16px rgba(0, 240, 255, 0.10);
|
||||
|
||||
&:hover {
|
||||
background: linear-gradient(135deg, rgba(0, 240, 255, 0.26), rgba(0, 120, 255, 0.12));
|
||||
border-color: rgba(0, 240, 255, 0.60);
|
||||
color: #00f0ff;
|
||||
box-shadow: 0 0 20px rgba(0, 240, 255, 0.16);
|
||||
}
|
||||
|
||||
:global(.ant-btn-icon) {
|
||||
font-size: 16px;
|
||||
}
|
||||
}
|
||||
|
||||
.headerCenter {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.headerTitle {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 12px;
|
||||
padding: 8px 22px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid rgba(0, 240, 255, 0.22);
|
||||
background: rgba(10, 20, 30, 0.35);
|
||||
box-shadow: 0 0 22px rgba(0, 240, 255, 0.10);
|
||||
}
|
||||
|
||||
.headerTitleText {
|
||||
font-size: 22px;
|
||||
font-weight: 800;
|
||||
letter-spacing: 6px;
|
||||
color: #fff;
|
||||
text-shadow: 0 0 18px rgba(0, 240, 255, 0.22);
|
||||
background-image: linear-gradient(180deg, #ffffff 0%, #aeeeff 100%);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
background-clip: text;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.headerTitleDeco {
|
||||
position: absolute;
|
||||
bottom: 6px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
width: 220px;
|
||||
height: 2px;
|
||||
background: linear-gradient(90deg, transparent, rgba(0, 240, 255, 0.85), transparent);
|
||||
opacity: 0.75;
|
||||
filter: drop-shadow(0 0 8px rgba(0, 240, 255, 0.25));
|
||||
}
|
||||
|
||||
.statsBadge {
|
||||
:global {
|
||||
.ant-badge-status-text {
|
||||
color: #00ff88 !important;
|
||||
font-weight: 600;
|
||||
text-shadow: 0 0 5px rgba(0, 0, 0, 0.8);
|
||||
background: rgba(0, 0, 0, 0.25);
|
||||
padding: 2px 10px;
|
||||
border-radius: 999px;
|
||||
border: 1px solid rgba(0, 255, 136, 0.18);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.tourismSelect {
|
||||
width: 320px;
|
||||
|
||||
:global {
|
||||
.ant-select-selector {
|
||||
background-color: rgba(0, 240, 255, 0.05) !important;
|
||||
border: 1px solid rgba(0, 240, 255, 0.28) !important;
|
||||
color: #fff;
|
||||
height: 34px;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 0 8px rgba(0, 240, 255, 0.12);
|
||||
|
||||
&:hover {
|
||||
border-color: #00f0ff !important;
|
||||
box-shadow: 0 0 14px rgba(0, 240, 255, 0.22);
|
||||
}
|
||||
}
|
||||
|
||||
.ant-select-selection-item {
|
||||
color: #fff;
|
||||
font-weight: 500;
|
||||
line-height: 32px;
|
||||
}
|
||||
|
||||
.ant-select-selection-placeholder {
|
||||
color: rgba(255, 255, 255, 0.42);
|
||||
}
|
||||
|
||||
.ant-select-arrow {
|
||||
color: #00f0ff;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.headerRight {
|
||||
:global {
|
||||
.ant-btn {
|
||||
background: rgba(255, 255, 255, 0.05);
|
||||
border-color: rgba(255, 255, 255, 0.1);
|
||||
color: #fff;
|
||||
border-radius: 10px;
|
||||
|
||||
&:hover {
|
||||
border-color: #00f0ff;
|
||||
color: #00f0ff;
|
||||
background: rgba(0, 240, 255, 0.1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 1200px) {
|
||||
.tourismSelect {
|
||||
width: 260px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.statsBadge {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.headerTitleText {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.tourismSelect {
|
||||
width: 180px;
|
||||
}
|
||||
|
||||
.headerTitle {
|
||||
padding: 8px 12px;
|
||||
}
|
||||
|
||||
.headerTitleDeco {
|
||||
width: 120px;
|
||||
}
|
||||
}
|
||||
|
||||
// 下拉弹窗样式
|
||||
.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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { Button, Space, Badge, message, Select, Tooltip } from 'antd';
|
||||
import {
|
||||
ArrowLeftOutlined,
|
||||
ReloadOutlined,
|
||||
FullscreenOutlined,
|
||||
FullscreenExitOutlined,
|
||||
GlobalOutlined,
|
||||
EnvironmentOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import { history } from 'umi';
|
||||
import MapContainer from './components/MapContainer';
|
||||
import { ordersApi } from '@/services/orders';
|
||||
import { tenantApi } from '@/services/tenant';
|
||||
import styles from './index.less';
|
||||
|
||||
const { Option } = Select;
|
||||
|
||||
const Map3D: React.FC = () => {
|
||||
const [tourismList, setTourismList] = useState<any[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [isFullscreen, setIsFullscreen] = useState(false);
|
||||
const [params, setParams] = useState<{ tenantId?: string; includeChildren?: boolean }>({});
|
||||
const [portalReady, setPortalReady] = useState(false);
|
||||
|
||||
// 用于 3D 模式下的外部选择控制
|
||||
const [selectedTourism, setSelectedTourism] = useState<any>(null);
|
||||
|
||||
// 首次进入时,默认按"当前租户 + 包含下级租户"查询
|
||||
useEffect(() => {
|
||||
setPortalReady(true);
|
||||
(async () => {
|
||||
try {
|
||||
let tenantId: string | undefined;
|
||||
const cur: any = await tenantApi.getCurrentTenant();
|
||||
tenantId = cur?.data?.tenantId ?? cur?.tenantId;
|
||||
if (!tenantId) {
|
||||
const stats: any = await tenantApi.getScopeStats();
|
||||
tenantId = stats?.data?.currentTenantId ?? stats?.currentTenantId;
|
||||
}
|
||||
if (tenantId) {
|
||||
setParams({ tenantId, includeChildren: true });
|
||||
}
|
||||
} catch {
|
||||
// 忽略错误
|
||||
}
|
||||
})();
|
||||
|
||||
// 监听租户变化事件
|
||||
const handleTenantChange = (e: CustomEvent) => {
|
||||
const { tenantId, includeChildren } = e.detail || {};
|
||||
if (tenantId) {
|
||||
setParams({ tenantId, includeChildren: includeChildren ?? true });
|
||||
}
|
||||
};
|
||||
window.addEventListener('tenant-change', handleTenantChange as EventListener);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('tenant-change', handleTenantChange as EventListener);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const onFullscreenChange = () => {
|
||||
setIsFullscreen(!!document.fullscreenElement);
|
||||
};
|
||||
document.addEventListener('fullscreenchange', onFullscreenChange);
|
||||
return () => document.removeEventListener('fullscreenchange', onFullscreenChange);
|
||||
}, []);
|
||||
|
||||
// 获取景区列表
|
||||
const fetchTourismList = async () => {
|
||||
if (!params.tenantId) {
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const response = await ordersApi.tourism({
|
||||
current: 1,
|
||||
pageSize: 1000,
|
||||
...params,
|
||||
});
|
||||
setTourismList(response.data || []);
|
||||
} catch (error) {
|
||||
message.error('获取景区列表失败');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 景区点击事件 - 3D模式下不跳转,直接在地图上展示
|
||||
const handleTourismClick = (tourism: any) => {
|
||||
setSelectedTourism(tourism);
|
||||
};
|
||||
|
||||
// 下拉框选择事件
|
||||
const handleDropdownSelect = (tourismId: number) => {
|
||||
const tourism = tourismList.find(t => t.id === tourismId);
|
||||
if (!tourism) return;
|
||||
setSelectedTourism(tourism);
|
||||
};
|
||||
|
||||
// 清空景区选择
|
||||
const handleClearSelection = () => {
|
||||
setSelectedTourism(null);
|
||||
};
|
||||
|
||||
// 返回大屏
|
||||
const goBack = () => {
|
||||
history.push('/dashboard');
|
||||
};
|
||||
|
||||
// 全屏切换
|
||||
const toggleFullscreen = () => {
|
||||
if (!document.fullscreenElement) {
|
||||
document.documentElement.requestFullscreen();
|
||||
setIsFullscreen(true);
|
||||
} else {
|
||||
document.exitFullscreen();
|
||||
setIsFullscreen(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 租户ID获取后,加载景区列表
|
||||
useEffect(() => {
|
||||
if (params.tenantId) {
|
||||
fetchTourismList();
|
||||
}
|
||||
}, [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;
|
||||
});
|
||||
|
||||
const leftSlot = portalReady ? document.getElementById('map3d-header-left') : null;
|
||||
const centerSlot = portalReady ? document.getElementById('map3d-header-center') : null;
|
||||
const rightSlot = portalReady ? document.getElementById('map3d-header-right') : null;
|
||||
|
||||
const headerLeft = (
|
||||
<div className={styles.headerLeft}>
|
||||
<Tooltip title="返回监控大屏" placement="bottom">
|
||||
<Button
|
||||
aria-label="返回监控大屏"
|
||||
shape="circle"
|
||||
icon={<ArrowLeftOutlined />}
|
||||
onClick={goBack}
|
||||
className={styles.backIconBtn}
|
||||
/>
|
||||
</Tooltip>
|
||||
|
||||
<Select
|
||||
showSearch
|
||||
placeholder="请选择景区进入..."
|
||||
optionFilterProp="children"
|
||||
value={selectedTourism?.id}
|
||||
onChange={handleDropdownSelect}
|
||||
allowClear
|
||||
onClear={handleClearSelection}
|
||||
filterOption={(input, option) =>
|
||||
(option?.children as unknown as string).toLowerCase().indexOf(input.toLowerCase()) >= 0
|
||||
}
|
||||
className={styles.tourismSelect}
|
||||
suffixIcon={<EnvironmentOutlined style={{ color: '#00f0ff' }} />}
|
||||
classNames={{ popup: { root: styles.tourismSelectPopup } }}
|
||||
>
|
||||
{validTourismList.map(t => (
|
||||
<Option key={t.id} value={t.id}>{t.tourismName}</Option>
|
||||
))}
|
||||
</Select>
|
||||
|
||||
<Badge status="success" text={`共${tourismList.length}个景区`} className={styles.statsBadge} />
|
||||
</div>
|
||||
);
|
||||
|
||||
const headerCenter = (
|
||||
<div className={styles.headerCenter}>
|
||||
<div className={styles.headerTitle}>
|
||||
<GlobalOutlined />
|
||||
<span className={styles.headerTitleText}>3D地图监控中心</span>
|
||||
<span className={styles.headerTitleDeco} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
const headerRight = (
|
||||
<Space size={10} className={styles.headerRight}>
|
||||
<Button icon={<ReloadOutlined />} onClick={fetchTourismList} loading={loading}>
|
||||
刷新
|
||||
</Button>
|
||||
<Button icon={isFullscreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />} onClick={toggleFullscreen}>
|
||||
{isFullscreen ? '退出全屏' : '全屏'}
|
||||
</Button>
|
||||
</Space>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={styles.mapDashboard}>
|
||||
{leftSlot && createPortal(headerLeft, leftSlot)}
|
||||
{centerSlot && createPortal(headerCenter, centerSlot)}
|
||||
{rightSlot && createPortal(headerRight, rightSlot)}
|
||||
|
||||
{/* 全屏地图 */}
|
||||
<div className={styles.mapWrapper}>
|
||||
<MapContainer
|
||||
mode="3d"
|
||||
tourismList={tourismList}
|
||||
onTourismClick={handleTourismClick}
|
||||
selectedTourism={selectedTourism}
|
||||
onClearSelection={handleClearSelection}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Map3D;
|
||||
@@ -0,0 +1,122 @@
|
||||
.login-page {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 24px;
|
||||
background:
|
||||
linear-gradient(135deg, rgba(0, 20, 50, 0.95) 0%, rgba(0, 40, 80, 0.9) 50%, rgba(0, 60, 100, 0.85) 100%);
|
||||
}
|
||||
|
||||
.login-wrap {
|
||||
width: 100%;
|
||||
max-width: 1000px;
|
||||
display: flex;
|
||||
gap: 24px;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.login-hero {
|
||||
flex: 1;
|
||||
min-height: 420px;
|
||||
color: #fff;
|
||||
border-radius: 14px;
|
||||
padding: 32px;
|
||||
background: rgba(0, 212, 255, 0.08);
|
||||
backdrop-filter: blur(10px);
|
||||
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
|
||||
border: 1px solid rgba(0, 212, 255, 0.2);
|
||||
}
|
||||
|
||||
.login-hero h1 {
|
||||
margin: 0 0 8px;
|
||||
font-weight: 700;
|
||||
font-size: 28px;
|
||||
color: #00d4ff;
|
||||
}
|
||||
|
||||
.login-hero p {
|
||||
opacity: 0.9;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.login-hero ul {
|
||||
margin: 24px 0 0;
|
||||
padding-left: 20px;
|
||||
li {
|
||||
margin-bottom: 12px;
|
||||
color: rgba(255, 255, 255, 0.85);
|
||||
&::marker {
|
||||
color: #00d4ff;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.login-form-card {
|
||||
width: 420px;
|
||||
max-width: 100%;
|
||||
background: rgba(19, 26, 61, 0.95);
|
||||
border-radius: 14px;
|
||||
padding: 24px;
|
||||
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.4);
|
||||
border: 1px solid rgba(0, 212, 255, 0.15);
|
||||
}
|
||||
|
||||
.login-form :global(.ant-pro-form-login-logo) img {
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.login-form :global(.ant-pro-form-login-title) {
|
||||
color: #00d4ff !important;
|
||||
}
|
||||
|
||||
.login-form :global(.ant-pro-form-login-desc) {
|
||||
color: rgba(255, 255, 255, 0.7) !important;
|
||||
}
|
||||
|
||||
.login-form :global(.ant-input-affix-wrapper),
|
||||
.login-form :global(.ant-input) {
|
||||
background: rgba(0, 0, 0, 0.3) !important;
|
||||
border-color: rgba(0, 212, 255, 0.3) !important;
|
||||
color: #fff !important;
|
||||
&:hover, &:focus {
|
||||
border-color: #00d4ff !important;
|
||||
}
|
||||
}
|
||||
|
||||
.login-form :global(.ant-input::placeholder) {
|
||||
color: rgba(255, 255, 255, 0.4) !important;
|
||||
}
|
||||
|
||||
.login-form :global(.ant-btn-primary) {
|
||||
background: linear-gradient(135deg, #00d4ff 0%, #0099cc 100%) !important;
|
||||
border: none !important;
|
||||
&:hover {
|
||||
background: linear-gradient(135deg, #00e5ff 0%, #00aadd 100%) !important;
|
||||
}
|
||||
}
|
||||
|
||||
.login-form-extra {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 8px;
|
||||
:global(.ant-checkbox-wrapper) {
|
||||
color: rgba(255, 255, 255, 0.7);
|
||||
}
|
||||
}
|
||||
|
||||
.login-footer {
|
||||
margin-top: 16px;
|
||||
color: rgba(255, 255, 255, 0.5);
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.login-wrap {
|
||||
max-width: 420px;
|
||||
}
|
||||
.login-hero { display: none; }
|
||||
.login-page { padding: 16px; }
|
||||
.login-form-card { padding: 20px; }
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import logo from '@/assets/logo.png';
|
||||
import React, { useEffect, useRef, useState } from 'react';
|
||||
import { LoginForm, ProFormText, ProFormCaptcha, ProFormCheckbox } from '@ant-design/pro-components';
|
||||
import { AppstoreOutlined, LockOutlined, UserOutlined } from '@ant-design/icons';
|
||||
import { Form, message, Spin } from 'antd';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { history } from 'umi';
|
||||
import { login, LoginParams } from '@/services/login';
|
||||
import './index.less';
|
||||
|
||||
const LoginPage: React.FC = () => {
|
||||
const [uuid, setUuid] = useState<string>(uuidv4());
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [form] = Form.useForm();
|
||||
const mountedRef = useRef(true);
|
||||
|
||||
useEffect(() => () => { mountedRef.current = false; }, []);
|
||||
|
||||
useEffect(() => {
|
||||
const clientId = localStorage.getItem('tenant_client_id');
|
||||
if (clientId) form.setFieldsValue({ clientId });
|
||||
}, []);
|
||||
|
||||
const handleSubmit = async (values: LoginParams) => {
|
||||
if (loading) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await login({ ...values, clientId: 'webApp', deviceId: uuid });
|
||||
const accessToken = res?.access_token || res?.data?.access_token || res?.accessToken;
|
||||
|
||||
if (accessToken) {
|
||||
sessionStorage.setItem('access_token', accessToken);
|
||||
try {
|
||||
const { ensureTenantCacheTokenGuard, setTenantTreeCache } = await import('@/utils/tenantCache');
|
||||
const { tenantApi } = await import('@/services/tenant');
|
||||
ensureTenantCacheTokenGuard();
|
||||
|
||||
const currentTenantRes: any = await tenantApi.getCurrentTenant();
|
||||
const currentTenantId = currentTenantRes?.data?.tenantId || currentTenantRes?.tenantId;
|
||||
if (currentTenantId) {
|
||||
localStorage.setItem('current_tenant_id', currentTenantId);
|
||||
}
|
||||
|
||||
const treeRes: any = await tenantApi.getAccessibleTenants();
|
||||
let list: any[] = [];
|
||||
if (typeof treeRes?.success !== 'undefined') list = treeRes.success ? (treeRes.data || []) : [];
|
||||
else if (Array.isArray(treeRes)) list = treeRes as any[];
|
||||
if (list && list.length) setTenantTreeCache(list);
|
||||
} catch {}
|
||||
message.success('登录成功,正在跳转...');
|
||||
|
||||
setTimeout(() => {
|
||||
const { query } = history.location as any;
|
||||
const { redirect } = query || {};
|
||||
// 跳转到大屏首页
|
||||
const targetPath = redirect || '/dashboard';
|
||||
history.push(targetPath);
|
||||
}, 1000);
|
||||
} else {
|
||||
const errorMsg = (res as any)?.resp_msg || (res as any)?.msg || '登录失败';
|
||||
message.error(errorMsg);
|
||||
setUuid(uuidv4());
|
||||
}
|
||||
} catch (e) {
|
||||
const errorMsg = (e as any)?.message || '登录失败,请重试';
|
||||
message.error(errorMsg);
|
||||
} finally {
|
||||
if (mountedRef.current) setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="login-page">
|
||||
<div className="login-wrap">
|
||||
<div className="login-hero">
|
||||
<h1>鹰眼管控平台</h1>
|
||||
<p>3D可视化设备管控与任务监控系统</p>
|
||||
<ul>
|
||||
<li>实时设备状态监控</li>
|
||||
<li>无人机任务管理</li>
|
||||
<li>3D地图可视化展示</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div className="login-form-card">
|
||||
<Spin spinning={loading}>
|
||||
<LoginForm
|
||||
className="login-form"
|
||||
logo={<img alt="logo" src={logo} />}
|
||||
title="鹰眼管控"
|
||||
subTitle="请输入账号后继续"
|
||||
initialValues={{ autoLogin: true }}
|
||||
form={form}
|
||||
onFinish={handleSubmit as any}
|
||||
submitter={{ searchConfig: { submitText: '登录' } }}
|
||||
>
|
||||
<ProFormText
|
||||
name="clientId"
|
||||
initialValue="webApp"
|
||||
disabled
|
||||
fieldProps={{ size: 'large', prefix: <AppstoreOutlined /> }}
|
||||
placeholder="请输入租户标识"
|
||||
rules={[{ required: true, message: '请输入租户标识' }]}
|
||||
/>
|
||||
<ProFormText
|
||||
name="username"
|
||||
fieldProps={{ size: 'large', prefix: <UserOutlined /> }}
|
||||
placeholder="请输入用户名"
|
||||
rules={[{ required: true, message: '请输入用户名' }]}
|
||||
/>
|
||||
<ProFormText.Password
|
||||
name="password"
|
||||
fieldProps={{ size: 'large', prefix: <LockOutlined /> }}
|
||||
placeholder="请输入密码"
|
||||
rules={[{ required: true, message: '请输入密码' }]}
|
||||
/>
|
||||
<ProFormCaptcha
|
||||
name="validCode"
|
||||
fieldProps={{ size: 'large', prefix: <LockOutlined /> }}
|
||||
captchaProps={{ size: 'large' }}
|
||||
placeholder="请输入验证码"
|
||||
captchaTextRender={() => (
|
||||
<img
|
||||
src={`/api-uaa/validata/code/${uuid}`}
|
||||
alt="验证码"
|
||||
style={{ height: 32, cursor: 'pointer' }}
|
||||
onClick={() => setUuid(uuidv4())}
|
||||
/>
|
||||
)}
|
||||
onGetCaptcha={async () => Promise.resolve()}
|
||||
rules={[{ required: true, message: '请输入验证码' }]}
|
||||
/>
|
||||
<div className="login-form-extra">
|
||||
<ProFormCheckbox noStyle name="autoLogin">自动登录</ProFormCheckbox>
|
||||
</div>
|
||||
</LoginForm>
|
||||
</Spin>
|
||||
</div>
|
||||
</div>
|
||||
<div className="login-footer">© {new Date().getFullYear()} 鹰眼管控平台</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default LoginPage;
|
||||
@@ -0,0 +1,227 @@
|
||||
import { request } from 'umi';
|
||||
import { deviceApi } from './device';
|
||||
import { listMission, MissionStatus } from './mission';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
/**
|
||||
* 大屏统计服务
|
||||
* 聚合设备和任务统计数据
|
||||
*/
|
||||
|
||||
export interface DeviceStats {
|
||||
total: number;
|
||||
online: number;
|
||||
offline: number;
|
||||
fault: number;
|
||||
onlineRate: number;
|
||||
byType: { type: string; name: string; count: number }[];
|
||||
}
|
||||
|
||||
export interface TaskStats {
|
||||
total: number;
|
||||
pending: number;
|
||||
running: number;
|
||||
completed: number;
|
||||
failed: number;
|
||||
todayNew: number;
|
||||
successRate: number;
|
||||
}
|
||||
|
||||
export interface TrendItem {
|
||||
date: string;
|
||||
created?: number;
|
||||
completed?: number;
|
||||
failed?: number;
|
||||
online?: number;
|
||||
total?: number;
|
||||
}
|
||||
|
||||
export interface AlertItem {
|
||||
id: string;
|
||||
type: 'device_offline' | 'task_failed' | 'low_battery' | 'device_fault';
|
||||
deviceSn?: string;
|
||||
deviceName?: string;
|
||||
taskId?: number;
|
||||
taskName?: string;
|
||||
message: string;
|
||||
level: 'warning' | 'error' | 'critical';
|
||||
timestamp: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取设备统计
|
||||
*/
|
||||
export async function getDeviceStats(params?: { tenantId?: string; includeChildren?: boolean }): Promise<DeviceStats> {
|
||||
try {
|
||||
const res = await deviceApi.deviceList({ page: 1, limit: 1000, ...params });
|
||||
const devices = res.data || [];
|
||||
|
||||
const online = devices.filter((d: any) => d.status === 1 || d.boundStatus === 1).length;
|
||||
const offline = devices.filter((d: any) => d.status === 0 || d.boundStatus === 0).length;
|
||||
const fault = devices.filter((d: any) => d.status === -1).length;
|
||||
const total = devices.length;
|
||||
|
||||
// 按类型分组
|
||||
const typeMap: Record<string, number> = {};
|
||||
devices.forEach((d: any) => {
|
||||
const type = d.deviceType || 'unknown';
|
||||
typeMap[type] = (typeMap[type] || 0) + 1;
|
||||
});
|
||||
|
||||
const typeNameMap: Record<string, string> = {
|
||||
drone: '无人机',
|
||||
dock: '机库',
|
||||
camera: '摄像头',
|
||||
unknown: '其他',
|
||||
};
|
||||
|
||||
const byType = Object.entries(typeMap).map(([type, count]) => ({
|
||||
type,
|
||||
name: typeNameMap[type] || type,
|
||||
count,
|
||||
}));
|
||||
|
||||
return {
|
||||
total,
|
||||
online,
|
||||
offline,
|
||||
fault,
|
||||
onlineRate: total > 0 ? Math.round((online / total) * 100) : 0,
|
||||
byType,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('获取设备统计失败:', error);
|
||||
return {
|
||||
total: 0,
|
||||
online: 0,
|
||||
offline: 0,
|
||||
fault: 0,
|
||||
onlineRate: 0,
|
||||
byType: [],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取任务统计
|
||||
*/
|
||||
export async function getTaskStats(params?: {
|
||||
tenantId?: string;
|
||||
includeChildren?: boolean;
|
||||
statType?: 'day' | 'month' | 'year';
|
||||
date?: string;
|
||||
}): Promise<TaskStats> {
|
||||
try {
|
||||
const statType = params?.statType || 'day';
|
||||
const baseDate = params?.date ? dayjs(params.date) : dayjs();
|
||||
const start = baseDate.startOf(statType);
|
||||
const end = baseDate.endOf(statType);
|
||||
|
||||
const res: any = await listMission({
|
||||
page: 1,
|
||||
limit: 1000,
|
||||
tenantId: params?.tenantId,
|
||||
includeChildren: params?.includeChildren,
|
||||
startDate: start.format('YYYY-MM-DD'),
|
||||
endDate: end.format('YYYY-MM-DD'),
|
||||
});
|
||||
|
||||
const missions = res?.data || [];
|
||||
|
||||
const missionsInRange = missions.filter((m: any) => {
|
||||
if (!m?.createTime) return true;
|
||||
const createdAt = dayjs(m.createTime);
|
||||
if (!createdAt.isValid()) return true;
|
||||
const createdAtMs = createdAt.valueOf();
|
||||
return createdAtMs >= start.valueOf() && createdAtMs <= end.valueOf();
|
||||
});
|
||||
|
||||
const total = missionsInRange.length;
|
||||
const pending = missionsInRange.filter((m: any) => m.missionStatus === MissionStatus.PENDING).length;
|
||||
const running = missionsInRange.filter((m: any) => m.missionStatus === MissionStatus.DOING).length;
|
||||
const completed = missionsInRange.filter((m: any) =>
|
||||
m.missionStatus === MissionStatus.COMPLETE ||
|
||||
m.missionStatus === MissionStatus.UPLOADED
|
||||
).length;
|
||||
const failed = missionsInRange.filter((m: any) => m.missionStatus === MissionStatus.CANCELED).length;
|
||||
|
||||
// 统计区间内新增(与筛选范围保持一致)
|
||||
const todayNew = total;
|
||||
|
||||
return {
|
||||
total,
|
||||
pending,
|
||||
running,
|
||||
completed,
|
||||
failed,
|
||||
todayNew,
|
||||
successRate: total > 0 ? Math.round((completed / total) * 100) : 0,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('获取任务统计失败:', error);
|
||||
return {
|
||||
total: 0,
|
||||
pending: 0,
|
||||
running: 0,
|
||||
completed: 0,
|
||||
failed: 0,
|
||||
todayNew: 0,
|
||||
successRate: 0,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取趋势数据(模拟)
|
||||
*/
|
||||
export async function getTrendData(days: number = 7): Promise<{ taskTrend: TrendItem[]; deviceTrend: TrendItem[] }> {
|
||||
const taskTrend: TrendItem[] = [];
|
||||
const deviceTrend: TrendItem[] = [];
|
||||
|
||||
for (let i = days - 1; i >= 0; i--) {
|
||||
const date = new Date();
|
||||
date.setDate(date.getDate() - i);
|
||||
const dateStr = date.toISOString().split('T')[0];
|
||||
|
||||
taskTrend.push({
|
||||
date: dateStr,
|
||||
created: Math.floor(Math.random() * 20) + 5,
|
||||
completed: Math.floor(Math.random() * 15) + 3,
|
||||
failed: Math.floor(Math.random() * 3),
|
||||
});
|
||||
|
||||
deviceTrend.push({
|
||||
date: dateStr,
|
||||
online: Math.floor(Math.random() * 30) + 70,
|
||||
total: 100,
|
||||
});
|
||||
}
|
||||
|
||||
return { taskTrend, deviceTrend };
|
||||
}
|
||||
|
||||
/**
|
||||
* 模拟告警数据
|
||||
*/
|
||||
export function getMockAlerts(): AlertItem[] {
|
||||
return [
|
||||
{
|
||||
id: '1',
|
||||
type: 'device_offline',
|
||||
deviceSn: 'DRONE001',
|
||||
deviceName: '巡检无人机A',
|
||||
message: '设备离线超过5分钟',
|
||||
level: 'warning',
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
{
|
||||
id: '2',
|
||||
type: 'low_battery',
|
||||
deviceSn: 'DRONE002',
|
||||
deviceName: '巡检无人机B',
|
||||
message: '电池电量低于20%',
|
||||
level: 'warning',
|
||||
timestamp: new Date(Date.now() - 300000).toISOString(),
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
import { request } from 'umi';
|
||||
|
||||
export interface DeviceItem {
|
||||
deviceSn?: string;
|
||||
deviceName?: string;
|
||||
boundStatus?: number;
|
||||
createTime?: string;
|
||||
status?: number; // 0-离线 1-在线
|
||||
deviceType?: string; // drone/dock/camera
|
||||
}
|
||||
|
||||
export interface TakeoffParams {
|
||||
deviceSn: string;
|
||||
targetLatitude: number;
|
||||
targetLongitude: number;
|
||||
targetHeight?: number;
|
||||
securityTakeoffHeight?: number;
|
||||
rthMode?: number;
|
||||
rthAltitude?: number;
|
||||
rcLostAction?: number;
|
||||
commanderModeLostAction?: number;
|
||||
commanderFlightMode?: number;
|
||||
commanderFlightHeight?: number;
|
||||
flightId?: string;
|
||||
maxSpeed?: number;
|
||||
flightSafetyAdvanceCheck?: number;
|
||||
}
|
||||
|
||||
export interface StickControlParams {
|
||||
deviceSn: string;
|
||||
roll?: number;
|
||||
pitch?: number;
|
||||
throttle?: number;
|
||||
yaw?: number;
|
||||
}
|
||||
|
||||
export interface GimbalControlParams {
|
||||
deviceSn: string;
|
||||
pitchSpeed?: number;
|
||||
yawSpeed?: number;
|
||||
locked?: boolean;
|
||||
}
|
||||
|
||||
export interface CommandResult {
|
||||
code?: number;
|
||||
msg?: string;
|
||||
resp_code?: number;
|
||||
resp_msg?: string;
|
||||
data?: string;
|
||||
}
|
||||
|
||||
function normalizeResponse(response: any): { code: number; msg: string; data?: any } {
|
||||
const code = response.resp_code !== undefined ? response.resp_code : response.code;
|
||||
const msg = response.resp_msg !== undefined ? response.resp_msg : response.msg;
|
||||
const data = response.data;
|
||||
return { code: code !== undefined ? code : 1, msg: msg || '', data };
|
||||
}
|
||||
|
||||
export const deviceApi = {
|
||||
// 设备列表
|
||||
deviceList: async (params: { page?: number; limit?: number; [k:string]: any }) => {
|
||||
const res = await request('/api-device/device', { method: 'GET', params });
|
||||
return { data: (res as any).data, total: (res as any).count } as { data: DeviceItem[]; total: number };
|
||||
},
|
||||
|
||||
// 航线列表
|
||||
wayline: async (params: { current?: number; pageSize?: number; [k:string]: any }) => {
|
||||
const { current, pageSize, ...rest } = params || {};
|
||||
const res = await request('/api-device/wayline', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
|
||||
return { data: (res as any).data, total: (res as any).count };
|
||||
},
|
||||
|
||||
// 一键起飞
|
||||
takeoff: async (params: TakeoffParams): Promise<CommandResult> => {
|
||||
const res = await request('/api-device/device/command/takeoff', { method: 'POST', data: params });
|
||||
return normalizeResponse(res);
|
||||
},
|
||||
|
||||
// 一键返航
|
||||
returnHome: async (deviceSn: string): Promise<CommandResult> => {
|
||||
const res = await request('/api-device/device/command/return', { method: 'POST', params: { deviceSn } });
|
||||
return normalizeResponse(res);
|
||||
},
|
||||
|
||||
// 取消返航
|
||||
cancelReturnHome: async (deviceSn: string): Promise<CommandResult> => {
|
||||
const res = await request('/api-device/device/command/return/cancel', { method: 'POST', params: { deviceSn } });
|
||||
return res as CommandResult;
|
||||
},
|
||||
|
||||
// 暂停
|
||||
pause: async (deviceSn: string): Promise<CommandResult> => {
|
||||
const res = await request('/api-device/device/command/pause', { method: 'POST', params: { deviceSn } });
|
||||
return res as CommandResult;
|
||||
},
|
||||
|
||||
// 恢复
|
||||
resume: async (deviceSn: string): Promise<CommandResult> => {
|
||||
const res = await request('/api-device/device/command/resume', { method: 'POST', params: { deviceSn } });
|
||||
return res as CommandResult;
|
||||
},
|
||||
|
||||
// 拍照
|
||||
takePhoto: async (deviceSn: string): Promise<CommandResult> => {
|
||||
const res = await request('/api-device/device/command/photo', { method: 'POST', params: { deviceSn } });
|
||||
return res as CommandResult;
|
||||
},
|
||||
|
||||
// 开始录像
|
||||
startRecording: async (deviceSn: string): Promise<CommandResult> => {
|
||||
const res = await request('/api-device/device/command/recording/start', { method: 'POST', params: { deviceSn } });
|
||||
return res as CommandResult;
|
||||
},
|
||||
|
||||
// 停止录像
|
||||
stopRecording: async (deviceSn: string): Promise<CommandResult> => {
|
||||
const res = await request('/api-device/device/command/recording/stop', { method: 'POST', params: { deviceSn } });
|
||||
return res as CommandResult;
|
||||
},
|
||||
|
||||
// 切换相机模式(0=拍照模式,1=录像模式)
|
||||
switchCameraMode: async (deviceSn: string, cameraMode: number): Promise<CommandResult> => {
|
||||
const res = await request('/api-device/device/command/camera/mode', { method: 'POST', params: { deviceSn, cameraMode } });
|
||||
return res as CommandResult;
|
||||
},
|
||||
|
||||
// 进入DRC模式
|
||||
enterDrcMode: async (deviceSn: string): Promise<CommandResult> => {
|
||||
const res = await request('/api-device/device/command/drc/enter', { method: 'POST', params: { deviceSn } });
|
||||
return res as CommandResult;
|
||||
},
|
||||
|
||||
// 杆量控制
|
||||
stickControl: async (params: StickControlParams): Promise<CommandResult> => {
|
||||
const res = await request('/api-device/device/command/drc/stick', { method: 'POST', data: params });
|
||||
return res as CommandResult;
|
||||
},
|
||||
|
||||
// 云台控制
|
||||
gimbalControl: async (params: GimbalControlParams): Promise<CommandResult> => {
|
||||
const res = await request('/api-device/device/command/gimbal', { method: 'POST', data: params });
|
||||
return res as CommandResult;
|
||||
},
|
||||
|
||||
// 订阅无人机遥测
|
||||
subscribeDroneTelemetry: async (deviceSn: string): Promise<{ success: boolean; message?: string }> => {
|
||||
try {
|
||||
const res = await request(`/api-device/sse/drone-telemetry/${deviceSn}/subscribe`, { method: 'POST' });
|
||||
return { success: true, message: res as string };
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message };
|
||||
}
|
||||
},
|
||||
|
||||
// 取消订阅
|
||||
unsubscribeDroneTelemetry: async (deviceSn: string): Promise<{ success: boolean; message?: string }> => {
|
||||
try {
|
||||
const res = await request(`/api-device/sse/drone-telemetry/${deviceSn}/unsubscribe`, { method: 'POST' });
|
||||
return { success: true, message: res as string };
|
||||
} catch (error: any) {
|
||||
return { success: false, message: error.message };
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,144 @@
|
||||
/**
|
||||
* 设备实时控制服务
|
||||
* 用于云台控制和摇杆控制
|
||||
* 使用HTTP API实现(替代WebSocket)
|
||||
*/
|
||||
|
||||
import { request } from 'umi';
|
||||
|
||||
export interface StickControlData {
|
||||
/** 横滚通道(624-1424,1024为中值,控制左右平移) */
|
||||
roll?: number;
|
||||
/** 俯仰通道(624-1424,1024为中值,控制前后平移) */
|
||||
pitch?: number;
|
||||
/** 升降通道(624-1424,1024为悬停,控制升降) */
|
||||
throttle?: number;
|
||||
/** 偏航通道(624-1424,1024为中值,控制左右旋转) */
|
||||
yaw?: number;
|
||||
}
|
||||
|
||||
export interface GimbalControlData {
|
||||
/** 云台 pitch 速度(度/秒) */
|
||||
pitchSpeed?: number;
|
||||
/** 云台 yaw 速度(度/秒) */
|
||||
yawSpeed?: number;
|
||||
/** 是否锁定机头:false=仅云台转,true=机身一起转 */
|
||||
locked?: boolean;
|
||||
}
|
||||
|
||||
type StatusHandler = (connected: boolean) => void;
|
||||
|
||||
class DeviceControlService {
|
||||
private statusHandlers: StatusHandler[] = [];
|
||||
private currentDeviceSn: string | null = null;
|
||||
private isActive = false;
|
||||
|
||||
/**
|
||||
* 连接设备(标记为活跃状态)
|
||||
*/
|
||||
connect(deviceSn: string): void {
|
||||
this.currentDeviceSn = deviceSn;
|
||||
this.isActive = true;
|
||||
console.log('[ControlHTTP] 已连接设备:', deviceSn);
|
||||
this.notifyStatusHandlers(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 断开连接(标记为非活跃状态)
|
||||
*/
|
||||
disconnect(): void {
|
||||
console.log('[ControlHTTP] 断开连接');
|
||||
this.isActive = false;
|
||||
this.currentDeviceSn = null;
|
||||
this.notifyStatusHandlers(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送摇杆控制指令
|
||||
*/
|
||||
sendStickControl(data: StickControlData): boolean {
|
||||
if (!this.currentDeviceSn || !this.isActive) {
|
||||
console.warn('[ControlHTTP] 未连接设备');
|
||||
return false;
|
||||
}
|
||||
|
||||
// 使用异步请求,不等待响应(提高控制频率)
|
||||
request('/api-device/device/command/drc/stick', {
|
||||
method: 'POST',
|
||||
data: {
|
||||
deviceSn: this.currentDeviceSn,
|
||||
roll: data.roll ?? 1024,
|
||||
pitch: data.pitch ?? 1024,
|
||||
throttle: data.throttle ?? 1024,
|
||||
yaw: data.yaw ?? 1024,
|
||||
gimbalPitch: 1024,
|
||||
},
|
||||
}).catch(e => {
|
||||
console.warn('[ControlHTTP] 摇杆指令发送失败:', e);
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送云台控制指令
|
||||
*/
|
||||
sendGimbalControl(data: GimbalControlData): boolean {
|
||||
if (!this.currentDeviceSn || !this.isActive) {
|
||||
console.warn('[ControlHTTP] 未连接设备');
|
||||
return false;
|
||||
}
|
||||
|
||||
// 使用异步请求,不等待响应
|
||||
request('/api-device/device/command/gimbal', {
|
||||
method: 'POST',
|
||||
data: {
|
||||
deviceSn: this.currentDeviceSn,
|
||||
pitchSpeed: data.pitchSpeed ?? 0,
|
||||
yawSpeed: data.yawSpeed ?? 0,
|
||||
locked: data.locked ?? false,
|
||||
},
|
||||
}).catch(e => {
|
||||
console.warn('[ControlHTTP] 云台指令发送失败:', e);
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否已连接
|
||||
*/
|
||||
isConnected(): boolean {
|
||||
return this.isActive && this.currentDeviceSn !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前设备SN
|
||||
*/
|
||||
getCurrentDeviceSn(): string | null {
|
||||
return this.currentDeviceSn;
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加状态处理器
|
||||
*/
|
||||
onStatusChange(handler: StatusHandler): () => void {
|
||||
this.statusHandlers.push(handler);
|
||||
return () => {
|
||||
this.statusHandlers = this.statusHandlers.filter(h => h !== handler);
|
||||
};
|
||||
}
|
||||
|
||||
private notifyStatusHandlers(connected: boolean): void {
|
||||
this.statusHandlers.forEach(handler => {
|
||||
try {
|
||||
handler(connected);
|
||||
} catch (e) {
|
||||
console.error('[ControlHTTP] 状态处理器错误:', e);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 导出单例(保持与原WebSocket版本相同的接口名)
|
||||
export const deviceControlWs = new DeviceControlService();
|
||||
@@ -0,0 +1,59 @@
|
||||
import { request } from 'umi';
|
||||
import { encryptPassword } from '@/utils/rsaUtil';
|
||||
|
||||
export interface LoginParams {
|
||||
username: string;
|
||||
password: string;
|
||||
tenantId?: string;
|
||||
deviceId?: string;
|
||||
clientId?: string;
|
||||
clientSecret?: string;
|
||||
validCode?: string;
|
||||
}
|
||||
|
||||
// 获取当前用户信息
|
||||
export async function currentUser(): Promise<any> {
|
||||
const res = await request('/api-user/users/current', { method: 'GET' });
|
||||
const mapped: any = res as any;
|
||||
if (typeof mapped?.success !== 'undefined') {
|
||||
if (mapped.success) return mapped.data;
|
||||
return { resp_msg: mapped.msg } as any;
|
||||
}
|
||||
return mapped;
|
||||
}
|
||||
|
||||
// 退出登录
|
||||
export async function outLogin(): Promise<any> {
|
||||
return request('/api-uaa/oauth/logout', { method: 'POST' });
|
||||
}
|
||||
|
||||
// 登录
|
||||
export async function login(body: LoginParams): Promise<any> {
|
||||
const encPwd = encryptPassword(body.password || '');
|
||||
|
||||
if (!encPwd) {
|
||||
throw new Error('密码加密失败,请刷新页面重试');
|
||||
}
|
||||
|
||||
const grantType = 'password_code';
|
||||
|
||||
const requestData = {
|
||||
userName: body.username,
|
||||
password: encPwd,
|
||||
grantType,
|
||||
clientId: body.clientId,
|
||||
validCode: body.validCode,
|
||||
deviceId: body.deviceId,
|
||||
};
|
||||
|
||||
const res = await request('/api-uaa/oauth/login', {
|
||||
method: 'POST',
|
||||
data: requestData,
|
||||
});
|
||||
const mapped: any = res as any;
|
||||
if (typeof mapped?.success !== 'undefined') {
|
||||
if (mapped.success) return mapped.data;
|
||||
return { resp_msg: mapped.msg } as any;
|
||||
}
|
||||
return mapped;
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
import { request } from 'umi';
|
||||
|
||||
/**
|
||||
* 任务类型枚举
|
||||
*/
|
||||
export enum MissionType {
|
||||
WAYLINE = 1, // 航线任务
|
||||
TAKEOFF = 2, // 一键起飞任务
|
||||
}
|
||||
|
||||
/**
|
||||
* 任务状态枚举
|
||||
*/
|
||||
export enum MissionStatus {
|
||||
PENDING = 1, // 待执行
|
||||
CANCELED = 2, // 已取消
|
||||
COMPLETE = 3, // 已完成
|
||||
DOING = 4, // 执行中
|
||||
UPLOADING = 5, // 图片上传中
|
||||
UPLOADED = 6, // 图片上传完成
|
||||
}
|
||||
|
||||
/**
|
||||
* 任务类型描述映射
|
||||
*/
|
||||
export const MissionTypeMap: Record<number, string> = {
|
||||
[MissionType.WAYLINE]: '航线任务',
|
||||
[MissionType.TAKEOFF]: '一键起飞',
|
||||
};
|
||||
|
||||
/**
|
||||
* 任务状态描述映射
|
||||
*/
|
||||
export const MissionStatusMap: Record<number, string> = {
|
||||
[MissionStatus.PENDING]: '待执行',
|
||||
[MissionStatus.CANCELED]: '已取消',
|
||||
[MissionStatus.COMPLETE]: '已完成',
|
||||
[MissionStatus.DOING]: '执行中',
|
||||
[MissionStatus.UPLOADING]: '上传中',
|
||||
[MissionStatus.UPLOADED]: '上传完成',
|
||||
};
|
||||
|
||||
/**
|
||||
* 任务状态颜色映射
|
||||
*/
|
||||
export const MissionStatusColorMap: Record<number, string> = {
|
||||
[MissionStatus.PENDING]: 'default',
|
||||
[MissionStatus.CANCELED]: 'error',
|
||||
[MissionStatus.COMPLETE]: 'success',
|
||||
[MissionStatus.DOING]: 'processing',
|
||||
[MissionStatus.UPLOADING]: 'warning',
|
||||
[MissionStatus.UPLOADED]: 'success',
|
||||
};
|
||||
|
||||
/**
|
||||
* 任务实体接口
|
||||
*/
|
||||
export interface Mission {
|
||||
id?: number;
|
||||
missionCode?: string;
|
||||
missionName?: string;
|
||||
missionType?: number;
|
||||
missionTypeDesc?: string;
|
||||
tourismId?: number;
|
||||
deviceSn?: string;
|
||||
waylineId?: string;
|
||||
waylineName?: string;
|
||||
missionStatus?: number;
|
||||
missionStatusDesc?: string;
|
||||
targetLatitude?: number;
|
||||
targetLongitude?: number;
|
||||
targetHeight?: number;
|
||||
creatorId?: number;
|
||||
creatorName?: string;
|
||||
startTime?: string;
|
||||
endTime?: string;
|
||||
remark?: string;
|
||||
createTime?: string;
|
||||
updateTime?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 任务图片实体接口
|
||||
*/
|
||||
export interface MissionImage {
|
||||
id?: number;
|
||||
missionCode?: string;
|
||||
tourismId?: number;
|
||||
deviceSn?: string;
|
||||
fileId?: string;
|
||||
filePath?: string;
|
||||
fileType?: string;
|
||||
viewUrl?: string;
|
||||
latitude?: number;
|
||||
longitude?: number;
|
||||
altitude?: number;
|
||||
shootTime?: string;
|
||||
createTime?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建任务请求参数
|
||||
*/
|
||||
export interface CreateMissionParams {
|
||||
deviceSn: string;
|
||||
missionType?: number;
|
||||
missionName?: string;
|
||||
tourismId?: number;
|
||||
waylineId?: string;
|
||||
waylineName?: string;
|
||||
targetLatitude?: number;
|
||||
targetLongitude?: number;
|
||||
targetHeight?: number;
|
||||
remark?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询任务列表请求参数
|
||||
*/
|
||||
export interface ListMissionParams {
|
||||
page?: number;
|
||||
limit?: number;
|
||||
deviceSn?: string;
|
||||
missionStatus?: number;
|
||||
missionType?: number;
|
||||
tourismId?: number;
|
||||
startDate?: string;
|
||||
endDate?: string;
|
||||
tenantId?: string;
|
||||
includeChildren?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建任务
|
||||
*/
|
||||
export async function saveMission(params: CreateMissionParams | any) {
|
||||
return request<API.Result<Mission>>('/api-order/mission/saveMission', {
|
||||
method: 'POST',
|
||||
data: params,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行任务(下发到设备)
|
||||
*/
|
||||
export async function executeMission(missionCode: string) {
|
||||
return request<API.Result<string>>('/api-order/mission/executeMission', {
|
||||
method: 'POST',
|
||||
data: { missionCode },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询任务列表
|
||||
*/
|
||||
export async function listMission(params: ListMissionParams) {
|
||||
return request<API.PageResult<Mission>>('/api-order/mission/listMission', {
|
||||
method: 'POST',
|
||||
data: params,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取任务详情
|
||||
*/
|
||||
export async function getMission(missionCode: string) {
|
||||
return request<API.Result<Mission>>('/api-order/mission/getMission', {
|
||||
method: 'POST',
|
||||
data: { missionCode },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新任务状态
|
||||
*/
|
||||
export async function updateMissionStatus(missionCode: string, status: number) {
|
||||
return request<API.Result<string>>('/api-order/mission/updateMissionStatus', {
|
||||
method: 'POST',
|
||||
data: { missionCode, status },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消任务
|
||||
*/
|
||||
export async function cancelMission(missionCode: string) {
|
||||
return request<API.Result<string>>('/api-order/mission/cancelMission', {
|
||||
method: 'POST',
|
||||
data: { missionCode },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 完成任务
|
||||
*/
|
||||
export async function completeMission(missionCode: string) {
|
||||
return request<API.Result<string>>('/api-order/mission/completeMission', {
|
||||
method: 'POST',
|
||||
data: { missionCode },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除任务
|
||||
*/
|
||||
export async function deleteMission(missionCode: string) {
|
||||
return request<API.Result<string>>('/api-order/mission/deleteMission', {
|
||||
method: 'POST',
|
||||
data: { missionCode },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存任务图片记录
|
||||
*/
|
||||
export async function saveMissionImage(params: Partial<MissionImage>) {
|
||||
return request<API.Result<MissionImage>>('/api-order/mission/image/saveMissionImage', {
|
||||
method: 'POST',
|
||||
data: params,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询任务图片列表
|
||||
*/
|
||||
export async function listMissionImage(missionCode: string) {
|
||||
return request<API.Result<MissionImage[]>>('/api-order/mission/image/listMissionImage', {
|
||||
method: 'POST',
|
||||
data: { missionCode },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询任务图片列表
|
||||
*/
|
||||
export async function pageMissionImage(params: {
|
||||
page?: number;
|
||||
limit?: number;
|
||||
missionCode?: string;
|
||||
deviceSn?: string;
|
||||
}) {
|
||||
return request<API.PageResult<MissionImage>>('/api-order/mission/image/pageMissionImage', {
|
||||
method: 'POST',
|
||||
data: params,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取图片详情
|
||||
*/
|
||||
export async function getMissionImage(id: number) {
|
||||
return request<API.Result<MissionImage>>('/api-order/mission/image/getMissionImage', {
|
||||
method: 'POST',
|
||||
data: { id },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除图片记录
|
||||
*/
|
||||
export async function deleteMissionImage(id: number) {
|
||||
return request<API.Result<string>>('/api-order/mission/image/deleteMissionImage', {
|
||||
method: 'POST',
|
||||
data: { id },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 统计任务图片数量
|
||||
*/
|
||||
export async function countMissionImage(missionCode: string) {
|
||||
return request<API.Result<number>>('/api-order/mission/image/countMissionImage', {
|
||||
method: 'POST',
|
||||
data: { missionCode },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { request } from 'umi';
|
||||
|
||||
/**
|
||||
* 订单服务(精简版)
|
||||
* 仅保留3D地图需要的景区相关接口
|
||||
*/
|
||||
export const ordersApi = {
|
||||
// 景区管理
|
||||
tourism: async (params: { current?: number; pageSize?: number; [k: string]: any }) => {
|
||||
const { current, pageSize, ...rest } = params || {};
|
||||
const res = await request('/api-order/tourism', { method: 'GET', params: { page: current, limit: pageSize, ...rest } });
|
||||
return { data: (res as any).data, total: (res as any).count };
|
||||
},
|
||||
|
||||
// 根据景区ID获取设备SN列表
|
||||
getDeviceSnsByTourismId: async (tourismId: number) => {
|
||||
const res = await request(`/api-order/tourism/${tourismId}/device-sns`, { method: 'GET' });
|
||||
return (res as any).data || [];
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,274 @@
|
||||
/**
|
||||
* SRS 流媒体服务
|
||||
* 处理 SRS 服务器认证和 WebRTC WHEP 视频流播放
|
||||
*/
|
||||
|
||||
// SRS 服务器配置
|
||||
const SRS_CONFIG = {
|
||||
// 所有环境都通过代理访问,避免跨域问题
|
||||
// 开发环境: webpack devServer 代理
|
||||
// 测试/生产环境: nginx 代理
|
||||
baseUrl: '',
|
||||
// 登录密码
|
||||
password: 'a6949674ed817fa3',
|
||||
};
|
||||
|
||||
// WebRTC ICE 服务器配置(用于 NAT 穿透)
|
||||
// 必须与 SRS 服务器配置的 STUN/TURN 一致
|
||||
const ICE_SERVERS: RTCConfiguration = {
|
||||
iceServers: [
|
||||
// 自建 STUN 服务器
|
||||
{ urls: 'stun:220.205.16.27:3478' },
|
||||
// 自建 TURN 服务器(用于复杂 NAT 环境)
|
||||
{
|
||||
urls: 'turn:220.205.16.27:3478?transport=udp',
|
||||
username: 'webrtc',
|
||||
credential: 'GoFly@2024',
|
||||
},
|
||||
// 备用 Google STUN(可选)
|
||||
{ urls: 'stun:stun.l.google.com:19302' },
|
||||
],
|
||||
iceCandidatePoolSize: 10,
|
||||
};
|
||||
|
||||
// 存储 token
|
||||
let srsToken: string | null = null;
|
||||
let tokenExpireTime: number = 0;
|
||||
|
||||
export interface SrsLoginResponse {
|
||||
code: number;
|
||||
data?: {
|
||||
token: string;
|
||||
[key: string]: any;
|
||||
};
|
||||
}
|
||||
|
||||
export const srsApi = {
|
||||
/**
|
||||
* 登录 SRS 服务器获取 token
|
||||
* @param password 登录密码
|
||||
*/
|
||||
login: async (password?: string): Promise<{ success: boolean; token?: string; error?: string }> => {
|
||||
try {
|
||||
const response = await fetch(`${SRS_CONFIG.baseUrl}/terraform/v1/mgmt/login`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ password: password || SRS_CONFIG.password }),
|
||||
credentials: 'include', // 重要:携带 cookie
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return { success: false, error: `HTTP ${response.status}` };
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.code === 0 && data.data?.token) {
|
||||
srsToken = data.data.token;
|
||||
// token 有效期设为 1 小时
|
||||
tokenExpireTime = Date.now() + 3600 * 1000;
|
||||
return { success: true, token: data.data.token };
|
||||
}
|
||||
|
||||
return { success: false, error: data.msg || '登录失败' };
|
||||
} catch (error: any) {
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 获取当前 token(如果过期则重新登录)
|
||||
*/
|
||||
getToken: async (): Promise<string | null> => {
|
||||
// 检查 token 是否有效
|
||||
if (srsToken && Date.now() < tokenExpireTime) {
|
||||
return srsToken;
|
||||
}
|
||||
|
||||
// 重新登录获取 token
|
||||
const result = await srsApi.login();
|
||||
return result.success ? result.token || null : null;
|
||||
},
|
||||
|
||||
/**
|
||||
* 检查是否已登录
|
||||
*/
|
||||
isLoggedIn: (): boolean => {
|
||||
return !!srsToken && Date.now() < tokenExpireTime;
|
||||
},
|
||||
|
||||
/**
|
||||
* 构建 WHEP 播放 URL
|
||||
* @param streamId 流ID(如 49214ac552fa)
|
||||
* @param app 应用名称(默认 live)
|
||||
*/
|
||||
buildWhepUrl: (streamId: string, app: string = 'live'): string => {
|
||||
return `${SRS_CONFIG.baseUrl}/rtc/v1/whep/?app=${app}&stream=${streamId}`;
|
||||
},
|
||||
|
||||
/**
|
||||
* 使用 WHEP 协议播放 WebRTC 视频流
|
||||
* @param streamId 流ID
|
||||
* @param videoElement video 元素
|
||||
* @param options 选项
|
||||
*/
|
||||
playWhep: async (
|
||||
streamId: string,
|
||||
videoElement: HTMLVideoElement,
|
||||
options?: { app?: string; videoOnly?: boolean; audioOnly?: boolean }
|
||||
): Promise<{
|
||||
success: boolean;
|
||||
pc?: RTCPeerConnection;
|
||||
stream?: MediaStream;
|
||||
error?: string;
|
||||
}> => {
|
||||
try {
|
||||
// 确保已登录
|
||||
const token = await srsApi.getToken();
|
||||
if (!token) {
|
||||
return { success: false, error: 'SRS 认证失败,请检查密码' };
|
||||
}
|
||||
|
||||
const url = srsApi.buildWhepUrl(streamId, options?.app);
|
||||
|
||||
// 创建 RTCPeerConnection(配置 ICE 服务器用于 NAT 穿透)
|
||||
const pc = new RTCPeerConnection(ICE_SERVERS);
|
||||
const stream = new MediaStream();
|
||||
|
||||
// 设置接收音视频轨道
|
||||
if (!options?.videoOnly) {
|
||||
pc.addTransceiver('audio', { direction: 'recvonly' });
|
||||
}
|
||||
if (!options?.audioOnly) {
|
||||
pc.addTransceiver('video', { direction: 'recvonly' });
|
||||
}
|
||||
|
||||
// 监听远端轨道
|
||||
pc.ontrack = (event) => {
|
||||
stream.addTrack(event.track);
|
||||
videoElement.srcObject = stream;
|
||||
};
|
||||
|
||||
// 创建 offer
|
||||
const offer = await pc.createOffer();
|
||||
await pc.setLocalDescription(offer);
|
||||
|
||||
// 发送 offer 到 WHEP 端点
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/sdp',
|
||||
},
|
||||
body: offer.sdp,
|
||||
credentials: 'include', // 携带 cookie
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
pc.close();
|
||||
return { success: false, error: `WHEP 请求失败: HTTP ${response.status}` };
|
||||
}
|
||||
|
||||
const answerSdp = await response.text();
|
||||
|
||||
// 设置远端描述
|
||||
await pc.setRemoteDescription(new RTCSessionDescription({
|
||||
type: 'answer',
|
||||
sdp: answerSdp,
|
||||
}));
|
||||
|
||||
return { success: true, pc, stream };
|
||||
} catch (error: any) {
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 使用完整 URL 播放 WHEP 视频流
|
||||
* @param whepUrl 完整的 WHEP URL(如:http://220.205.16.27:8024/rtc/v1/whep/?app=live&stream=xxx)
|
||||
* @param videoElement video 元素
|
||||
* @param options 选项
|
||||
*/
|
||||
playWhepByUrl: async (
|
||||
whepUrl: string,
|
||||
videoElement: HTMLVideoElement,
|
||||
options?: { videoOnly?: boolean; audioOnly?: boolean }
|
||||
): Promise<{
|
||||
success: boolean;
|
||||
pc?: RTCPeerConnection;
|
||||
stream?: MediaStream;
|
||||
error?: string;
|
||||
}> => {
|
||||
try {
|
||||
// 解析 URL,提取路径部分通过代理访问(避免跨域)
|
||||
const urlObj = new URL(whepUrl);
|
||||
// 所有环境都使用代理路径,避免跨域问题
|
||||
const actualUrl = `${urlObj.pathname}${urlObj.search}`;
|
||||
|
||||
// 确保已登录
|
||||
const token = await srsApi.getToken();
|
||||
|
||||
// 创建 RTCPeerConnection(配置 ICE 服务器用于 NAT 穿透)
|
||||
const pc = new RTCPeerConnection(ICE_SERVERS);
|
||||
const stream = new MediaStream();
|
||||
|
||||
// 设置接收音视频轨道
|
||||
if (!options?.videoOnly) {
|
||||
pc.addTransceiver('audio', { direction: 'recvonly' });
|
||||
}
|
||||
if (!options?.audioOnly) {
|
||||
pc.addTransceiver('video', { direction: 'recvonly' });
|
||||
}
|
||||
|
||||
// 监听远端轨道
|
||||
pc.ontrack = (event) => {
|
||||
stream.addTrack(event.track);
|
||||
videoElement.srcObject = stream;
|
||||
};
|
||||
|
||||
// 创建 offer
|
||||
const offer = await pc.createOffer();
|
||||
await pc.setLocalDescription(offer);
|
||||
|
||||
// 发送 offer 到 WHEP 端点
|
||||
const response = await fetch(actualUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/sdp',
|
||||
},
|
||||
body: offer.sdp,
|
||||
credentials: 'include', // 携带 cookie
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
pc.close();
|
||||
return { success: false, error: `WHEP 请求失败: HTTP ${response.status}` };
|
||||
}
|
||||
|
||||
const answerSdp = await response.text();
|
||||
|
||||
// 设置远端描述
|
||||
await pc.setRemoteDescription(new RTCSessionDescription({
|
||||
type: 'answer',
|
||||
sdp: answerSdp,
|
||||
}));
|
||||
|
||||
return { success: true, pc, stream };
|
||||
} catch (error: any) {
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 停止播放并清理资源
|
||||
*/
|
||||
stopPlay: (pc: RTCPeerConnection | null, stream: MediaStream | null) => {
|
||||
if (stream) {
|
||||
stream.getTracks().forEach(track => track.stop());
|
||||
}
|
||||
if (pc) {
|
||||
pc.close();
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,60 @@
|
||||
import { request } from 'umi';
|
||||
|
||||
export interface TenantTreeNode {
|
||||
tenantId: string;
|
||||
tenantName: string;
|
||||
parentTenantId?: string;
|
||||
tenantType: string;
|
||||
tenantLevel: number;
|
||||
status: number;
|
||||
enabled: boolean;
|
||||
description?: string;
|
||||
children?: TenantTreeNode[];
|
||||
hasChildren?: boolean;
|
||||
childrenCount?: number;
|
||||
}
|
||||
|
||||
export interface TenantInfo {
|
||||
tenantId: string;
|
||||
tenantName: string;
|
||||
parentTenantId?: string;
|
||||
parentTenantName?: string;
|
||||
tenantLevel: number;
|
||||
tenantPath: string;
|
||||
tenantType: string;
|
||||
tenantCode?: string;
|
||||
contactPerson?: string;
|
||||
contactPhone?: string;
|
||||
address?: string;
|
||||
description?: string;
|
||||
status: number;
|
||||
statusText: string;
|
||||
hasChildren?: boolean;
|
||||
childrenCount?: number;
|
||||
createTime?: string;
|
||||
updateTime?: string;
|
||||
}
|
||||
|
||||
export const tenantApi = {
|
||||
// 可访问租户树
|
||||
getAccessibleTenants: () => request('/api-user/tenant/accessible', { method: 'GET' }),
|
||||
// 切换当前查询租户
|
||||
switchTenant: (tenantId: string) => request('/api-user/tenant/switch-query', { method: 'POST', params: { tenantId } }),
|
||||
// 当前租户详情
|
||||
getCurrentTenant: () => request('/api-user/tenant/current/info', { method: 'GET' }),
|
||||
// 当前查询范围统计
|
||||
getScopeStats: () => request('/api-user/tenant/scope/stats', { method: 'GET' }),
|
||||
// 重置为默认租户
|
||||
resetToDefaultTenant: () => request('/api-user/tenant/reset', { method: 'POST' }),
|
||||
};
|
||||
|
||||
declare global {
|
||||
namespace API {
|
||||
interface ResponseStructure<T = any> {
|
||||
success: boolean;
|
||||
code?: number;
|
||||
msg?: string;
|
||||
data: T;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import { request } from 'umi';
|
||||
|
||||
const API_BASE = '/api-device/3d-model';
|
||||
|
||||
export enum ModelType {
|
||||
OBLIQUE = 1,
|
||||
POINT_CLOUD = 2,
|
||||
BIM = 3,
|
||||
OTHER = 4,
|
||||
}
|
||||
|
||||
export const ModelTypeMap: Record<number, string> = {
|
||||
1: '倾斜摄影',
|
||||
2: '点云',
|
||||
3: 'BIM',
|
||||
4: '其他',
|
||||
};
|
||||
|
||||
export interface ThreeDModelVO {
|
||||
id: number;
|
||||
modelName: string;
|
||||
modelType: number;
|
||||
modelTypeName: string;
|
||||
modelFormat: string;
|
||||
description: string;
|
||||
tilesetUrl: string;
|
||||
fileCount: number;
|
||||
totalSize: number;
|
||||
totalSizeFormat: string;
|
||||
tourismId: number;
|
||||
tourismName: string;
|
||||
position: {
|
||||
longitude: number;
|
||||
latitude: number;
|
||||
height: number;
|
||||
cesiumHeight?: number;
|
||||
arcgisHeight?: number;
|
||||
terrainType?: string;
|
||||
};
|
||||
transform: {
|
||||
scale: number;
|
||||
rotationX: number;
|
||||
rotationY: number;
|
||||
rotationZ: number;
|
||||
};
|
||||
style: {
|
||||
maximumScreenSpaceError: number;
|
||||
maximumMemoryUsage: number;
|
||||
skipLevelOfDetail: boolean;
|
||||
preferLeaves: boolean;
|
||||
};
|
||||
status: number;
|
||||
statusName: string;
|
||||
uploadStatus: number;
|
||||
uploadStatusName: string;
|
||||
uploadProgress: number;
|
||||
thumbnailUrl: string;
|
||||
sourceType: string;
|
||||
createTime: string;
|
||||
updateTime: string;
|
||||
}
|
||||
|
||||
export interface ModelQueryParams {
|
||||
page?: number;
|
||||
limit?: number;
|
||||
modelName?: string;
|
||||
modelType?: number;
|
||||
tourismId?: number;
|
||||
status?: number;
|
||||
uploadStatus?: number;
|
||||
}
|
||||
|
||||
export async function getModelList(params: ModelQueryParams) {
|
||||
return request<API.PageResult<ThreeDModelVO>>(API_BASE, {
|
||||
method: 'GET',
|
||||
params,
|
||||
});
|
||||
}
|
||||
|
||||
export async function getModelById(id: number) {
|
||||
return request<API.Result<ThreeDModelVO>>(`${API_BASE}/${id}`, {
|
||||
method: 'GET',
|
||||
});
|
||||
}
|
||||
|
||||
export async function getModelsByTourismId(tourismId: number) {
|
||||
return request<API.Result<ThreeDModelVO[]>>(`${API_BASE}/tourism/${tourismId}`, {
|
||||
method: 'GET',
|
||||
});
|
||||
}
|
||||
|
||||
export async function getAvailableModels() {
|
||||
return request<API.Result<ThreeDModelVO[]>>(`${API_BASE}/available`, {
|
||||
method: 'GET',
|
||||
});
|
||||
}
|
||||
|
||||
export function convertToTilesetConfig(model: ThreeDModelVO) {
|
||||
return {
|
||||
id: `model_${model.id}`,
|
||||
name: model.modelName,
|
||||
url: model.tilesetUrl,
|
||||
tourismId: model.tourismId,
|
||||
position: model.position ? {
|
||||
longitude: model.position.longitude || 0,
|
||||
latitude: model.position.latitude || 0,
|
||||
height: model.position.height || 0,
|
||||
cesiumHeight: model.position.cesiumHeight,
|
||||
arcgisHeight: model.position.arcgisHeight,
|
||||
terrainType: model.position.terrainType || 'cesium_ion',
|
||||
} : undefined,
|
||||
transform: model.transform ? {
|
||||
scale: model.transform.scale || 1,
|
||||
rotationX: model.transform.rotationX || 0,
|
||||
rotationY: model.transform.rotationY || 0,
|
||||
rotationZ: model.transform.rotationZ || 0,
|
||||
} : undefined,
|
||||
style: {
|
||||
maximumScreenSpaceError: model.style?.maximumScreenSpaceError || 1,
|
||||
maximumMemoryUsage: model.style?.maximumMemoryUsage || 2048,
|
||||
skipLevelOfDetail: model.style?.skipLevelOfDetail ?? false,
|
||||
preferLeaves: model.style?.preferLeaves ?? true,
|
||||
},
|
||||
visible: model.status === 1,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
import { request } from 'umi';
|
||||
|
||||
// 航线任务列表项
|
||||
export interface WaylineRouteListItemVO {
|
||||
routeId: string;
|
||||
routeName: string;
|
||||
fileWaylineId: string;
|
||||
deviceSn: string;
|
||||
deviceName: string;
|
||||
parseStatus: number;
|
||||
parseStatusDesc?: string;
|
||||
waypointCount: number;
|
||||
totalDistance: number;
|
||||
totalDuration: number;
|
||||
createTime: string;
|
||||
}
|
||||
|
||||
// 航点数据
|
||||
export interface WaypointVO {
|
||||
index: number;
|
||||
longitude: number;
|
||||
latitude: number;
|
||||
height: number; // 相对高度
|
||||
executeHeight?: number; // 执行高度
|
||||
ellipsoidHeight?: number; // 椭球高度(用于3D地图显示)
|
||||
speed?: number;
|
||||
headingAngle?: number;
|
||||
actions?: WaypointActionVO[];
|
||||
}
|
||||
|
||||
// 轨迹点数据
|
||||
export interface TrackPointVO {
|
||||
lng: number;
|
||||
lat: number;
|
||||
alt?: number;
|
||||
height?: number;
|
||||
speed?: number;
|
||||
heading?: number;
|
||||
batteryPercent?: number;
|
||||
time?: string;
|
||||
deviationDistance?: number;
|
||||
isDeviation?: boolean;
|
||||
}
|
||||
|
||||
// 航点动作数据
|
||||
export interface WaypointActionVO {
|
||||
actionGroupId?: number;
|
||||
actionIndex?: number;
|
||||
actionType?: string;
|
||||
actionTypeDesc?: string;
|
||||
actionParams?: Record<string, any>;
|
||||
triggerType?: string;
|
||||
triggerTypeDesc?: string;
|
||||
delayTime?: number;
|
||||
payloadPositionIndex?: number;
|
||||
hoverTime?: number;
|
||||
aircraftHeading?: number;
|
||||
gimbalPitchRotateAngle?: number;
|
||||
gimbalYawRotateAngle?: number;
|
||||
focalLength?: number;
|
||||
megaphoneFilePath?: string;
|
||||
}
|
||||
|
||||
// 创建航线任务参数
|
||||
export interface CreateRouteParams {
|
||||
routeName: string;
|
||||
fileWaylineId: string;
|
||||
deviceSn: string;
|
||||
deviceName?: string;
|
||||
remark?: string;
|
||||
}
|
||||
|
||||
// 航线任务详情
|
||||
export interface WaylineRouteDetailVO {
|
||||
routeId: string;
|
||||
routeName: string;
|
||||
fileWaylineId: string;
|
||||
deviceSn: string;
|
||||
deviceName: string;
|
||||
parseStatus: number;
|
||||
parseStatusDesc?: string;
|
||||
waypointCount: number;
|
||||
totalDistance: number;
|
||||
totalDuration: number;
|
||||
waypoints?: WaypointVO[];
|
||||
}
|
||||
|
||||
// 飞行轨迹数据
|
||||
export interface FlightTrackData {
|
||||
deviceSn: string;
|
||||
jobId?: string;
|
||||
routeId?: string;
|
||||
trackPoints: TrackPointVO[];
|
||||
totalPoints: number;
|
||||
duration: number;
|
||||
startTime?: string;
|
||||
endTime?: string;
|
||||
}
|
||||
|
||||
// 航线任务详情(完整版)
|
||||
export interface RouteDetailVO {
|
||||
routeInfo: WaylineRouteListItemVO;
|
||||
waypoints: WaypointVO[];
|
||||
actions: WaypointActionVO[];
|
||||
totalWaypoints: number;
|
||||
totalActions: number;
|
||||
totalDistance: number;
|
||||
totalDuration: number;
|
||||
}
|
||||
|
||||
export const waylineRouteApi = {
|
||||
// 创建航线任务(关联航迹文件和设备)
|
||||
createRoute: (params: CreateRouteParams) =>
|
||||
request('/api-device/device/route/create', { method: 'POST', data: params }),
|
||||
|
||||
// 根据设备SN获取绑定的航线任务列表
|
||||
getRouteListByDevice: (deviceSn: string) =>
|
||||
request(`/api-device/device/route/listByDevice/${deviceSn}`) as Promise<{ resp_code: number; data: WaylineRouteListItemVO[] }>,
|
||||
|
||||
// 获取航线任务详情(含航点)
|
||||
getRouteDetails: (routeId: string) =>
|
||||
request(`/api-device/device/route/detail/${routeId}`) as Promise<{ resp_code: number; data: WaylineRouteDetailVO }>,
|
||||
|
||||
// 获取航点列表(3D地图绑制航线使用)
|
||||
getRouteWaypoints: (routeId: string) =>
|
||||
request(`/api-device/device/route/waypoints/${routeId}`) as Promise<{ resp_code: number; data: WaypointVO[] }>,
|
||||
|
||||
// 解析航线任务
|
||||
parseRoute: (routeId: string) =>
|
||||
request(`/api-device/device/route/parse/${routeId}`, { method: 'POST' }),
|
||||
|
||||
// 批量解析航线任务
|
||||
batchParseRoutes: (routeIds: string[]) =>
|
||||
request('/api-device/device/route/parse/batch', { method: 'POST', data: routeIds }),
|
||||
|
||||
// 获取飞行轨迹
|
||||
getFlightTrack: (
|
||||
deviceSn: string,
|
||||
params?: {
|
||||
jobId?: string;
|
||||
routeId?: string;
|
||||
startTime?: string;
|
||||
endTime?: string;
|
||||
limit?: number;
|
||||
}
|
||||
) =>
|
||||
request(`/api-device/device/drone/track/${deviceSn}`, { params }) as Promise<{ resp_code: number; data: FlightTrackData }>,
|
||||
|
||||
// 获取最新轨迹点
|
||||
getLatestTrackPoint: (deviceSn: string) =>
|
||||
request(`/api-device/device/drone/track/latest/${deviceSn}`) as Promise<{ resp_code: number; data: TrackPointVO }>,
|
||||
|
||||
// 删除历史轨迹
|
||||
deleteHistoryTracks: (deviceSn: string, beforeTime: string) =>
|
||||
request(`/api-device/device/drone/track/history/${deviceSn}`, {
|
||||
method: 'DELETE',
|
||||
params: { beforeTime },
|
||||
}),
|
||||
|
||||
// 统计轨迹点数量
|
||||
countTrackPoints: (
|
||||
deviceSn: string,
|
||||
params?: {
|
||||
jobId?: string;
|
||||
routeId?: string;
|
||||
startTime?: string;
|
||||
endTime?: string;
|
||||
}
|
||||
) =>
|
||||
request(`/api-device/device/drone/track/count/${deviceSn}`, { params }) as Promise<{ resp_code: number; data: number }>,
|
||||
|
||||
// 获取无人机设备列表
|
||||
getDroneDeviceList: () =>
|
||||
request('/api-device/device/drone/list') as Promise<{ resp_code: number; data: Array<{ sn: string; deviceName: string }> }>,
|
||||
|
||||
// 获取航迹文件列表
|
||||
getWaylineFileList: (params?: any) =>
|
||||
request('/api-device/device/wayline', { params }) as Promise<{ resp_code: number; data: Array<{ waylineId: string; name: string }> }>,
|
||||
|
||||
// 根据航迹文件ID获取航线任务列表
|
||||
getRouteListByFileWaylineId: (fileWaylineId: string) =>
|
||||
request(`/api-device/device/route/listByFileWaylineId/${fileWaylineId}`) as Promise<{ resp_code: number; data: WaylineRouteListItemVO[] }>,
|
||||
|
||||
// 获取航线任务详情(含航点和动作)
|
||||
getRouteDetail: (routeId: string) =>
|
||||
request(`/api-device/device/route/detail/${routeId}`) as Promise<{ resp_code: number; data: RouteDetailVO }>,
|
||||
|
||||
// 绑定航迹文件到设备并解析航线
|
||||
bindWaylineToDevice: (params: {
|
||||
deviceSn: string;
|
||||
waylineId: string;
|
||||
waylineName: string;
|
||||
workspaceId?: string;
|
||||
}) =>
|
||||
request('/api-device/device/route/bindWaylineToDevice', { method: 'POST', data: params }),
|
||||
};
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* Ant Design 5.x 主题配置
|
||||
* 使用 ConfigProvider 配置主题 token
|
||||
*/
|
||||
import React from 'react';
|
||||
import { ConfigProvider, theme as antdTheme } from 'antd';
|
||||
import zhCN from 'antd/es/locale/zh_CN';
|
||||
|
||||
// 深色科技主题配置
|
||||
const customTheme = {
|
||||
// 使用暗色算法
|
||||
algorithm: antdTheme.darkAlgorithm,
|
||||
token: {
|
||||
// 主色
|
||||
colorPrimary: '#00d4ff',
|
||||
// 链接色
|
||||
colorLink: '#00d4ff',
|
||||
// 成功色
|
||||
colorSuccess: '#00ff88',
|
||||
// 警告色
|
||||
colorWarning: '#ffa502',
|
||||
// 错误色
|
||||
colorError: '#ff4757',
|
||||
// 圆角
|
||||
borderRadius: 8,
|
||||
// 字体
|
||||
fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
|
||||
},
|
||||
components: {
|
||||
Button: {
|
||||
colorPrimary: '#00d4ff',
|
||||
algorithm: true,
|
||||
},
|
||||
Input: {
|
||||
colorBgContainer: 'rgba(255, 255, 255, 0.05)',
|
||||
colorBorder: 'rgba(0, 212, 255, 0.3)',
|
||||
},
|
||||
Select: {
|
||||
colorBgContainer: 'rgba(255, 255, 255, 0.05)',
|
||||
colorBorder: 'rgba(0, 212, 255, 0.3)',
|
||||
},
|
||||
Table: {
|
||||
colorBgContainer: 'transparent',
|
||||
headerBg: 'rgba(0, 212, 255, 0.1)',
|
||||
},
|
||||
Modal: {
|
||||
contentBg: 'rgba(15, 25, 40, 0.95)',
|
||||
headerBg: 'rgba(15, 25, 40, 0.95)',
|
||||
},
|
||||
Card: {
|
||||
colorBgContainer: 'rgba(15, 25, 40, 0.85)',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const ThemeProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||
return (
|
||||
<ConfigProvider theme={customTheme} locale={zhCN}>
|
||||
{children}
|
||||
</ConfigProvider>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* Ant Design 5.x 主题配置
|
||||
* 使用 ConfigProvider 配置主题 token
|
||||
*/
|
||||
import React from 'react';
|
||||
import { ConfigProvider, theme as antdTheme } from 'antd';
|
||||
import zhCN from 'antd/es/locale/zh_CN';
|
||||
|
||||
// 深色科技主题配置
|
||||
const customTheme = {
|
||||
// 使用暗色算法
|
||||
algorithm: antdTheme.darkAlgorithm,
|
||||
token: {
|
||||
// 主色
|
||||
colorPrimary: '#00d4ff',
|
||||
// 链接色
|
||||
colorLink: '#00d4ff',
|
||||
// 成功色
|
||||
colorSuccess: '#00ff88',
|
||||
// 警告色
|
||||
colorWarning: '#ffa502',
|
||||
// 错误色
|
||||
colorError: '#ff4757',
|
||||
// 背景色
|
||||
colorBgBase: '#0a0e27',
|
||||
// 文字颜色
|
||||
colorTextBase: '#ffffff',
|
||||
// 圆角
|
||||
borderRadius: 8,
|
||||
// 字体
|
||||
fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
|
||||
},
|
||||
components: {
|
||||
Button: {
|
||||
colorPrimary: '#00d4ff',
|
||||
algorithm: true,
|
||||
},
|
||||
Input: {
|
||||
colorBgContainer: 'rgba(255, 255, 255, 0.05)',
|
||||
colorBorder: 'rgba(0, 212, 255, 0.3)',
|
||||
},
|
||||
Select: {
|
||||
colorBgContainer: 'rgba(255, 255, 255, 0.05)',
|
||||
colorBorder: 'rgba(0, 212, 255, 0.3)',
|
||||
},
|
||||
Table: {
|
||||
colorBgContainer: 'transparent',
|
||||
headerBg: 'rgba(0, 212, 255, 0.1)',
|
||||
},
|
||||
Modal: {
|
||||
contentBg: 'rgba(15, 25, 40, 0.95)',
|
||||
headerBg: 'rgba(15, 25, 40, 0.95)',
|
||||
},
|
||||
Card: {
|
||||
colorBgContainer: 'rgba(15, 25, 40, 0.85)',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const ThemeProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||
return (
|
||||
<ConfigProvider theme={customTheme} locale={zhCN}>
|
||||
{children}
|
||||
</ConfigProvider>
|
||||
);
|
||||
};
|
||||
|
||||
export default ThemeProvider;
|
||||
Vendored
+113
@@ -0,0 +1,113 @@
|
||||
// 全局类型声明
|
||||
|
||||
// umi 模块声明补充
|
||||
declare module 'umi' {
|
||||
export const history: {
|
||||
push: (path: string, state?: any) => void;
|
||||
replace: (path: string, state?: any) => void;
|
||||
go: (n: number) => void;
|
||||
goBack: () => void;
|
||||
goForward: () => void;
|
||||
location: {
|
||||
pathname: string;
|
||||
search: string;
|
||||
hash: string;
|
||||
state: any;
|
||||
};
|
||||
listen: (listener: (location: any, action: string) => void) => () => void;
|
||||
};
|
||||
export function useHistory(): typeof history;
|
||||
export function request<T = any>(url: string, options?: {
|
||||
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
|
||||
params?: Record<string, any>;
|
||||
data?: any;
|
||||
headers?: Record<string, string>;
|
||||
[key: string]: any;
|
||||
}): Promise<T>;
|
||||
export const Outlet: React.FC;
|
||||
export function useLocation(): { pathname: string; search: string; hash: string; state: any };
|
||||
export function useParams<T = any>(): T;
|
||||
}
|
||||
|
||||
// CSS模块声明
|
||||
declare module '*.css' {
|
||||
const content: any;
|
||||
export default content;
|
||||
}
|
||||
|
||||
declare module '*.less' {
|
||||
const content: any;
|
||||
export default content;
|
||||
}
|
||||
|
||||
// 图片资源声明
|
||||
declare module '*.png' {
|
||||
const content: string;
|
||||
export default content;
|
||||
}
|
||||
|
||||
declare module '*.jpg' {
|
||||
const content: string;
|
||||
export default content;
|
||||
}
|
||||
|
||||
declare module '*.jpeg' {
|
||||
const content: string;
|
||||
export default content;
|
||||
}
|
||||
|
||||
declare module '*.gif' {
|
||||
const content: string;
|
||||
export default content;
|
||||
}
|
||||
|
||||
declare module '*.svg' {
|
||||
const content: string;
|
||||
export default content;
|
||||
}
|
||||
|
||||
declare module '*.webp' {
|
||||
const content: string;
|
||||
export default content;
|
||||
}
|
||||
|
||||
// Cesium相关声明
|
||||
declare module 'cesium' {
|
||||
const content: any;
|
||||
export = content;
|
||||
}
|
||||
|
||||
declare module 'cesium/Build/Cesium/Widgets/widgets.css';
|
||||
|
||||
// 扩展Window类型
|
||||
interface Window {
|
||||
AMap: any;
|
||||
}
|
||||
|
||||
// API 相关类型
|
||||
declare namespace API {
|
||||
// 通用响应结构(兼容两种格式)
|
||||
interface Result<T = any> {
|
||||
resp_code?: number;
|
||||
resp_msg?: string;
|
||||
code?: number;
|
||||
msg?: string;
|
||||
success?: boolean;
|
||||
data?: T;
|
||||
datas?: T;
|
||||
}
|
||||
|
||||
// 分页响应结构(兼容两种格式)
|
||||
interface PageResult<T = any> {
|
||||
resp_code?: number;
|
||||
resp_msg?: string;
|
||||
code?: number;
|
||||
msg?: string;
|
||||
success?: boolean;
|
||||
data?: T[];
|
||||
datas?: T[];
|
||||
count?: number;
|
||||
total?: number;
|
||||
totalCount?: number;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import * as JSEncryptLib from 'jsencrypt';
|
||||
|
||||
// 确定正确的JSEncrypt构造函数
|
||||
const JSEncrypt = JSEncryptLib.JSEncrypt || JSEncryptLib.default || JSEncryptLib;
|
||||
|
||||
/**
|
||||
* RSA加密工具类 - 与后端RSAUtil对应
|
||||
*/
|
||||
export class RSAUtil {
|
||||
private static readonly PUBLIC_KEY_RAW =
|
||||
'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCGu7lYGfEtMICO8kREJrObu0Hy' +
|
||||
'pF7R9iEIefyxApmB6wJ/y3Rg/eBO6kLDCo18hYZ3ZNxKp5CMymZvXDh5j+sd7IHm' +
|
||||
'tUh6sEZzpXExQJIzT8gA1SULd+iXe4V9zt2AcbROIi94vA6lOfmtON28Ex+uAlLK' +
|
||||
'N/iJDXFFXdEOmfdqhwIDAQAB';
|
||||
|
||||
private static readonly PUBLIC_KEY =
|
||||
'-----BEGIN PUBLIC KEY-----\n' +
|
||||
RSAUtil.PUBLIC_KEY_RAW +
|
||||
'\n-----END PUBLIC KEY-----';
|
||||
|
||||
private static getJSEncryptInstance(): any {
|
||||
try {
|
||||
const jsEncrypt: any = new JSEncrypt();
|
||||
jsEncrypt.setPublicKey(this.PUBLIC_KEY);
|
||||
if (!jsEncrypt.getPublicKey()) {
|
||||
jsEncrypt.setPublicKey(this.PUBLIC_KEY_RAW);
|
||||
}
|
||||
if (!jsEncrypt.getPublicKey()) {
|
||||
throw new Error('公钥设置失败');
|
||||
}
|
||||
return jsEncrypt;
|
||||
} catch (error) {
|
||||
console.error('JSEncrypt实例创建失败:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public static encrypt(data: string): string | null {
|
||||
try {
|
||||
const jsEncryptInstance = this.getJSEncryptInstance();
|
||||
const encrypted = jsEncryptInstance.encrypt(data);
|
||||
if (!encrypted) {
|
||||
return null;
|
||||
}
|
||||
return encrypted.replace(/\//g, '%2F');
|
||||
} catch (error) {
|
||||
console.error('RSA加密异常:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static encryptPassword(password: string): string | null {
|
||||
if (!password || password.trim() === '') {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
if (typeof JSEncrypt !== 'function') {
|
||||
return null;
|
||||
}
|
||||
const crypt = new JSEncrypt();
|
||||
crypt.setPublicKey(RSAUtil.PUBLIC_KEY_RAW);
|
||||
const encrypted = crypt.encrypt(password);
|
||||
if (encrypted) {
|
||||
return encrypted.replace(/\//g, '%2F');
|
||||
}
|
||||
return null;
|
||||
} catch (error) {
|
||||
console.error('RSA加密失败:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default RSAUtil;
|
||||
export const encryptPassword = RSAUtil.encryptPassword;
|
||||
export const encryptData = RSAUtil.encrypt;
|
||||
@@ -0,0 +1,85 @@
|
||||
// 租户数据缓存工具:会话级缓存(sessionStorage),按 token 隔离
|
||||
|
||||
type AnyNode = { tenantId?: string; tenantName?: string; status?: number | boolean; children?: AnyNode[] };
|
||||
|
||||
const KEY_META = 'tenant_cache_meta';
|
||||
const KEY_TREE = 'tenant_cache_tree';
|
||||
const KEY_CHILDREN = 'tenant_cache_children';
|
||||
const KEY_DETAIL = 'tenant_cache_detail';
|
||||
|
||||
const safeParse = <T = any>(s?: string | null): T | undefined => {
|
||||
if (!s) return undefined as any;
|
||||
try { return JSON.parse(s) as T; } catch { return undefined as any; }
|
||||
};
|
||||
|
||||
const getToken = () => {
|
||||
try { return sessionStorage.getItem('access_token') || undefined; } catch { return undefined; }
|
||||
};
|
||||
|
||||
export const ensureTenantCacheTokenGuard = () => {
|
||||
try {
|
||||
const meta = safeParse<{ token?: string }>(sessionStorage.getItem(KEY_META));
|
||||
const cur = getToken();
|
||||
if (!meta?.token || !cur || meta.token !== cur) {
|
||||
clearTenantCache();
|
||||
if (cur) sessionStorage.setItem(KEY_META, JSON.stringify({ token: cur }));
|
||||
}
|
||||
} catch {}
|
||||
};
|
||||
|
||||
export const setTenantTreeCache = (tree: AnyNode[]) => {
|
||||
try {
|
||||
ensureTenantCacheTokenGuard();
|
||||
sessionStorage.setItem(KEY_TREE, JSON.stringify(tree || []));
|
||||
} catch {}
|
||||
};
|
||||
|
||||
export const getTenantTreeCache = (): AnyNode[] | undefined => {
|
||||
try {
|
||||
ensureTenantCacheTokenGuard();
|
||||
return safeParse<AnyNode[]>(sessionStorage.getItem(KEY_TREE));
|
||||
} catch { return undefined; }
|
||||
};
|
||||
|
||||
export const setTenantChildrenCache = (parentId: string, children: AnyNode[] | undefined) => {
|
||||
try {
|
||||
ensureTenantCacheTokenGuard();
|
||||
const map = safeParse<Record<string, AnyNode[]>>(sessionStorage.getItem(KEY_CHILDREN)) || {};
|
||||
if (parentId) map[parentId] = children || [];
|
||||
sessionStorage.setItem(KEY_CHILDREN, JSON.stringify(map));
|
||||
} catch {}
|
||||
};
|
||||
|
||||
export const getTenantChildrenCache = (parentId: string): AnyNode[] | undefined => {
|
||||
try {
|
||||
ensureTenantCacheTokenGuard();
|
||||
const map = safeParse<Record<string, AnyNode[]>>(sessionStorage.getItem(KEY_CHILDREN)) || {};
|
||||
return parentId ? (map[parentId] || undefined) : undefined;
|
||||
} catch { return undefined; }
|
||||
};
|
||||
|
||||
export const setTenantDetailCache = (tenantId: string, detail: AnyNode | undefined) => {
|
||||
try {
|
||||
ensureTenantCacheTokenGuard();
|
||||
const map = safeParse<Record<string, AnyNode>>(sessionStorage.getItem(KEY_DETAIL)) || {};
|
||||
if (tenantId) map[tenantId] = detail || {};
|
||||
sessionStorage.setItem(KEY_DETAIL, JSON.stringify(map));
|
||||
} catch {}
|
||||
};
|
||||
|
||||
export const getTenantDetailCache = (tenantId: string): AnyNode | undefined => {
|
||||
try {
|
||||
ensureTenantCacheTokenGuard();
|
||||
const map = safeParse<Record<string, AnyNode>>(sessionStorage.getItem(KEY_DETAIL)) || {};
|
||||
return tenantId ? (map[tenantId] || undefined) : undefined;
|
||||
} catch { return undefined; }
|
||||
};
|
||||
|
||||
export const clearTenantCache = () => {
|
||||
try {
|
||||
sessionStorage.removeItem(KEY_TREE);
|
||||
sessionStorage.removeItem(KEY_CHILDREN);
|
||||
sessionStorage.removeItem(KEY_DETAIL);
|
||||
sessionStorage.removeItem(KEY_META);
|
||||
} catch {}
|
||||
};
|
||||
Reference in New Issue
Block a user