diff --git a/src/components/SystemSetting/RuleConfigManagement.tsx b/src/components/SystemSetting/RuleConfigManagement.tsx index c13e4fc..f4f2a6a 100644 --- a/src/components/SystemSetting/RuleConfigManagement.tsx +++ b/src/components/SystemSetting/RuleConfigManagement.tsx @@ -16,6 +16,7 @@ import { Col, App, } from 'antd'; +import type { FormInstance } from 'antd/es/form'; import { SearchOutlined, ReloadOutlined, @@ -41,67 +42,134 @@ const { Option } = Select; const AntdCard = Card as any; -// 规则类型 +// ====================== TS 类型(和后端实体对齐)====================== +type RuleType = 'LOW_BATTERY_RETURN'; +type DeviceScope = 'ALL' | 'GROUP' | 'SOME'; +type CompareEnum = 'GT' | 'GTE' | 'LT' | 'LTE' | 'EQ' | 'NE' | 'BETWEEN' | 'NOT_BETWEEN'; +type ActionType = 'AUTO_TASK' | 'SEND_COMMAND' | 'ALARM' | 'WORK_ORDER'; + +interface TriggerConditions { + key: string; + operator: CompareEnum; + value: string; +} + +interface ActionConfig { + actionType: ActionType; + args: Record; +} + +interface RuleItem { + id?: number; + ruleName: string; + ruleType: RuleType; + deviceScope: DeviceScope; + conditions: TriggerConditions; + actionConfig: ActionConfig; + enabled: boolean; + // 后端字段:ForceExecute(大驼峰,不规范,建议后端改为 forceExecute) + ForceExecute: boolean; + orgId?: string; + siteId?: string; +} + +interface SearchFormValues { + ruleName?: string; + ruleType?: RuleType; + enabled?: number | ''; +} + +interface RuleFormValues { + ruleName: string; + ruleType: RuleType; + deviceScope: DeviceScope; + key: string; + operator: CompareEnum; + value?: number; + min?: number; + max?: number; + actionType: ActionType; + argsJson: string; + enabled: boolean; + ForceExecute: boolean; +} + +// ====================== 常量配置 ====================== const RuleTypeOptions = [ - { value: 'LOW_BATTERY_RETURN', labelKey: 'ruleTypeLowBatteryReturn' }, + { value: 'LOW_BATTERY_RETURN' as RuleType, labelKey: 'ruleTypeLowBatteryReturn' }, ]; -// 适用范围 const DeviceScopeOptions = [ - { value: 'ALL', labelKey: 'deviceScopeAll' }, - { value: 'GROUP', labelKey: 'deviceScopeGroup' }, - { value: 'SOME', labelKey: 'deviceScopeSome' }, + { value: 'ALL' as DeviceScope, labelKey: 'deviceScopeAll' }, + { value: 'GROUP' as DeviceScope, labelKey: 'deviceScopeGroup' }, + { value: 'SOME' as DeviceScope, labelKey: 'deviceScopeSome' }, ]; -// 触发字段 const TriggerKeyOptions = [ - { value: 'battery', labelKey: 'triggerKeyBattery' }, + { value: 'battery_percentage', labelKey: 'triggerKeyBattery' }, { value: 'temperature', labelKey: 'triggerKeyTemperature' }, { value: 'offline_duration', labelKey: 'triggerKeyOfflineDuration' }, { value: 'voltage', labelKey: 'triggerKeyVoltage' }, ]; -// 执行动作 const ActionTypeOptions = [ - { value: 'AUTO_TASK', labelKey: 'actionTypeAutoTask' }, - { value: 'SEND_COMMAND', labelKey: 'actionTypeSendCommand' }, - { value: 'ALARM', labelKey: 'actionTypeAlarm' }, - { value: 'WORK_ORDER', labelKey: 'actionTypeWorkOrder' }, + //{ value: 'AUTO_TASK' as ActionType, labelKey: 'actionTypeAutoTask' }, + { value: 'BACK_TO_REST' as ActionType, labelKey: 'actionTypeBackToRest' }, + + //BACK_TO_REST + { value: 'SEND_COMMAND' as ActionType, labelKey: 'actionTypeSendCommand' }, + { value: 'ALARM' as ActionType, labelKey: 'actionTypeAlarm' }, + { value: 'WORK_ORDER' as ActionType, labelKey: 'actionTypeWorkOrder' }, ]; -const rangeOperators = ['BETWEEN', 'NOT_BETWEEN']; +const rangeOperators: CompareEnum[] = ['BETWEEN', 'NOT_BETWEEN']; export default function RuleConfigManagement() { const { t } = useTranslation(); const { stationId, currentStation } = useSelector((state: RootState) => state.station); const { modal } = App.useApp(); - const [form] = Form.useForm(); - const [searchForm] = Form.useForm(); + const [form] = Form.useForm(); + const [searchForm] = Form.useForm(); const [loading, setLoading] = useState(false); - const [ruleList, setRuleList] = useState([]); - const [filteredList, setFilteredList] = useState([]); + const [ruleList, setRuleList] = useState([]); + const [filteredList, setFilteredList] = useState([]); const [modalVisible, setModalVisible] = useState(false); const [modalType, setModalType] = useState<'add' | 'edit' | 'view'>('add'); - const [currentRecord, setCurrentRecord] = useState(null); + const [currentRecord, setCurrentRecord] = useState(null); const [submitting, setSubmitting] = useState(false); - // 获取规则列表 + const operatorWatch = Form.useWatch('operator', form); + const isRangeOperator = useMemo(() => rangeOperators.includes(operatorWatch), [operatorWatch]); + const disabledForm = modalType === 'view'; + + // 公共翻译label获取 + const getOptionLabel = (options: Array<{ value: string; labelKey: string }>, value: string, ns = 'systemSetting') => { + const item = options.find(o => o.value === value); + return item ? t(`${ns}.${item.labelKey}`) : value; + }; + + // 获取列表 const fetchRuleList = async () => { if (!stationId) return; setLoading(true); try { const res = await selectRuleBySiteId({ siteId: stationId }); - if (res.code == 200) { - const list = res?.data || res?.rows || []; + if (res.code === 200) { + // 兼容多种后端返回结构:数组直接用 / 分页对象取 records/rows/list / 其他回退空数组 + const raw = res?.data; + let list: RuleItem[] = []; + if (Array.isArray(raw)) list = raw; + else if (raw && typeof raw === 'object') list = Array.isArray(raw.records) ? raw.records : Array.isArray(raw.rows) ? raw.rows : Array.isArray(raw.list) ? raw.list : []; + console.log('[selectRuleBySiteId] res.data type:', Array.isArray(raw) ? 'array' : typeof raw, '-> list len:', list.length); setRuleList(list); + console.log(list, "list") setFilteredList(list); } else { setRuleList([]); setFilteredList([]); } - } catch (err) { utils.message.error(t('systemSetting.operationFailed')); } finally { @@ -117,7 +185,7 @@ export default function RuleConfigManagement() { const handleSearch = () => { searchForm.validateFields().then(values => { const next = ruleList.filter(item => { - const matchName = !values.ruleName || (item.ruleName || '').toLowerCase().includes(values.ruleName.toLowerCase()); + const matchName = !values.ruleName || item.ruleName.toLowerCase().includes(values.ruleName.toLowerCase()); const matchType = !values.ruleType || item.ruleType === values.ruleType; const matchEnabled = values.enabled === undefined || values.enabled === '' || Number(item.enabled) === Number(values.enabled); return matchName && matchType && matchEnabled; @@ -132,31 +200,36 @@ export default function RuleConfigManagement() { }; // 打开弹窗 - const openModal = (type: 'add' | 'edit' | 'view', record?: any) => { + const openModal = (type: 'add' | 'edit' | 'view', record?: RuleItem) => { setModalType(type); - setCurrentRecord(record || null); + setCurrentRecord(record ?? null); setModalVisible(true); form.resetFields(); if ((type === 'edit' || type === 'view') && record) { - const conditions = record.conditions || {}; - const actionConfig = record.actionConfig || {}; + const conditions = record.conditions; + const actionConfig = record.actionConfig; const isRange = rangeOperators.includes(conditions.operator); - let min = ''; - let max = ''; - let value = conditions.value; - if (isRange && typeof conditions.value === 'string' && conditions.value.includes(',')) { + + let min: number | undefined; + let max: number | undefined; + let value: number | undefined; + + if (isRange && conditions.value.includes(',')) { const [a, b] = conditions.value.split(','); - min = a; - max = b; - value = ''; + min = Number(a); + max = Number(b); + } else { + value = Number(conditions.value); } + let argsJson = ''; try { argsJson = actionConfig.args ? JSON.stringify(actionConfig.args, null, 2) : ''; } catch (e) { argsJson = ''; } + form.setFieldsValue({ ruleName: record.ruleName, ruleType: record.ruleType, @@ -168,10 +241,11 @@ export default function RuleConfigManagement() { max, actionType: actionConfig.actionType, argsJson, - enabled: record.enabled === true || record.enabled === 1, - ForceExecute: record.ForceExecute === true || record.ForceExecute === 1, + enabled: record.enabled, + ForceExecute: record.ForceExecute, }); } else { + // 新增默认值 form.setFieldsValue({ ruleType: 'LOW_BATTERY_RETURN', deviceScope: 'ALL', @@ -184,39 +258,53 @@ export default function RuleConfigManagement() { } }; - // 保存规则 - const handleSave = async (values: any) => { - let argsObj: any = {}; - if (values.argsJson) { + // ✅ 保存逻辑(重点优化) + const handleSave = async (values: RuleFormValues) => { + // 1. JSON 参数解析校验 + let argsObj: Record = {}; + if (values.argsJson?.trim()) { try { - argsObj = JSON.parse(values.argsJson); + argsObj = JSON.parse(values.argsJson.trim()); } catch (e) { utils.message.error(t('systemSetting.invalidJson')); return; } } - const isRange = rangeOperators.includes(values.operator); - const value = isRange ? `${values.min},${values.max}` : values.value; + // 2. 根据运算符拼接 value(后端存字符串) + let conditionValue: string; + if (isRangeOperator) { + if (values.min === undefined || values.max === undefined) { + utils.message.error(t('systemSetting.pleaseInputTriggerValue')); + return; + } + conditionValue = `${values.min},${values.max}`; + } else { + if (values.value === undefined) { + utils.message.error(t('systemSetting.pleaseInputTriggerValue')); + return; + } + conditionValue = String(values.value); + } - const submitData: any = { + const submitData: RuleItem = { id: modalType === 'edit' ? currentRecord?.id : undefined, - ruleName: values.ruleName, + ruleName: values.ruleName.trim(), ruleType: values.ruleType, deviceScope: values.deviceScope, conditions: { key: values.key, operator: values.operator, - value, + value: conditionValue, }, actionConfig: { actionType: values.actionType, args: argsObj, }, - enabled: values.enabled ? 1 : 0, - ForceExecute: values.ForceExecute ? 1 : 0, - orgId: currentStation?.orgId || '', - siteId: stationId || '', + enabled: values.enabled, + ForceExecute: values.ForceExecute, + orgId: currentStation?.orgId, + siteId: stationId, }; setSubmitting(true); @@ -236,8 +324,8 @@ export default function RuleConfigManagement() { } }; - // 删除规则 - const handleDelete = (record: any) => { + // 删除 + const handleDelete = (record: RuleItem) => { modal.confirm({ title: t('common.confirmDelete'), content: t('systemSetting.confirmDeleteRule', { name: record.ruleName }), @@ -246,7 +334,7 @@ export default function RuleConfigManagement() { cancelText: t('common.cancel'), onOk: async () => { try { - const res = await deleteRule({ ids: [record.id] }); + const res = await deleteRule([record.id!]); if (res?.code === 200) { utils.message.success(t('common.deleteSuccess')); fetchRuleList(); @@ -260,19 +348,16 @@ export default function RuleConfigManagement() { }); }; - const operatorWatch = Form.useWatch('operator', form); - const isRangeOperator = useMemo(() => rangeOperators.includes(operatorWatch), [operatorWatch]); + const renderConditions = (record: RuleItem) => { + const c = record.conditions; + // 匹配 key 对应的 labelKey + const keyItem = TriggerKeyOptions.find(o => o.value === c.key); + const keyLabel = keyItem ? t(`systemSetting.${keyItem.labelKey}`) : c.key; - const getLabel = (options: any[], value: string, ns: string = 'systemSetting') => { - const item = options.find(o => o.value === value); - return item ? t(`${ns}.${item.labelKey}`) : value; - }; - - const renderConditions = (record: any) => { - const c = record.conditions || {}; const opItem = CompareEnumOptions.find(o => o.value === c.operator); - const opLabel = opItem ? t(`constants.${opItem.label}`) : c.operator; - return {c.key} {opLabel} {c.value}; + const opLabel = opItem ? t(opItem.label) : c.operator; + + return {keyLabel} {opLabel} {c.value}; }; const columns = [ @@ -288,59 +373,71 @@ export default function RuleConfigManagement() { dataIndex: 'ruleType', key: 'ruleType', width: 140, - render: (text: string) => getLabel(RuleTypeOptions, text), + render: (text: RuleType) => getOptionLabel(RuleTypeOptions, text), }, { title: t('systemSetting.deviceScope'), dataIndex: 'deviceScope', key: 'deviceScope', width: 120, - render: (text: string) => getLabel(DeviceScopeOptions, text), + render: (text: DeviceScope) => getOptionLabel(DeviceScopeOptions, text), }, { title: t('systemSetting.triggerKey'), key: 'conditions', width: 220, - render: (_: any, record: any) => renderConditions(record), + render: (_: any, record: RuleItem) => renderConditions(record), }, { title: t('systemSetting.actionType'), dataIndex: ['actionConfig', 'actionType'], key: 'actionType', width: 140, - render: (text: string) => getLabel(ActionTypeOptions, text), + render: (text: ActionType) => getOptionLabel(ActionTypeOptions, text), }, { title: t('systemSetting.enabledLabel'), dataIndex: 'enabled', key: 'enabled', width: 100, - render: (val: any) => {val === 1 || val === true ? t('common.enable') : t('common.disable')}, - }, - { - title: t('systemSetting.forceExecute'), - dataIndex: 'ForceExecute', - key: 'ForceExecute', - width: 100, - render: (val: any) => {val === 1 || val === true ? t('common.yes') : t('common.no')}, + render: (val: boolean) => ( + + {val ? t('common.enable') : t('common.disable')} + + ), }, + //{ + // title: t('systemSetting.forceExecute'), + // dataIndex: 'ForceExecute', + // key: 'ForceExecute', + // width: 100, + // render: (val: boolean) => ( + // + // {val ? t('common.yes') : t('common.no')} + // + // ), + //}, { title: t('common.actions'), key: 'action', width: 220, fixed: 'right' as const, - render: (_: any, record: any) => ( + render: (_: any, record: RuleItem) => ( - - - + + + ), }, ]; - const disabledForm = modalType === 'view'; - return (
@@ -351,7 +448,9 @@ export default function RuleConfigManagement() { @@ -363,9 +462,20 @@ export default function RuleConfigManagement() { - - - + + + @@ -376,12 +486,22 @@ export default function RuleConfigManagement() { dataSource={filteredList} loading={loading} scroll={{ x: 1100 }} - pagination={{ pageSize: 10, showSizeChanger: true, showTotal: total => t('common.total', { total }) }} + pagination={{ + pageSize: 10, + showSizeChanger: true, + showTotal: total => t('common.total', { total }), + }} /> - + ) } @@ -406,15 +528,25 @@ export default function RuleConfigManagement() { > - + - + @@ -423,19 +555,31 @@ export default function RuleConfigManagement() { - + - + @@ -444,10 +588,16 @@ export default function RuleConfigManagement() { - + @@ -456,18 +606,30 @@ export default function RuleConfigManagement() { {isRangeOperator ? ( - + - + ) : ( - + )} @@ -476,10 +638,16 @@ export default function RuleConfigManagement() { - + @@ -491,21 +659,21 @@ export default function RuleConfigManagement() { - + {/*