feat: 天气系统规则引擎

This commit is contained in:
2026-01-28 17:30:34 +08:00
parent d1e340af83
commit ad41a38620
69 changed files with 10282 additions and 33 deletions
@@ -0,0 +1,666 @@
import React, { useEffect, useState } from 'react';
import {
Modal,
Switch,
Space,
Typography,
Alert,
Divider,
Button,
Card,
Row,
Col,
Tag,
message,
Spin,
Empty,
InputNumber,
Select,
Input,
} from 'antd';
import {
CloudOutlined,
ThunderboltOutlined,
SafetyCertificateOutlined,
PlusOutlined,
DeleteOutlined,
InfoCircleOutlined,
CheckCircleOutlined,
CloseCircleOutlined,
} from '@ant-design/icons';
import { ordersApi } from '@/services/orders';
import { deviceApi } from '@/services/device';
const { Text } = Typography;
// 天气参数配置
const WEATHER_PARAMETERS = [
{ key: 'windSpeed', label: '风速', unit: 'm/s', icon: '💨', defaultValue: 10 },
{ key: 'temperature', label: '温度', unit: '°C', icon: '🌡️', defaultValue: -4 },
{ key: 'humidity', label: '湿度', unit: '%', icon: '💧', defaultValue: 80 },
{ key: 'precipitation', label: '降雨量', unit: 'mm/h', icon: '🌧️', defaultValue: 0.5 },
{ key: 'visibility', label: '能见度', unit: 'm', icon: '👁️', defaultValue: 1000 },
];
// 运算符配置
const OPERATORS = [
{ value: '>', label: '> 大于' },
{ value: '>=', label: '>= 大于等于' },
{ value: '<', label: '< 小于' },
{ value: '<=', label: '<= 小于等于' },
{ value: 'between', label: '区间' },
];
interface RuleCondition {
parameter?: string;
operator?: string;
value?: number;
minValue?: number;
maxValue?: number;
unit?: string;
description?: string;
}
interface ConditionGroup {
groupName?: string;
conditions: RuleCondition[];
logicalOperator: string; // 组内逻辑,默认AND
}
interface WeatherRuleItem {
id?: number;
ruleCode?: string;
ruleName?: string;
ruleLevel?: number;
targetId?: string;
priority?: number;
ruleContent?: {
conditions?: RuleCondition[];
conditionGroups?: ConditionGroup[];
groupOperator?: string;
logicalOperator?: string;
};
status?: number;
}
interface WeatherBlockSettingModalProps {
visible: boolean;
onVisibleChange: (visible: boolean) => void;
type: 'tourism' | 'device';
targetId: string | number;
targetName?: string;
weatherBlockEnabled?: number;
onSuccess?: () => void;
}
// 预设模板(使用分组模式)
const RULE_TEMPLATES = [
{
name: '结冰风险规则',
description: '风速>10 或 (温度<-4 且 湿度>80)',
conditionGroups: [
{
groupName: '大风阻飞',
conditions: [{ parameter: 'windSpeed', operator: '>', value: 10, unit: 'm/s' }],
logicalOperator: 'AND',
},
{
groupName: '结冰风险',
conditions: [
{ parameter: 'temperature', operator: '<', value: -4, unit: '°C' },
{ parameter: 'humidity', operator: '>', value: 80, unit: '%' },
],
logicalOperator: 'AND',
},
],
groupOperator: 'OR',
},
{
name: '标准阻飞规则',
description: '风速>10 或 降雨>0.5',
conditionGroups: [
{
groupName: '大风阻飞',
conditions: [{ parameter: 'windSpeed', operator: '>', value: 10, unit: 'm/s' }],
logicalOperator: 'AND',
},
{
groupName: '降雨阻飞',
conditions: [{ parameter: 'precipitation', operator: '>', value: 0.5, unit: 'mm/h' }],
logicalOperator: 'AND',
},
],
groupOperator: 'OR',
},
{
name: '严格阻飞规则',
description: '风速>8 或 降雨>0 或 能见度<1000',
conditionGroups: [
{
groupName: '大风',
conditions: [{ parameter: 'windSpeed', operator: '>', value: 8, unit: 'm/s' }],
logicalOperator: 'AND',
},
{
groupName: '降雨',
conditions: [{ parameter: 'precipitation', operator: '>', value: 0, unit: 'mm/h' }],
logicalOperator: 'AND',
},
{
groupName: '低能见度',
conditions: [{ parameter: 'visibility', operator: '<', value: 1000, unit: 'm' }],
logicalOperator: 'AND',
},
],
groupOperator: 'OR',
},
];
const WeatherBlockSettingModal: React.FC<WeatherBlockSettingModalProps> = ({
visible,
onVisibleChange,
type,
targetId,
targetName,
weatherBlockEnabled = 0,
onSuccess,
}) => {
const [loading, setLoading] = useState(false);
const [saving, setSaving] = useState(false);
const [enabled, setEnabled] = useState(weatherBlockEnabled === 1);
const [existingRule, setExistingRule] = useState<WeatherRuleItem | null>(null);
const [showRuleForm, setShowRuleForm] = useState(false);
const [conditionGroups, setConditionGroups] = useState<ConditionGroup[]>([]);
const [groupOperator, setGroupOperator] = useState<string>('OR');
const [ruleName, setRuleName] = useState('');
useEffect(() => {
if (visible && targetId) {
loadExistingRule();
setEnabled(weatherBlockEnabled === 1);
}
}, [visible, targetId, weatherBlockEnabled]);
const loadExistingRule = async () => {
setLoading(true);
try {
let rule = null;
if (type === 'tourism') {
rule = await ordersApi.getTourismWeatherRule(Number(targetId));
} else {
rule = await ordersApi.getDeviceWeatherRule(String(targetId));
}
setExistingRule(rule);
if (rule?.ruleContent) {
// 优先使用分组模式
if (rule.ruleContent.conditionGroups?.length) {
setConditionGroups(rule.ruleContent.conditionGroups);
setGroupOperator(rule.ruleContent.groupOperator || 'OR');
} else if (rule.ruleContent.conditions?.length) {
// 兼容旧的简单模式,转换为单组
setConditionGroups([{
groupName: '条件组1',
conditions: rule.ruleContent.conditions,
logicalOperator: rule.ruleContent.logicalOperator || 'AND',
}]);
setGroupOperator('OR');
}
setRuleName(rule.ruleName || '');
}
} catch (error) {
console.error('加载规则失败', error);
} finally {
setLoading(false);
}
};
const handleToggle = (checked: boolean) => {
setEnabled(checked);
if (checked && !existingRule) {
setShowRuleForm(true);
}
};
const applyTemplate = (template: typeof RULE_TEMPLATES[0]) => {
setConditionGroups(template.conditionGroups);
setGroupOperator(template.groupOperator);
setRuleName(template.name);
message.success(`已应用「${template.name}」模板`);
};
// 添加条件组
const addConditionGroup = () => {
setConditionGroups([
...conditionGroups,
{
groupName: `条件组${conditionGroups.length + 1}`,
conditions: [],
logicalOperator: 'AND',
},
]);
};
// 删除条件组
const removeConditionGroup = (groupIndex: number) => {
setConditionGroups(conditionGroups.filter((_, i) => i !== groupIndex));
};
// 更新条件组名称
const updateGroupName = (groupIndex: number, name: string) => {
const newGroups = [...conditionGroups];
newGroups[groupIndex].groupName = name;
setConditionGroups(newGroups);
};
// 更新组内逻辑
const updateGroupLogicalOperator = (groupIndex: number, operator: string) => {
const newGroups = [...conditionGroups];
newGroups[groupIndex].logicalOperator = operator;
setConditionGroups(newGroups);
};
// 添加条件到组
const addConditionToGroup = (groupIndex: number, paramKey?: string) => {
const param = WEATHER_PARAMETERS.find(p => p.key === paramKey);
const newCondition: RuleCondition = {
parameter: paramKey || '',
operator: '>',
value: param?.defaultValue,
unit: param?.unit || '',
};
const newGroups = [...conditionGroups];
newGroups[groupIndex].conditions.push(newCondition);
setConditionGroups(newGroups);
};
// 更新条件
const updateCondition = (groupIndex: number, condIndex: number, field: string, value: any) => {
const newGroups = [...conditionGroups];
newGroups[groupIndex].conditions[condIndex] = {
...newGroups[groupIndex].conditions[condIndex],
[field]: value,
};
if (field === 'parameter') {
const param = WEATHER_PARAMETERS.find(p => p.key === value);
if (param) {
newGroups[groupIndex].conditions[condIndex].unit = param.unit;
newGroups[groupIndex].conditions[condIndex].value = param.defaultValue;
}
}
setConditionGroups(newGroups);
};
// 删除条件
const removeCondition = (groupIndex: number, condIndex: number) => {
const newGroups = [...conditionGroups];
newGroups[groupIndex].conditions = newGroups[groupIndex].conditions.filter((_, i) => i !== condIndex);
setConditionGroups(newGroups);
};
const handleSave = async () => {
setSaving(true);
try {
// 1. 更新开关状态
if (type === 'tourism') {
await ordersApi.updateTourismWeatherBlock(Number(targetId), enabled ? 1 : 0);
} else {
await deviceApi.updateDeviceWeatherBlock(String(targetId), enabled ? 1 : 0);
}
// 2. 检查是否有有效条件
const hasValidConditions = conditionGroups.some(g => g.conditions.length > 0);
if (enabled && hasValidConditions) {
const ruleCode = type === 'tourism'
? `TOURISM_${targetId}_RULE`
: `DEVICE_${targetId}_RULE`;
const rulePayload = {
ruleCode: existingRule?.ruleCode || ruleCode,
ruleName: ruleName || `${targetName || targetId}天气规则`,
ruleLevel: type === 'tourism' ? 2 : 3,
targetId: String(targetId),
priority: 100,
status: 1,
ruleContent: {
conditionGroups,
groupOperator,
},
};
console.log('保存规则:', rulePayload);
let result;
if (existingRule?.id) {
result = await ordersApi.updateWeatherRule(existingRule.id, rulePayload);
} else {
result = await ordersApi.createWeatherRule(rulePayload);
}
console.log('规则保存结果:', result);
// 检查返回结果
if (result && (result as any).resp_code !== 0 && (result as any).code !== 0) {
throw new Error((result as any).resp_msg || (result as any).msg || '规则保存失败');
}
} else if (enabled && !hasValidConditions) {
message.warning('请至少配置一个条件');
setSaving(false);
return;
}
message.success('保存成功');
onSuccess?.();
onVisibleChange(false);
} catch (error: any) {
console.error('保存失败:', error);
message.error(error?.message || '保存失败');
} finally {
setSaving(false);
}
};
// 渲染条件行
const renderConditionRow = (condition: RuleCondition, groupIndex: number, condIndex: number) => (
<Row key={condIndex} gutter={8} align="middle" style={{ marginBottom: 8 }}>
<Col span={7}>
<Select
value={condition.parameter}
onChange={(v) => updateCondition(groupIndex, condIndex, 'parameter', v)}
placeholder="参数"
size="small"
style={{ width: '100%' }}
>
{WEATHER_PARAMETERS.map(p => (
<Select.Option key={p.key} value={p.key}>
{p.icon} {p.label}
</Select.Option>
))}
</Select>
</Col>
<Col span={6}>
<Select
value={condition.operator}
onChange={(v) => updateCondition(groupIndex, condIndex, 'operator', v)}
size="small"
style={{ width: '100%' }}
>
{OPERATORS.map(op => (
<Select.Option key={op.value} value={op.value}>
{op.label}
</Select.Option>
))}
</Select>
</Col>
<Col span={7}>
{condition.operator === 'between' ? (
<Space size={4}>
<InputNumber
value={condition.minValue}
onChange={(v) => updateCondition(groupIndex, condIndex, 'minValue', v)}
size="small"
style={{ width: 60 }}
/>
<span>~</span>
<InputNumber
value={condition.maxValue}
onChange={(v) => updateCondition(groupIndex, condIndex, 'maxValue', v)}
size="small"
style={{ width: 60 }}
/>
</Space>
) : (
<InputNumber
value={condition.value}
onChange={(v) => updateCondition(groupIndex, condIndex, 'value', v)}
size="small"
style={{ width: '100%' }}
addonAfter={<span style={{ fontSize: 11 }}>{condition.unit}</span>}
/>
)}
</Col>
<Col span={4}>
<Button
type="text"
danger
size="small"
icon={<DeleteOutlined />}
onClick={() => removeCondition(groupIndex, condIndex)}
/>
</Col>
</Row>
);
// 渲染条件组
const renderConditionGroup = (group: ConditionGroup, groupIndex: number) => {
// 获取当前组已使用的参数
const usedParams = group.conditions.map(c => c.parameter).filter(Boolean);
return (
<Card
key={groupIndex}
size="small"
style={{ marginBottom: 12, borderColor: '#1890ff', borderStyle: 'dashed' }}
title={
<Row align="middle" justify="space-between">
<Col>
<Space>
<Input
value={group.groupName}
onChange={(e) => updateGroupName(groupIndex, e.target.value)}
size="small"
style={{ width: 120 }}
placeholder="组名称"
/>
{group.conditions.length > 1 && (
<Select
value={group.logicalOperator}
onChange={(v) => updateGroupLogicalOperator(groupIndex, v)}
size="small"
style={{ width: 90 }}
>
<Select.Option value="AND">
<Tag color="blue">AND</Tag>
</Select.Option>
<Select.Option value="OR">
<Tag color="orange">OR</Tag>
</Select.Option>
</Select>
)}
</Space>
</Col>
<Col>
<Button
type="text"
danger
size="small"
icon={<DeleteOutlined />}
onClick={() => removeConditionGroup(groupIndex)}
>
删除组
</Button>
</Col>
</Row>
}
>
{group.conditions.length === 0 ? (
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="请添加条件" style={{ margin: '8px 0' }} />
) : (
group.conditions.map((cond, condIndex) => renderConditionRow(cond, groupIndex, condIndex))
)}
<Space wrap style={{ marginTop: 8 }}>
{WEATHER_PARAMETERS.map(param => (
<Button
key={param.key}
size="small"
type="dashed"
disabled={usedParams.includes(param.key)}
onClick={() => addConditionToGroup(groupIndex, param.key)}
>
+ {param.icon} {param.label}
</Button>
))}
</Space>
</Card>
);
};
// 生成规则描述
const generateRuleDescription = () => {
if (conditionGroups.length === 0) return '';
const groupDescs = conditionGroups.map(g => {
if (g.conditions.length === 0) return '';
const condDescs = g.conditions.map(c => {
const param = WEATHER_PARAMETERS.find(p => p.key === c.parameter);
return `${param?.label || c.parameter} ${c.operator} ${c.value}${c.unit}`;
});
return g.conditions.length > 1 ? `(${condDescs.join(` ${g.logicalOperator} `)})` : condDescs[0];
}).filter(Boolean);
return groupDescs.join(` ${groupOperator} `);
};
return (
<Modal
title={
<Space>
<CloudOutlined style={{ color: '#1890ff' }} />
<span>天气阻飞设置</span>
<Tag color={type === 'tourism' ? 'green' : 'red'}>
{type === 'tourism' ? '景区' : '设备'}
</Tag>
</Space>
}
open={visible}
onCancel={() => onVisibleChange(false)}
width={750}
footer={[
<Button key="cancel" onClick={() => onVisibleChange(false)}>取消</Button>,
<Button key="save" type="primary" loading={saving} onClick={handleSave}>保存设置</Button>,
]}
destroyOnClose
>
<Spin spinning={loading}>
<Alert
message={<Space><Text strong>{targetName || targetId}</Text><Text type="secondary">({type === 'tourism' ? `景区ID: ${targetId}` : `设备SN: ${targetId}`})</Text></Space>}
type="info"
showIcon
icon={type === 'tourism' ? <CloudOutlined /> : <ThunderboltOutlined />}
style={{ marginBottom: 16 }}
/>
<Card size="small" style={{ marginBottom: 16 }}>
<Row align="middle" justify="space-between">
<Col>
<Space>
<SafetyCertificateOutlined style={{ fontSize: 20, color: enabled ? '#52c41a' : '#999' }} />
<div>
<div><Text strong>启用天气阻飞</Text></div>
<Text type="secondary" style={{ fontSize: 12 }}>开启后,满足阻飞条件时将禁止创建任务</Text>
</div>
</Space>
</Col>
<Col>
<Switch
checked={enabled}
onChange={handleToggle}
checkedChildren={<CheckCircleOutlined />}
unCheckedChildren={<CloseCircleOutlined />}
/>
</Col>
</Row>
</Card>
{enabled && (
<>
<Divider orientation="left" plain><Text type="secondary">阻飞规则配置</Text></Divider>
{existingRule && !showRuleForm ? (
<Card size="small" style={{ marginBottom: 16 }}>
<Row align="middle" justify="space-between">
<Col><Text strong>{existingRule.ruleName}</Text></Col>
<Col><Button size="small" onClick={() => setShowRuleForm(true)}>编辑规则</Button></Col>
</Row>
<div style={{ marginTop: 8 }}>
<Text type="secondary">{generateRuleDescription()}</Text>
</div>
</Card>
) : (
<>
<div style={{ marginBottom: 12 }}>
<Text style={{ marginRight: 8 }}>规则名称:</Text>
<Input
value={ruleName}
onChange={(e) => setRuleName(e.target.value)}
placeholder="请输入规则名称"
style={{ width: 300 }}
/>
</div>
<div style={{ marginBottom: 12 }}>
<Text type="secondary" style={{ marginRight: 8 }}>快速应用模板:</Text>
<Space wrap>
{RULE_TEMPLATES.map(t => (
<Button key={t.name} size="small" onClick={() => applyTemplate(t)} title={t.description}>
{t.name}
</Button>
))}
</Space>
</div>
{conditionGroups.length > 1 && (
<div style={{ marginBottom: 12 }}>
<Text style={{ marginRight: 8 }}>条件组之间关系:</Text>
<Select value={groupOperator} onChange={setGroupOperator} style={{ width: 200 }}>
<Select.Option value="OR"><Tag color="orange">OR</Tag> 任一组满足则阻飞</Select.Option>
<Select.Option value="AND"><Tag color="blue">AND</Tag> 所有组满足才阻飞</Select.Option>
</Select>
</div>
)}
{conditionGroups.length === 0 ? (
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="请添加条件组" style={{ margin: '16px 0' }} />
) : (
<>
{conditionGroups.map((group, index) => (
<React.Fragment key={index}>
{renderConditionGroup(group, index)}
{index < conditionGroups.length - 1 && (
<div style={{ textAlign: 'center', margin: '8px 0' }}>
<Tag color={groupOperator === 'OR' ? 'orange' : 'blue'}>{groupOperator}</Tag>
</div>
)}
</React.Fragment>
))}
</>
)}
<Button type="dashed" block icon={<PlusOutlined />} onClick={addConditionGroup} style={{ marginTop: 8 }}>
添加条件组
</Button>
{conditionGroups.length > 0 && (
<Alert
message={<Text strong>规则预览:</Text>}
description={generateRuleDescription() || '请配置条件'}
type="info"
style={{ marginTop: 16 }}
/>
)}
</>
)}
<Alert
message={type === 'tourism' ? '景区级别规则对该景区下所有设备生效' : '设备级别规则优先级最高,仅对该设备生效'}
type="warning"
showIcon
icon={<InfoCircleOutlined />}
style={{ marginTop: 16 }}
/>
</>
)}
</Spin>
</Modal>
);
};
export default WeatherBlockSettingModal;