Files
gofly-platform-services/zlt-web/react-web-next/src/pages/orders/WeatherRule/index.tsx
T

558 lines
17 KiB
TypeScript

import React, { useRef, useState, useEffect } from 'react';
import { PageContainer, ProTable, type ActionType, ProCard } from '@ant-design/pro-components';
import {
Button,
Space,
Tag,
message,
Badge,
Tooltip,
Row,
Col,
Statistic,
Switch,
Typography,
Dropdown,
Modal,
} from 'antd';
import {
ThunderboltOutlined,
CloudOutlined,
SafetyCertificateOutlined,
SettingOutlined,
CopyOutlined,
EyeOutlined,
DeleteOutlined,
MoreOutlined,
} from '@ant-design/icons';
import { ordersApi } from '@/services/orders';
import WeatherRuleForm, { WeatherRuleItem } from './components/WeatherRuleForm';
import WeatherRuleDetailModal from './components/WeatherRuleDetailModal';
const { Text } = Typography;
// 天气参数配置(与 WeatherBlockSettingModal 保持一致)
const WEATHER_PARAMETERS: Record<string, { label: string; unit: string; icon: string }> = {
windSpeed: { label: '风速', unit: 'm/s', icon: '💨' },
temperature: { label: '温度', unit: '°C', icon: '🌡️' },
humidity: { label: '湿度', unit: '%', icon: '💧' },
precipitation: { label: '降雨量', unit: 'mm/h', icon: '🌧️' },
visibility: { label: '能见度', unit: 'm', icon: '👁️' },
};
interface RuleCondition {
parameter?: string;
operator?: string;
value?: number;
minValue?: number;
maxValue?: number;
unit?: string;
}
interface ConditionGroup {
groupName?: string;
conditions: RuleCondition[];
logicalOperator: string;
}
/**
* 天气规则管理页面
* 支持景区级别、设备级别的天气规则配置
* 优先级:设备级别 > 景区级别
*/
const WeatherRulePage: React.FC = () => {
const [createOpen, setCreateOpen] = useState(false);
const [detailOpen, setDetailOpen] = useState(false);
const [current, setCurrent] = useState<WeatherRuleItem | undefined>(undefined);
const [statistics, setStatistics] = useState({
total: 0,
enabled: 0,
scenicLevel: 0,
deviceLevel: 0,
});
const actionRef = useRef<ActionType>();
// 规则级别配置
const ruleLevelConfig = {
2: { text: '景区级别', color: '#52c41a', icon: <CloudOutlined /> },
3: { text: '设备级别', color: '#f5222d', icon: <ThunderboltOutlined /> },
};
// 加载统计数据
const loadStatistics = async () => {
try {
const response = await ordersApi.getWeatherRuleList({ current: 1, size: 1000 });
const list = response.data || [];
setStatistics({
total: list.length,
enabled: list.filter((item: WeatherRuleItem) => item.status === 1).length,
scenicLevel: list.filter((item: WeatherRuleItem) => item.ruleLevel === 2).length,
deviceLevel: list.filter((item: WeatherRuleItem) => item.ruleLevel === 3).length,
});
} catch (error) {
console.error('加载统计数据失败', error);
}
};
useEffect(() => {
loadStatistics();
}, []);
// 快速切换状态
const handleStatusChange = async (record: WeatherRuleItem, checked: boolean) => {
const hide = message.loading('正在更新...');
try {
await ordersApi.updateWeatherRuleStatus(record.id!, checked ? 1 : 0);
message.success('状态更新成功');
actionRef.current?.reload();
loadStatistics();
} catch {
message.error('状态更新失败');
} finally {
hide();
}
};
// 删除规则
const handleDelete = async (record: WeatherRuleItem) => {
Modal.confirm({
title: '确认删除',
content: `确定要删除规则「${record.ruleName}」吗?`,
okText: '确定',
cancelText: '取消',
okButtonProps: { danger: true },
onOk: async () => {
const hide = message.loading('正在删除...');
try {
await ordersApi.deleteWeatherRule(record.id!);
message.success('删除成功');
actionRef.current?.reload();
loadStatistics();
} catch {
message.error('删除失败');
} finally {
hide();
}
},
});
};
// 复制规则
const handleCopyRule = (record: WeatherRuleItem) => {
const newRule = {
...record,
id: undefined,
ruleCode: `${record.ruleCode}_copy`,
ruleName: `${record.ruleName}(副本)`,
};
setCurrent(newRule);
setCreateOpen(true);
};
// 生成规则描述(支持分组模式)
const generateRuleDescription = (ruleContent: any): string => {
if (!ruleContent) return '';
// 分组模式
if (ruleContent.conditionGroups?.length) {
const groupDescs = ruleContent.conditionGroups.map((g: ConditionGroup) => {
if (!g.conditions?.length) return '';
const condDescs = g.conditions.map((c: RuleCondition) => {
const param = WEATHER_PARAMETERS[c.parameter || ''];
const label = param?.label || c.parameter;
if (c.operator === 'between') {
return `${label} ${c.minValue}-${c.maxValue}${c.unit || ''}`;
}
return `${label}${c.operator}${c.value}${c.unit || ''}`;
});
return g.conditions.length > 1 ? `(${condDescs.join(` ${g.logicalOperator} `)})` : condDescs[0];
}).filter(Boolean);
return groupDescs.join(` ${ruleContent.groupOperator || 'OR'} `);
}
// 简单模式(向后兼容)
if (ruleContent.conditions?.length) {
const condDescs = ruleContent.conditions.map((c: RuleCondition) => {
const param = WEATHER_PARAMETERS[c.parameter || ''];
const label = param?.label || c.parameter;
if (c.operator === 'between') {
return `${label} ${c.minValue}-${c.maxValue}${c.unit || ''}`;
}
return `${label}${c.operator}${c.value}${c.unit || ''}`;
});
return condDescs.join(` ${ruleContent.logicalOperator || 'AND'} `);
}
return '';
};
// 渲染条件预览(支持分组模式)
const renderConditionsPreview = (record: WeatherRuleItem) => {
const ruleContent = record.ruleContent;
if (!ruleContent) return <Text type="secondary">暂无条件</Text>;
// 分组模式
if (ruleContent.conditionGroups?.length) {
const groupOperator = ruleContent.groupOperator || 'OR';
return (
<Space direction="vertical" size={4} style={{ width: '100%' }}>
{ruleContent.conditionGroups.map((group: ConditionGroup, gIndex: number) => (
<div key={gIndex}>
{gIndex > 0 && (
<Tag color={groupOperator === 'OR' ? 'orange' : 'blue'} style={{ marginBottom: 4 }}>
{groupOperator}
</Tag>
)}
<Space size={4} wrap>
{group.groupName && (
<Text type="secondary" style={{ fontSize: 12 }}>[{group.groupName}]</Text>
)}
{group.conditions?.map((cond: RuleCondition, cIndex: number) => {
const param = WEATHER_PARAMETERS[cond.parameter || ''];
return (
<React.Fragment key={cIndex}>
{cIndex > 0 && (
<Text type="secondary" style={{ fontSize: 11 }}>{group.logicalOperator}</Text>
)}
<Tag color="blue" style={{ margin: 0 }}>
{param?.icon} {param?.label || cond.parameter} {cond.operator}{' '}
{cond.operator === 'between'
? `${cond.minValue}-${cond.maxValue}`
: cond.value}
{cond.unit}
</Tag>
</React.Fragment>
);
})}
</Space>
</div>
))}
</Space>
);
}
// 简单模式(向后兼容)
const conditions = ruleContent.conditions || [];
if (conditions.length === 0) return <Text type="secondary">暂无条件</Text>;
const operator = ruleContent.logicalOperator || 'AND';
return (
<Space size={4} wrap>
{conditions.map((cond: RuleCondition, index: number) => {
const param = WEATHER_PARAMETERS[cond.parameter || ''];
return (
<React.Fragment key={index}>
{index > 0 && <Text type="secondary" style={{ fontSize: 11 }}>{operator}</Text>}
<Tag color="blue" style={{ margin: 0 }}>
{param?.icon} {param?.label || cond.parameter} {cond.operator}{' '}
{cond.operator === 'between'
? `${cond.minValue}-${cond.maxValue}`
: cond.value}
{cond.unit}
</Tag>
</React.Fragment>
);
})}
</Space>
);
};
const columns: any[] = [
{
title: '规则信息',
dataIndex: 'ruleName',
width: 280,
render: (_: any, record: WeatherRuleItem) => (
<Space direction="vertical" size={0}>
<Space>
<Text strong style={{ fontSize: 14 }}>{record.ruleName}</Text>
{record.status === 1 && <Badge status="success" />}
</Space>
<Text type="secondary" copyable={{ text: record.ruleCode }} style={{ fontSize: 12 }}>
{record.ruleCode}
</Text>
</Space>
),
},
{
title: '规则级别',
dataIndex: 'ruleLevel',
width: 130,
render: (_: any, record: WeatherRuleItem) => {
const level = record.ruleLevel;
const config = ruleLevelConfig[level as keyof typeof ruleLevelConfig];
return config ? (
<Tag
icon={config.icon}
color={config.color}
style={{ borderRadius: 12, padding: '2px 10px' }}
>
{config.text}
</Tag>
) : (
<Tag>{level || '未知'}</Tag>
);
},
filters: [
{ text: '景区级别', value: 2 },
{ text: '设备级别', value: 3 },
],
valueEnum: {
2: { text: '景区级别' },
3: { text: '设备级别' },
},
},
{
title: '目标ID',
dataIndex: 'targetId',
width: 160,
ellipsis: true,
copyable: true,
render: (text: string, record: WeatherRuleItem) => (
<Tooltip title={`${record.ruleLevel === 2 ? '景区' : '设备'}: ${text}`}>
<Text code style={{ fontSize: 12 }}>{text}</Text>
</Tooltip>
),
},
{
title: '规则条件',
dataIndex: 'ruleContent',
width: 350,
search: false,
render: (_: any, record: WeatherRuleItem) => renderConditionsPreview(record),
},
{
title: '优先级',
dataIndex: 'priority',
width: 90,
sorter: true,
search: false,
render: (priority: number) => (
<Tag color={priority >= 100 ? 'orange' : 'default'} style={{ minWidth: 50, textAlign: 'center' }}>
{priority}
</Tag>
),
},
{
title: '状态',
dataIndex: 'status',
width: 100,
render: (_: any, record: WeatherRuleItem) => {
const isEnabled = record.status === 1;
return (
<Switch
checked={isEnabled}
checkedChildren="启用"
unCheckedChildren="禁用"
onChange={(checked) => handleStatusChange(record, checked)}
/>
);
},
filters: [
{ text: '启用', value: 1 },
{ text: '禁用', value: 0 },
],
valueEnum: {
0: { text: '禁用', status: 'Default' },
1: { text: '启用', status: 'Success' },
},
},
{
title: '更新时间',
dataIndex: 'updateTime',
valueType: 'dateTime',
width: 160,
sorter: true,
search: false,
},
{
title: '操作',
key: 'action',
width: 120,
fixed: 'right',
search: false,
render: (_: any, record: WeatherRuleItem) => (
<Space size={0} split={<span style={{ color: '#d9d9d9', margin: '0 4px' }}>|</span>}>
<Tooltip title="查看详情">
<Button
type="link"
size="small"
icon={<EyeOutlined />}
onClick={() => {
setCurrent(record);
setDetailOpen(true);
}}
/>
</Tooltip>
<Dropdown
menu={{
items: [
{
key: 'copy',
icon: <CopyOutlined />,
label: '复制规则',
onClick: () => handleCopyRule(record),
},
{
type: 'divider',
},
{
key: 'delete',
icon: <DeleteOutlined />,
label: '删除',
danger: true,
onClick: () => handleDelete(record),
},
],
}}
>
<Button type="link" size="small" icon={<MoreOutlined />} />
</Dropdown>
</Space>
),
},
];
return (
<PageContainer
header={{
title: (
<Space>
<CloudOutlined style={{ fontSize: 24, color: '#1890ff' }} />
<span>天气规则管理</span>
</Space>
),
subTitle: '配置无人机飞行天气限制规则,保障飞行安全',
}}
>
{/* 统计卡片 */}
<Row gutter={16} style={{ marginBottom: 16 }}>
<Col span={6}>
<ProCard hoverable style={{ borderRadius: 8 }}>
<Statistic
title={<Text type="secondary">规则总数</Text>}
value={statistics.total}
prefix={<SettingOutlined style={{ color: '#1890ff' }} />}
valueStyle={{ color: '#1890ff' }}
/>
</ProCard>
</Col>
<Col span={6}>
<ProCard hoverable style={{ borderRadius: 8 }}>
<Statistic
title={<Text type="secondary">已启用</Text>}
value={statistics.enabled}
prefix={<SafetyCertificateOutlined style={{ color: '#52c41a' }} />}
valueStyle={{ color: '#52c41a' }}
suffix={<Text type="secondary" style={{ fontSize: 14 }}>/ {statistics.total}</Text>}
/>
</ProCard>
</Col>
<Col span={6}>
<ProCard hoverable style={{ borderRadius: 8 }}>
<Statistic
title={<Text type="secondary">景区级别</Text>}
value={statistics.scenicLevel}
prefix={<CloudOutlined style={{ color: '#52c41a' }} />}
valueStyle={{ color: '#52c41a', fontSize: 20 }}
/>
</ProCard>
</Col>
<Col span={6}>
<ProCard hoverable style={{ borderRadius: 8 }}>
<Statistic
title={<Text type="secondary">设备级别</Text>}
value={statistics.deviceLevel}
prefix={<ThunderboltOutlined style={{ color: '#f5222d' }} />}
valueStyle={{ color: '#f5222d', fontSize: 20 }}
/>
</ProCard>
</Col>
</Row>
{/* 规则列表 */}
<ProCard style={{ borderRadius: 8 }}>
<ProTable
actionRef={actionRef}
rowKey="id"
columns={columns}
request={async (params, sort) => {
try {
const response = await ordersApi.getWeatherRuleList({
...params,
current: params.current,
size: params.pageSize,
...sort,
});
// 刷新统计
loadStatistics();
return {
data: response.data || [],
success: true,
total: response.total || 0,
};
} catch (error) {
message.error('查询失败');
return { data: [], success: false, total: 0 };
}
}}
search={{
labelWidth: 'auto',
defaultCollapsed: false,
span: 6,
}}
pagination={{
defaultPageSize: 10,
showSizeChanger: true,
showQuickJumper: true,
showTotal: (total) => `共 ${total} 条规则`,
}}
scroll={{ x: 1400 }}
options={{
density: true,
fullScreen: true,
reload: true,
setting: true,
}}
toolBarRender={false}
tableAlertRender={false}
rowClassName={(record) => record.status === 0 ? 'disabled-row' : ''}
/>
</ProCard>
{/* 创建规则弹窗 */}
<WeatherRuleForm
visible={createOpen}
onVisibleChange={setCreateOpen}
initialValues={current}
onSuccess={() => {
setCreateOpen(false);
setCurrent(undefined);
actionRef.current?.reload();
loadStatistics();
}}
/>
{/* 规则详情弹窗 */}
<WeatherRuleDetailModal
visible={detailOpen}
onVisibleChange={setDetailOpen}
data={current}
/>
<style>{`
.disabled-row {
opacity: 0.6;
background-color: #fafafa;
}
.ant-pro-card:hover {
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.09);
transition: box-shadow 0.3s;
}
`}</style>
</PageContainer>
);
};
export default WeatherRulePage;