告警中心 初始化

This commit is contained in:
mmc
2026-05-07 14:13:26 +08:00
parent e401eef62f
commit 9cf26ce2bd
19 changed files with 1321 additions and 928 deletions

View File

@@ -0,0 +1,349 @@
import { useState } from 'react';
import {
Card, Table, Button, Space, Form, Modal, Input, Select, InputNumber,
Tabs, Tag, Popconfirm, message, Divider, Switch, Empty
} from 'antd';
import {
PlusOutlined, EditOutlined, DeleteOutlined, ProductOutlined,
AppstoreOutlined, SwapOutlined, VideoCameraOutlined, AlertOutlined
} from '@ant-design/icons';
const { Option } = Select;
const { TabPane } = Tabs;
// ====================== 模拟基础数据 ======================
const productList = [
{
id: 1, name: '海康威视摄像头', code: 'hikvision', protocolType: 'onvif', manufacturer: '海康',
publishTopic: '/hik/device/upload', subscribeTopic: '/hik/device/cmd'
},
{
id: 2, name: '大华摄像头', code: 'dahua', protocolType: 'rtsp', manufacturer: '大华',
publishTopic: '/dahua/device/upload', subscribeTopic: '/dahua/device/cmd'
},
{
id: 3, name: '通用MQTT设备', code: 'mqtt_device', protocolType: 'mqtt', manufacturer: '通用',
publishTopic: '/iot/device/upload', subscribeTopic: '/iot/device/cmd'
},
];
const modelList = [
{ id: 10, name: '通用视频监控设备', code: 'video_camera', desc: '摄像头、云台、告警' },
{ id: 11, name: '环境监测设备', code: 'env_sensor', desc: '温湿度、烟感' },
{ id: 12, name: '电池供电设备', code: 'battery_device', desc: '电量、电压监测' },
];
const modelDetailList: Record<number, {
props: any[];
events: any[];
actions: any[];
}> = {
10: {
props: [
{ id: 1, code: 'device_online', name: '在线状态', type: 'bool', rw: 'r', isAlarm: false },
{ id: 2, code: 'record_status', name: '录像状态', type: 'string', rw: 'r', isAlarm: false },
],
events: [{ id: 1, code: 'alarm_perimeter', name: '周界入侵告警' }],
actions: [{ id: 1, code: 'take_snapshot', name: '截图' }]
},
11: {
props: [
{ id: 1, code: 'temp', name: '温度', type: 'float', rw: 'r', isAlarm: true },
{ id: 2, code: 'humi', name: '湿度', type: 'float', rw: 'r', isAlarm: true },
],
events: [{ id: 1, code: 'temp_over', name: '超温告警' }],
actions: []
},
12: {
props: [
{ id: 1, code: 'battery', name: '电量', type: 'int', rw: 'r', isAlarm: true },
{ id: 2, code: 'voltage', name: '电压', type: 'float', rw: 'r', isAlarm: true },
],
events: [{ id: 1, code: 'low_power', name: '低电量告警' }],
actions: []
}
};
let mappingInitList = [
{ id: 1, productId: 1, standardCode: 'device_online', sourceField: 'online_flag', convertRule: 'value==1?true:false' }
];
const deviceList = [
{
id: 1, name: '1#阵列区球机', sn: 'HK20260507001',
productId: 1, productName: '海康威视摄像头', modelId: 10, modelName: '通用视频监控设备',
protocolType: 'onvif', ip: '192.168.1.65', port: 80, username: 'admin', password: '123456',
mqttServer: '', mqttPort: 1883, clientId: '', mqttUsername: '', mqttPassword: '',
alarmConfig: {}, onlineStatus: 1, createTime: '2026-05-07 10:23:45'
},
{
id: 2, name: '1#环境传感器', sn: 'SEN001',
productId: 3, productName: '通用MQTT设备', modelId: 11, modelName: '环境监测设备',
protocolType: 'mqtt', mqttServer: 'tcp://192.168.1.200', mqttPort: 1883, clientId: 'sen_001',
alarmConfig: { tempMax: 60, tempMin: 0, humiMax: 90, humiMin: 20 }, onlineStatus: 1
}
];
const alarmList = [{ id: 1, deviceName: '1#环境传感器', level: 'warn', content: '温度超过阈值 62℃', time: '2026-05-07 10:24:00' }];
export default function DeviceAccessPage() {
const [activeTab, setActiveTab] = useState('device');
const [form] = Form.useForm();
const [visible, setVisible] = useState(false);
const [modalType, setModalType] = useState('');
const [editData, setEditData] = useState<any>(null);
const [deviceProtocol, setDeviceProtocol] = useState('onvif');
const [productProtocol, setProductProtocol] = useState('');
const [modelDetail, setModelDetail] = useState<any>({ props: [], events: [], actions: [] });
const [itemModal, setItemModal] = useState(false);
const [itemType, setItemType] = useState<'props' | 'events' | 'actions'>('props');
const [itemForm] = Form.useForm();
// 字段映射(实时增删改查,实时保存)
const [mappingList, setMappingList] = useState(mappingInitList);
const [mappingModal, setMappingModal] = useState(false);
const [mappingForm] = Form.useForm();
// 打开弹窗
const openModal = (type: string, record?: any) => {
setModalType(type);
setEditData(record);
form.resetFields();
if (record) {
form.setFieldsValue(record);
if (type === 'model') setModelDetail(modelDetailList[record.id] || { props: [], events: [], actions: [] });
if (type === 'device') {
setDeviceProtocol(record.protocolType);
setModelDetail(modelDetailList[record.modelId] || { props: [] });
}
if (type === 'product') setProductProtocol(record.protocolType || '');
} else {
if (type === 'device') { setDeviceProtocol('onvif'); setModelDetail({ props: [] }); }
else if (type === 'product') setProductProtocol('');
else setModelDetail({ props: [], events: [], actions: [] });
}
setVisible(true);
};
// 产品提交
const handleSubmit = () => {
form.validateFields().then(values => {
message.success('产品信息保存成功');
setVisible(false);
});
};
// 物模型
const openItemModal = (type: 'props' | 'events' | 'actions', record?: any) => {
setItemType(type);
itemForm.resetFields();
if (record) itemForm.setFieldsValue(record);
setItemModal(true);
};
const saveItem = () => {
itemForm.validateFields().then((val) => {
const list = [...modelDetail[itemType]];
val.id ? list.splice(list.findIndex(x => x.id === val.id), 1, val) : list.push({ ...val, id: Date.now() });
setModelDetail({ ...modelDetail, [itemType]: list });
setItemModal(false);
});
};
const deleteItem = (type: 'props' | 'events' | 'actions', id: number) => {
const list = modelDetail[type].filter(x => x.id !== id);
setModelDetail({ ...modelDetail, [type]: list });
};
// ===================== 字段映射:增删改 立即保存 =====================
const openMappingModal = (record?: any) => {
mappingForm.resetFields();
if (record) mappingForm.setFieldsValue(record);
else mappingForm.setFieldsValue({ productId: editData?.id });
setMappingModal(true);
};
// 新增/编辑 → 立即保存
const saveMapping = () => {
mappingForm.validateFields().then(val => {
let newList = [...mappingList];
if (val.id) {
// 编辑
const index = newList.findIndex(x => x.id === val.id);
if (index >= 0) newList[index] = val;
message.success('字段映射修改成功');
} else {
// 新增
newList.push({ ...val, id: Date.now() });
message.success('字段映射新增成功');
}
setMappingList(newList);
mappingInitList = newList;
setMappingModal(false);
});
};
// 删除 → 立即保存
const deleteMapping = (id: number) => {
const newList = mappingList.filter(x => x.id !== id);
setMappingList(newList);
mappingInitList = newList;
message.success('字段映射删除成功');
};
// 获取告警属性
const getAlarmProps = () => modelDetail?.props?.filter(item => item.isAlarm) || [];
// 表格列
const deviceColumns = [
{ title: '设备名称', dataIndex: 'name' },
{ title: 'SN', dataIndex: 'sn' },
{ title: '所属产品', dataIndex: 'productName' },
{ title: '物模型', dataIndex: 'modelName' },
{ title: '协议', dataIndex: 'protocolType', render: t => <Tag>{t.toUpperCase()}</Tag> },
{ title: '状态', render: r => <Tag color={r.onlineStatus ? 'green' : 'red'}>{r.onlineStatus ? '在线' : '离线'}</Tag> },
{ title: '操作', render: r => <Space><Button type="text" icon={<EditOutlined />} onClick={() => openModal('device', r)}>编辑</Button></Space> }
];
const productColumns = [
{ title: '产品名称', dataIndex: 'name' },
{ title: '厂商', dataIndex: 'manufacturer' },
{ title: '协议', dataIndex: 'protocolType' },
{ title: '上报Topic', dataIndex: 'publishTopic' },
{ title: '订阅Topic', dataIndex: 'subscribeTopic' },
{
title: '操作', render: r => (
<Space>
<Button type="text" icon={<EditOutlined />} onClick={() => openModal('product', r)}>编辑</Button>
<Button type="text" icon={<SwapOutlined />} onClick={() => openModal('product', r)}>字段映射</Button>
</Space>
)
}
];
const modelColumns = [
{ title: '模型名称', dataIndex: 'name' },
{ title: '描述', dataIndex: 'desc' },
{ title: '操作', render: r => <Button type="text" icon={<EditOutlined />} onClick={() => openModal('model', r)}>编辑</Button> }
];
return (
<div className="p-5 bg-[#f5f7fa] min-h-screen">
<Card className="mb-4">
<Tabs activeKey={activeTab} onChange={setActiveTab}>
<TabPane tab={<span><VideoCameraOutlined />设备管理</span>} key="device" />
<TabPane tab={<span><ProductOutlined />产品管理</span>} key="product" />
<TabPane tab={<span><AppstoreOutlined />物模型管理</span>} key="model" />
</Tabs>
</Card>
{activeTab === 'device' && <Card><Space className="mb-3"><Button type="primary" icon={<PlusOutlined />} onClick={() => openModal('device')}>新增设备</Button></Space><Table rowKey="id" columns={deviceColumns} dataSource={deviceList} /></Card>}
{activeTab === 'product' && <Card><Space><Button type="primary" icon={<PlusOutlined />} onClick={() => openModal('product')}>新增产品</Button></Space><Table rowKey="id" columns={productColumns} dataSource={productList} /></Card>}
{activeTab === 'model' && <Card><Space><Button type="primary" icon={<PlusOutlined />} onClick={() => openModal('model')}>新增物模型</Button></Space><Table rowKey="id" columns={modelColumns} dataSource={modelList} /></Card>}
<Modal open={visible} width={850} onCancel={() => setVisible(false)} onOk={handleSubmit} destroyOnClose
title={modalType === 'device' ? '设备配置' : modalType === 'product' ? '产品配置' : '物模型配置'}>
<Form form={form} layout="vertical">
{modalType === 'device' && (
<Tabs defaultActiveKey="base">
<TabPane tab="基础信息" key="base">
<Form.Item label="设备名称" name="name" rules={[{ required: true }]}><Input /></Form.Item>
<Form.Item label="设备SN" name="sn" rules={[{ required: true }]}><Input /></Form.Item>
<Form.Item label="关联产品" name="productId" rules={[{ required: true }]}><Select>{productList.map(p => <Option key={p.id} value={p.id}>{p.name}</Option>)}</Select></Form.Item>
<Form.Item label="关联物模型" name="modelId" rules={[{ required: true }]}><Select onChange={val => setModelDetail(modelDetailList[val] || { props: [] })}>{modelList.map(m => <Option key={m.id} value={m.id}>{m.name}</Option>)}</Select></Form.Item>
</TabPane>
<TabPane tab="协议配置" key="protocol">
<Form.Item label="设备协议类型" name="protocolType" rules={[{ required: true }]}>
<Select value={deviceProtocol} onChange={setDeviceProtocol}>
<Option value="onvif">ONVIF 协议</Option>
<Option value="rtsp">RTSP 视频流</Option>
<Option value="mqtt">MQTT 物联网协议</Option>
</Select>
</Form.Item>
<Divider />
{deviceProtocol === 'onvif' && <><Form.Item label="设备IP地址" name="ip"><Input /></Form.Item><Form.Item label="访问端口" name="port"><InputNumber className="w-full" /></Form.Item><Form.Item label="登录账号" name="username"><Input /></Form.Item><Form.Item label="登录密码" name="password"><Input.Password /></Form.Item></>}
{deviceProtocol === 'rtsp' && <Form.Item label="RTSP 完整流地址" name="rtspUrl"><Input /></Form.Item>}
{deviceProtocol === 'mqtt' && <><Form.Item label="MQTT 服务地址" name="mqttServer"><Input /></Form.Item><Form.Item label="MQTT 端口" name="mqttPort"><InputNumber defaultValue={1883} /></Form.Item><Form.Item label="设备 ClientID" name="clientId"><Input /></Form.Item><Form.Item label="MQTT 用户名" name="mqttUsername"><Input /></Form.Item><Form.Item label="MQTT 密码" name="mqttPassword"><Input.Password /></Form.Item></>}
</TabPane>
<TabPane tab="报警阈值" key="alarm">
{getAlarmProps().map(item => <div key={item.code}><Form.Item label={`${item.name} 上限`} name={['alarmConfig', `${item.code}Max`]}><InputNumber className="w-full" /></Form.Item><Form.Item label={`${item.name} 下限`} name={['alarmConfig', `${item.code}Min`]}><InputNumber className="w-full" /></Form.Item></div>)}
{getAlarmProps().length === 0 && <Empty description="当前物模型无配置告警参数" />}
</TabPane>
</Tabs>
)}
{modalType === 'product' && (
<Tabs defaultActiveKey="base">
<TabPane tab="基础信息" key="base">
<Form.Item label="产品名称" name="name" rules={[{ required: true }]}><Input /></Form.Item>
<Form.Item label="厂商名称" name="manufacturer"><Input /></Form.Item>
<Form.Item label="默认协议类型" name="protocolType"><Select value={productProtocol} onChange={setProductProtocol}><Option value="onvif">ONVIF</Option><Option value="rtsp">RTSP</Option><Option value="mqtt">MQTT</Option></Select></Form.Item>
{productProtocol === 'mqtt' && <><Divider>MQTT 厂商级 Topic 配置</Divider><Form.Item label="设备上报 Topic" name="publishTopic"><Input /></Form.Item><Form.Item label="平台下发 Topic" name="subscribeTopic"><Input /></Form.Item></>}
</TabPane>
<TabPane tab="字段映射" key="mapping">
<Button size="small" type="primary" icon={<PlusOutlined />} onClick={() => openMappingModal()} className="mb-2">新增映射</Button>
<Table size="small" dataSource={mappingList.filter(x => x.productId === editData?.id)} pagination={false}
columns={[
{ title: '标准字段', dataIndex: 'standardCode' },
{ title: '厂商原始字段', dataIndex: 'sourceField' },
{ title: '转换规则', dataIndex: 'convertRule' },
{
title: '操作', render: r => (
<Space>
<Button type="text" icon={<EditOutlined />} onClick={() => openMappingModal(r)}>编辑</Button>
<Popconfirm onConfirm={() => deleteMapping(r.id)} title="确定删除?"><Button type="text" danger icon={<DeleteOutlined />}>删除</Button></Popconfirm>
</Space>
)
}
]}
/>
</TabPane>
</Tabs>
)}
{modalType === 'model' && (
<>
<Form.Item label="模型名称" name="name" rules={[{ required: true }]}><Input /></Form.Item>
<Form.Item label="模型编码" name="code" rules={[{ required: true }]}><Input /></Form.Item>
<Form.Item label="模型描述" name="desc"><Input.TextArea rows={2} /></Form.Item>
<Divider>属性列表</Divider>
<Button size="small" type="primary" icon={<PlusOutlined />} onClick={() => openItemModal('props')} className="mb-2">新增属性</Button>
<Table size="small" dataSource={modelDetail.props} pagination={false} columns={[
{ title: '编码', dataIndex: 'code' }, { title: '名称', dataIndex: 'name' }, { title: '类型', dataIndex: 'type' },
{ title: '告警', render: r => <Switch checked={r.isAlarm} disabled size="small" /> },
{ title: '操作', render: r => <Space><Button type="text" icon={<EditOutlined />} onClick={() => openItemModal('props', r)}>编辑</Button><Popconfirm onConfirm={() => deleteItem('props', r.id)}><Button type="text" danger icon={<DeleteOutlined />}>删除</Button></Popconfirm></Space> }
]} />
<Divider>事件列表</Divider>
<Button size="small" type="primary" icon={<PlusOutlined />} onClick={() => openItemModal('events')} className="mb-2">新增事件</Button>
<Table size="small" dataSource={modelDetail.events} pagination={false} columns={[{ title: '编码', dataIndex: 'code' }, { title: '名称', dataIndex: 'name' }, { title: '操作', render: r => <Button type="text" icon={<EditOutlined />} onClick={() => openItemModal('events', r)}>编辑</Button> }]} />
</>
)}
</Form>
</Modal>
<Modal open={itemModal} width={520} zIndex={1001} destroyOnClose onCancel={() => setItemModal(false)} onOk={saveItem} title="编辑">
<Form form={itemForm} layout="vertical">
<Form.Item name="id" hidden><Input /></Form.Item>
<Form.Item label="编码" name="code" rules={[{ required: true }]}><Input /></Form.Item>
<Form.Item label="名称" name="name" rules={[{ required: true }]}><Input /></Form.Item>
{itemType === 'props' && <><Form.Item label="数据类型" name="type"><Select><Option value="int">int</Option><Option value="float">float</Option><Option value="string">string</Option></Select></Form.Item><Form.Item label="作为告警参数" name="isAlarm" valuePropName="checked"><Switch /></Form.Item></>}
</Form>
</Modal>
{/* 字段映射弹窗:操作即保存 */}
<Modal open={mappingModal} width={600} zIndex={1002} destroyOnClose onCancel={() => setMappingModal(false)} onOk={saveMapping} title="字段映射配置">
<Form form={mappingForm} layout="vertical">
<Form.Item name="id" hidden /><Form.Item name="productId" hidden />
<Form.Item label="标准模型字段" name="standardCode" rules={[{ required: true }]}>
<Select>{modelDetail.props?.map(p => <Option key={p.code} value={p.code}>{p.name}</Option>)}</Select>
</Form.Item>
<Form.Item label="厂商原始字段" name="sourceField" rules={[{ required: true }]}><Input /></Form.Item>
<Form.Item label="转换规则" name="convertRule"><Input /></Form.Item>
</Form>
</Modal>
</div>
);
}

View File

@@ -0,0 +1,272 @@
import React, { useState, useEffect } from 'react';
import {
Table, Button, Space, Modal, Form, Tree, message,
Input, Popconfirm, Select, Card, InputNumber, Row, Col, Tooltip
} from 'antd';
// 引入全部常用图标
import * as AllIcons from '@ant-design/icons';
import {
PlusOutlined, EditOutlined, DeleteOutlined, SettingOutlined
} from '@ant-design/icons';
import { addMenu, deleteMenu, getMenuList, updateMenu } from '../../api/mune';
import { buildPermTree, buildTreeFromFlat } from '../../lib/utils';
const { Option } = Select;
// 筛选常用图标(够用、不乱)
const iconList = Object.keys(AllIcons).filter(item => {
return item.endsWith('Outlined')
});
const rolePermissionMap = {};
export default function MenuList() {
const [rawMenuList, setRawMenuList] = useState([]);
const [menuTreeData, setMenuTreeData] = useState([]);
const [menuTree, setMenuTree] = useState([]);
const [iconModal, setIconModal] = useState(false);
const [menuModal, setMenuModal] = useState(false);
const [menuForm] = Form.useForm();
const [editMenu, setEditMenu] = useState(null);
const [permModal, setPermModal] = useState(false);
const [selectedRole, setSelectedRole] = useState('');
const [checkedKeys, setCheckedKeys] = useState([]);
const [messageApi, contextHolder] = message.useMessage();
// 分页状态
const [pagination, setPagination] = useState({
pageNum: 1,
pageSize: 9999,
total: 0
});
// 获取菜单(带分页)
const getMenuListApi = () => {
const params = {
pageNum: pagination.pageNum,
pageSize: pagination.pageSize
};
getMenuList(params).then(res => {
console.log(res, "res")
if (res.code === 200) {
const data = res.rows || [];
setRawMenuList(data);
const tree = buildTreeFromFlat(data);
setMenuTreeData(tree);
setMenuTree(buildPermTree(tree));
// 如果后台返回 total,设置总数
setPagination({
...pagination,
total: res.total || data.length
});
}
}).catch(() => {
messageApi.error('菜单加载失败');
});
};
useEffect(() => {
getMenuListApi();
}, [pagination.pageNum, pagination.pageSize]);
// 编辑
const handleEdit = (record) => {
setEditMenu(record);
menuForm.setFieldsValue({ ...record });
setMenuModal(true);
};
// 新增子菜单
const handleAddChild = (parentRecord) => {
setEditMenu(null);
menuForm.resetFields();
menuForm.setFieldsValue({
parentId: parentRecord.menuId
});
setMenuModal(true);
};
// 选择图标
const handleSelectIcon = (iconName) => {
menuForm.setFieldValue('icon', iconName);
setIconModal(false);
};
// 保存菜单
const handleSaveMenu = () => {
menuForm.validateFields().then(values => {
if (editMenu) {
const data = {
menuId: editMenu.menuId,
...values
};
updateMenu(data).then(res => {
if (res.code === 200) {
messageApi.success("编辑成功");
setMenuModal(false);
getMenuListApi();
} else {
messageApi.error(res.msg);
}
}).catch(() => {
messageApi.error('编辑失败');
});
} else {
addMenu(values).then(res => {
if (res.code === 200) {
messageApi.success("新增成功");
setMenuModal(false);
getMenuListApi();
} else {
messageApi.error(res.msg);
}
}).catch(() => {
messageApi.error('新增失败');
});
}
});
};
// 删除
const handleDelete = (menuId) => {
deleteMenu(menuId).then(res => {
if (res.code == 200) {
messageApi.success('删除成功');
getMenuListApi();
} else {
messageApi.error(res.msg);
}
}).catch(() => {
messageApi.error("删除失败");
});
};
const topMenus = rawMenuList.filter(m => m.parentId === 0 || !m.parentId);
const columns = [
{
title: '菜单名称',
dataIndex: 'menuName',
key: 'menuName',
},
{ title: '路由地址', dataIndex: 'path', key: 'path' },
{ title: '排序', dataIndex: 'orderNum', key: 'orderNum' },
{
title: '操作',
key: 'action',
width: 320,
render: (_, record) => (
<Space>
{record.parentId === 0 && (
<Button type="text" icon={<PlusOutlined />} onClick={() => handleAddChild(record)}>
新增子菜单
</Button>
)}
<Button type="text" icon={<EditOutlined />} onClick={() => handleEdit(record)}>编辑</Button>
<Popconfirm title="确定删除?" onConfirm={() => handleDelete(record.menuId)}>
<Button type="text" danger>删除</Button>
</Popconfirm>
</Space>
),
},
];
// 动态渲染图标
const renderIcon = (name) => {
const Icon = AllIcons[name];
return Icon ? <Icon /> : null;
};
return (
<div style={{ padding: '20px' }}>
{contextHolder}
<Card title="菜单管理" style={{ borderRadius: 8 }}>
<div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
<Button type="primary" icon={<PlusOutlined />} onClick={() => {
setEditMenu(null);
menuForm.resetFields();
setMenuModal(true);
}}>新增菜单</Button>
</div>
<Table
columns={columns}
dataSource={menuTreeData}
rowKey="menuId"
pagination={false} // 关闭分页
bordered
size="middle"
indentSize={24}
/>
{/* 菜单弹窗 */}
<Modal
title={editMenu ? '编辑菜单' : '新增菜单'}
open={menuModal}
width={600}
onCancel={() => setMenuModal(false)}
onOk={handleSaveMenu}
destroyOnClose
>
<Form form={menuForm} layout="vertical">
<Form.Item label="上级菜单" name="parentId">
<Select placeholder="无(一级菜单)">
<Option value={0}>无(一级菜单)</Option>
{topMenus.map(m => (
<Option key={m.menuId} value={m.menuId}>{m.menuName}</Option>
))}
</Select>
</Form.Item>
<Form.Item label="菜单名称" name="menuName" rules={[{ required: true }]}>
<Input placeholder="请输入菜单名称" />
</Form.Item>
<Form.Item label="路由地址" name="path">
<Input placeholder="/system/menu" />
</Form.Item>
<Form.Item label="显示排序" name="orderNum">
<InputNumber min={0} style={{ width: '100%' }} placeholder="数字越小越靠前" />
</Form.Item>
</Form>
</Modal>
{/* 图标选择弹窗 */}
{/*<Modal
title="选择菜单图标"
open={iconModal}
onCancel={() => setIconModal(false)}
footer={null}
width={500}
>
<Row gutter={[12, 12]}>
{iconList.map(iconName => (
<Col span={4} key={iconName}>
<Tooltip title={iconName}>
<Button
block
icon={renderIcon(iconName)}
onClick={() => handleSelectIcon(iconName)}
/>
</Tooltip>
</Col>
))}
</Row>
</Modal>*/}
</Card>
</div>
);
}

View File

@@ -0,0 +1,226 @@
import React, { useState, useEffect } from 'react';
import {
Card, Table, Button, Typography, Space, Modal, Form, message,
Input, Popconfirm, Select, InputNumber
} from 'antd';
import {
PlusOutlined, EditOutlined, DeleteOutlined
} from '@ant-design/icons';
import { addOrg, deleteOrg, getOrgList } from '../../api/organization';
const { Title } = Typography;
const { Option } = Select;
const AntdCard = Card as any;
export default function Organization() {
const [orgList, setOrgList] = useState([]);
const [modalVisible, setModalVisible] = useState(false);
const [form] = Form.useForm();
const [editRecord, setEditRecord] = useState(null);
const [messageApi, contextHolder] = message.useMessage();
// 统一分页
const [pagination, setPagination] = useState({
pageNum: 1,
pageSize: 10,
total: 0
});
// 获取组织列表(带分页)
const getOrgData = () => {
const params = {
pageNum: pagination.pageNum,
pageSize: pagination.pageSize
};
getOrgList(params).then(res => {
if (res.code === 200) {
setOrgList(res.rows || []);
setPagination({
...pagination,
total: res.total || res.rows?.length || 0
});
}
});
};
// 分页切换
const handleTableChange = (newPagination) => {
setPagination({
...pagination,
pageNum: newPagination.current,
pageSize: newPagination.pageSize
});
};
useEffect(() => {
getOrgData();
}, [pagination.pageNum, pagination.pageSize]);
// 打开新增
const handleAdd = () => {
form.resetFields();
setEditRecord(null);
form.setFieldsValue({
status: 0,
});
setModalVisible(true);
};
// 打开编辑
const handleEdit = (record) => {
setEditRecord(record);
form.setFieldsValue({ ...record });
setModalVisible(true);
};
// 删除
const handleDelete = (id) => {
deleteOrg({ id }).then(res => {
if (res.code == 200) {
messageApi.success('删除成功');
getOrgData();
} else {
messageApi.error(res.msg || '删除失败');
}
}).catch(() => {
messageApi.error('删除失败');
});
};
// 保存
const handleSave = () => {
form.validateFields().then(values => {
if (editRecord) {
const params = {
...values,
id: editRecord.id
};
addOrg(params).then(res => {
if (res.code === 200) {
messageApi.success('编辑成功');
getOrgData();
setModalVisible(false);
} else {
messageApi.error(res.msg || '编辑失败');
}
});
} else {
addOrg(values).then(res => {
if (res.code === 200) {
messageApi.success('新增成功');
getOrgData();
setModalVisible(false);
} else {
messageApi.error(res.msg || '新增失败');
}
});
}
});
};
const columns = [
{ title: '组织名称', dataIndex: 'orgName' },
{ title: '组织编码', dataIndex: 'orgCode' },
{ title: '负责人', dataIndex: 'manager' },
{ title: '联系电话', dataIndex: 'phone' },
{ title: '邮箱', dataIndex: 'email' },
//{
// title: '状态',
// dataIndex: 'status',
// render: (s) => (
// <span className={s == 1 ? 'text-green-600' : 'text-red-600'}>
// {s == 1 ? '正常' : '禁用'}
// </span>
// )
//},
{
title: '操作',
render: (_, r) => (
<Space>
<Button type="text" icon={<EditOutlined />} onClick={() => handleEdit(r)}>编辑</Button>
<Popconfirm title="确定删除该组织?" onConfirm={() => handleDelete(r.id)}>
<Button type="text" danger icon={<DeleteOutlined />}>删除</Button>
</Popconfirm>
</Space>
)
}
];
return (
<div style={{ padding: '20px' }}>
{contextHolder}
<AntdCard title="组织管理" style={{ borderRadius: 8 }}>
<div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
<Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
新增组织
</Button>
</div>
{/* 表格 + 统一分页 */}
<Table
rowKey="id"
columns={columns}
dataSource={orgList}
pagination={{
current: pagination.pageNum,
pageSize: pagination.pageSize,
total: pagination.total,
showSizeChanger: true,
showTotal: (total) => `共 ${total} 条`
}}
onChange={handleTableChange}
bordered
size="middle"
/>
</AntdCard>
<Modal
title={editRecord ? '编辑组织' : '新增组织'}
open={modalVisible}
onCancel={() => setModalVisible(false)}
onOk={handleSave}
width={550}
destroyOnClose
>
<Form form={form} layout="vertical">
<Form.Item name="orgName" label="组织名称" rules={[{ required: true }]}>
<Input placeholder="请输入组织名称" />
</Form.Item>
<Form.Item name="orgCode" label="组织编码" rules={[{ required: true }]}>
<Input placeholder="请输入组织编码" />
</Form.Item>
<Form.Item name="manager" label="负责人" rules={[{ required: true, message: '请输入负责人' }]}>
<Input placeholder="请输入负责人" />
</Form.Item>
<Form.Item name="phone" label="联系电话" rules={[{ required: true, message: '请输入联系电话' }]}>
<Input placeholder="请输入联系电话" />
</Form.Item>
<Form.Item name="email" label="邮箱">
<Input placeholder="请输入邮箱" />
</Form.Item>
<Form.Item name="address" label="地址">
<Input placeholder="请输入地址" />
</Form.Item>
<Form.Item name="remark" label="备注">
<Input.TextArea rows={3} placeholder="请输入备注" />
</Form.Item>
<Form.Item name="status" label="状态">
<Select>
<Option value={1}>正常</Option>
<Option value={0}>禁用</Option>
</Select>
</Form.Item>
</Form>
</Modal>
</div>
);
}

View File

@@ -0,0 +1,399 @@
import React, { useState, useEffect } from 'react';
import {
Card, Table, Button, Space, Modal, Form, Input, Popconfirm, Select,
Switch, Divider, Row, Col, Tag, message
} from 'antd';
import {
PlusOutlined, EditOutlined, DeleteOutlined, BgColorsOutlined
} from '@ant-design/icons';
import {
getStationList, saveSite, deleteSite,
getStationRegions, saveRegion, deleteRegion
} from '../../api/stationManage';
import { getOrgList } from '../../api/organization';
import { useSelector } from 'react-redux';
import { RootState } from '../../store';
const { Option } = Select;
export default function StationManage() {
const [stationList, setStationList] = useState([]);
const [currentStation, setCurrentStation] = useState(null);
const [regionList, setRegionList] = useState([]);
// 组织列表
const [orgList, setOrgList] = useState([]);
// 获取当前登录用户信息
const { userInfo } = useSelector((state: RootState) => state.user);
// 场站弹窗
const [modalVisible, setModalVisible] = useState(false);
const [form] = Form.useForm();
const [editRecord, setEditRecord] = useState(null);
// 分区弹窗
const [areaVisible, setAreaVisible] = useState(false);
const [regionForm] = Form.useForm();
const [editRegion, setEditRegion] = useState(null);
// 地图弹窗
const [mapVisible, setMapVisible] = useState(false);
const [messageApi, contextHolder] = message.useMessage();
// 分页状态
const [pagination, setPagination] = useState({
pageNum: 1,
pageSize: 10,
total: 0
});
// ====================== 获取组织列表(根据 userId 过滤) ======================
const getOrgData = () => {
const params = {
pageNum: 1,
pageSize: 9999,
userId: userInfo?.userId
};
getOrgList(params).then(res => {
if (res.code === 200) {
setOrgList(res.rows || []);
}
});
};
// ====================== 获取场站列表(分页) ======================
const getStationData = () => {
const params = {
pageNum: pagination.pageNum,
pageSize: pagination.pageSize,
orgId: userInfo?.orgId,
};
getStationList(params).then(res => {
if (res.code === 200) {
setStationList(res.rows || []);
setPagination({
...pagination,
total: res.total || res.rows?.length || 0
});
}
});
};
// 切换分页
const handleTableChange = (newPagination) => {
setPagination({
...pagination,
pageNum: newPagination.current,
pageSize: newPagination.pageSize
});
};
// 初始化加载
useEffect(() => {
getStationData();
getOrgData();
}, [pagination.pageNum, pagination.pageSize]);
// ====================== 新增 / 编辑 场站 ======================
const handleAdd = () => {
form.resetFields();
setEditRecord(null);
form.setFieldsValue({ status: 1 });
setModalVisible(true);
};
const handleEdit = (record) => {
setEditRecord(record);
form.setFieldsValue({
...record,
status: record.status === 1
});
setModalVisible(true);
};
const handleSave = () => {
form.validateFields().then(values => {
const params = {
...values,
status: values.status ? 1 : 0
};
if (editRecord) {
params.id = editRecord.id;
}
saveSite(params).then(res => {
if (res.code === 200) {
messageApi.success(editRecord ? '编辑成功' : '新增成功');
getStationData();
setModalVisible(false);
} else {
messageApi.error(res.msg || '保存失败');
}
});
});
};
// ====================== 删除场站 ======================
const handleDelete = (id) => {
deleteSite([id]).then(res => {
if (res.code === 200) {
messageApi.success('删除成功');
getStationData();
} else {
messageApi.error(res.msg || '删除失败');
}
});
};
// ====================== 分区管理 ======================
const handleOpenArea = async (record) => {
setCurrentStation(record);
setAreaVisible(true);
setEditRegion(null);
regionForm.resetFields();
const res = await getStationRegions({ id: record.id });
if (res.code === 200) setRegionList(res.data || []);
};
const handleSaveRegion = () => {
regionForm.validateFields().then(values => {
const params = {
...values,
siteId: currentStation.id,
status: values.status ? 1 : 0
};
if (editRegion) params.id = editRegion.id;
saveRegion(params).then(res => {
if (res.code === 200) {
messageApi.success('保存成功');
getStationRegions({ id: currentStation.id }).then(r => {
setRegionList(r.data || []);
});
setEditRegion(null);
regionForm.resetFields();
}
});
});
};
const handleDeleteRegion = (id) => {
deleteRegion([id]).then(res => {
if (res.code === 200) {
messageApi.success('删除成功');
setRegionList(regionList.filter(x => x.id !== id));
}
});
};
// ====================== 边界绘制 ======================
const handleOpenMap = (record) => {
setCurrentStation(record);
setMapVisible(true);
};
// ====================== 表格列 ======================
const columns = [
{ title: '场站名称', dataIndex: 'siteName' },
{ title: '场站编号', dataIndex: 'siteCode' },
{
title: '所属组织',
dataIndex: 'orgId',
render: (orgId) => {
const org = orgList.find(item => item.id == orgId);
return org ? org.orgName : '—';
}
},
{ title: '地址', dataIndex: 'address' },
//{
// title: '状态',
// dataIndex: 'status',
// render: s => s === 1 ? <Tag color="green">启用</Tag> : <Tag color="red">停用</Tag>
//},
{
title: '操作',
width: 400,
render: (_, record) => (
<Space wrap size="small">
<Button icon={<EditOutlined />} onClick={() => handleEdit(record)}>编辑</Button>
<Button icon={<BgColorsOutlined />} onClick={() => handleOpenArea(record)}>分区设置</Button>
<Button onClick={() => handleOpenMap(record)}>边界绘制</Button>
<Popconfirm title="确定删除?" onConfirm={() => handleDelete(record.id)}>
<Button danger>删除</Button>
</Popconfirm>
</Space>
)
}
];
return (
<div style={{ padding: '20px' }}>
{contextHolder}
<Card title="场站管理" style={{ borderRadius: 8 }}>
<div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
<Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
新增场站
</Button>
</div>
<Table
rowKey="id"
columns={columns}
dataSource={stationList}
pagination={{
current: pagination.pageNum,
pageSize: pagination.pageSize,
total: pagination.total,
showSizeChanger: true,
showTotal: (total) => `共 ${total} 条`
}}
onChange={handleTableChange}
bordered
size="middle"
/>
</Card>
{/* ====================== 场站弹窗 ====================== */}
<Modal
title={editRecord ? '编辑场站' : '新增场站'}
open={modalVisible}
width={650}
onCancel={() => setModalVisible(false)}
onOk={handleSave}
destroyOnClose
>
<Form form={form} layout="vertical">
<Row gutter={16}>
<Col span={12}>
<Form.Item name="siteName" label="场站名称" rules={[{ required: true }]}>
<Input placeholder="请输入" />
</Form.Item>
</Col>
<Col span={12}>
<Form.Item name="siteCode" label="场站编号" rules={[{ required: true }]}>
<Input placeholder="唯一编码" />
</Form.Item>
</Col>
</Row>
<Form.Item name="orgId" label="所属组织" rules={[{ required: true }]}>
<Select placeholder="请选择所属组织" allowClear>
{orgList.map(item => (
// ✅ 这里修复了!原来是 item.orgId,现在是 item.id
<Option key={item.id} value={item.id}>
{item.orgName}
</Option>
))}
</Select>
</Form.Item>
<Row gutter={16}>
<Col span={12}>
<Form.Item name="longitude" label="经度">
<Input placeholder="经度" />
</Form.Item>
</Col>
<Col span={12}>
<Form.Item name="latitude" label="纬度">
<Input placeholder="纬度" />
</Form.Item>
</Col>
</Row>
<Form.Item name="address" label="详细地址">
<Input placeholder="地址" />
</Form.Item>
<Form.Item name="remark" label="备注">
<Input.TextArea rows={3} />
</Form.Item>
<Form.Item name="status" label="状态" valuePropName="checked">
<Switch checkedChildren="启用" unCheckedChildren="停用" />
</Form.Item>
</Form>
</Modal>
{/* ====================== 分区弹窗 ====================== */}
<Modal
title={`【${currentStation?.siteName}】分区设置`}
open={areaVisible}
width={650}
onCancel={() => setAreaVisible(false)}
footer={null}
>
<Form form={regionForm} layout="vertical" style={{ marginBottom: 16 }}>
<Row gutter={16}>
<Col span={12}>
<Form.Item name="regionName" label="分区名称" rules={[{ required: true }]}>
<Input />
</Form.Item>
</Col>
<Col span={12}>
<Form.Item name="regionCode" label="分区编码" rules={[{ required: true }]}>
<Input />
</Form.Item>
</Col>
</Row>
<Row gutter={16}>
<Col span={12}>
<Form.Item name="type" label="分区类型">
<Select><Option value="清扫区">清扫区</Option><Option value="巡检区">巡检区</Option></Select>
</Form.Item>
</Col>
<Col span={12}>
<Form.Item name="status" label="状态" valuePropName="checked">
<Switch checkedChildren="启用" unCheckedChildren="停用" />
</Form.Item>
</Col>
</Row>
<Form.Item name="remark" label="备注"><Input.TextArea rows={2} /></Form.Item>
<Button type="primary" onClick={handleSaveRegion}>保存分区</Button>
</Form>
<Table
size="middle"
rowKey="id"
pagination={false}
bordered
columns={[
{ title: '分区名称', dataIndex: 'regionName' },
{ title: '编码', dataIndex: 'regionCode' },
{ title: '类型', dataIndex: 'type' },
{
title: '状态', render: r => r.status === 1 ? '启用' : '停用'
},
{
title: '操作', render: (_, r) => (
<Space>
<Button onClick={() => { setEditRegion(r); regionForm.setFieldsValue(r); }}>编辑</Button>
<Button danger onClick={() => handleDeleteRegion(r.id)}>删除</Button>
</Space>
)
}
]}
dataSource={regionList}
/>
</Modal>
{/* ====================== 地图绘制 ====================== */}
<Modal
title={`【${currentStation?.siteName}】边界绘制`}
open={mapVisible}
width={800}
onCancel={() => setMapVisible(false)}
footer={null}
>
<div style={{ height: 400, background: '#f5f5f5', borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column' }}>
地图区域绘制(可自行接入高德/百度地图)
<Space style={{ marginTop: 20 }}>
<Button type="primary">开始绘制</Button>
<Button>保存边界</Button>
</Space>
</div>
</Modal>
</div>
);
}

View File

@@ -0,0 +1,723 @@
import React, { useState, useEffect } from 'react';
import {
Layout, Tabs, Card, Row, Col, Button, Typography, Space, Modal, Form, Tree, message,
Input, Popconfirm, Divider, InputNumber, Pagination, Table, Select,
Tag, Checkbox, App
} from 'antd';
import {
PlusOutlined, EditOutlined, DeleteOutlined, UserOutlined
} from '@ant-design/icons';
import { getMenuList } from '../../api/mune';
import { buildPermTree, buildTreeFromFlat } from '../../lib/utils';
import { addRole, deleteRole, editRoleApi, getRoleAllocate, getRoleDetailById, getRoleList } from '../../api/role';
import { addUser, deleteUser, editUser, getUser } from '../../api/user';
import EmptyData from '../Empty';
import { useSelector } from 'react-redux';
import { RootState } from '../../store';
import { getOrgList } from '../../api/organization';
import { getSiteByOrgId } from '../../api/stationManage';
const { Text } = Typography;
const { TabPane } = Tabs;
const AntdCard = Card as any;
export default function UserRolePage() {
// ====================== 全局提示 ======================
const [messageApi, contextHolder] = message.useMessage();
const { modal } = App.useApp();
// ====================== 角色管理状态 ======================
const [roles, setRoles] = useState([]);
const [menuTree, setMenuTree] = useState([]);
const [checkedKeys, setCheckedKeys] = useState<number[]>([]);
const [roleModalVisible, setRoleModalVisible] = useState(false);
const [roleForm] = Form.useForm();
const [editRole, setEditRole] = useState(null);
const [selectedRoleIds, setSelectedRoleIds] = useState<number[]>([]);
// ====================== 用户管理状态 ======================
const [userList, setUserList] = useState([]);
const [modalVisible, setModalVisible] = useState(false);
const [form] = Form.useForm();
const [currentUser, setCurrentUser] = useState(null);
const [rolesOption, setRolesOption] = useState([]);
const [selectedUserIds, setSelectedUserIds] = useState<number[]>([]);
const { userInfo } = useSelector((state: RootState) => state.user);
const [orgList, setOrgList] = useState([]);
const [siteList, setSiteList] = useState([]);
// 全局缓存:所有场站(用于表格展示)
const [allSiteList, setAllSiteList] = useState([]);
const [showSite, setShowSite] = useState(true);
const [siteDisabled, setSiteDisabled] = useState(false);
const isEditSelf = currentUser?.userId == userInfo?.userId;
// ====================== 分页 ======================
const [rolePagination, setRolePagination] = useState({
pageNum: 1, pageSize: 12, total: 0
});
const [userPagination, setUserPagination] = useState({
pageNum: 1, pageSize: 10, total: 0
});
// 获取组织列表
const getOrgData = async () => {
const res = await getOrgList({ pageNum: 1, pageSize: 9999, userId: userInfo?.userId });
if (res.code === 200) {
const orgs = res.rows || [];
setOrgList(orgs);
// 预加载所有组织下的场站,缓存
await loadAllSite(orgs);
}
};
// 预加载全部场站
const loadAllSite = async (orgs) => {
let totalSite = [];
for (const org of orgs) {
const res = await getSiteByOrgId({ id: org.id }).catch(() => ({ code: 200, data: [] }));
if (res.code === 200) {
const list = res.data || res.rows || [];
totalSite = [...totalSite, ...list];
}
}
setAllSiteList(totalSite);
};
// 根据组织ID获取场站(弹窗下拉用)
const getSiteByOrg = (orgId) => {
if (!orgId) {
setSiteList([]);
return;
}
const list = allSiteList.filter(item => item.orgId == orgId);
setSiteList(list);
};
// 获取角色列表
const getRoleData = () => {
const params = { pageNum: rolePagination.pageNum, pageSize: rolePagination.pageSize };
getRoleList(params).then(res => {
if (res.code === 200) {
let sortedRoles = (res.data || []).sort((a, b) => (a.roleSort || 999) - (b.roleSort || 999));
setRoles(sortedRoles);
setRolePagination({
...rolePagination,
total: res.total || res.data?.length || 0
});
}
});
};
// 获取菜单树
const getMenuData = () => {
getMenuList({ pageNum: 1, pageSize: 1000 }).then(res => {
if (res.code == 200) {
const treeData = buildTreeFromFlat(res.rows || []);
setMenuTree(buildPermTree(treeData));
}
});
};
// 获取用户列表
const getUserData = () => {
const params = {
pageNum: userPagination.pageNum,
pageSize: userPagination.pageSize,
orgId: userInfo?.orgId,
siteId: userInfo?.siteId,
};
getUser(params).then(res => {
if (res.code === 200) {
setUserList(res.rows || []);
setUserPagination({
...userPagination,
total: res.total || res.rows?.length || 0
});
}
});
};
// 角色下拉选项
const getRoleForSelect = () => {
getRoleAllocate({ pageNum: 1, pageSize: 1000 }).then(res => {
if (res.code === 200) {
let sortedRoles = (res.data || []).sort((a, b) => (a.roleSort || 999) - (b.roleSort || 999));
setRolesOption(sortedRoles);
}
});
};
// 初始化
useEffect(() => {
getMenuData();
getOrgData();
}, []);
useEffect(() => {
getRoleData();
}, [rolePagination.pageNum, rolePagination.pageSize]);
useEffect(() => {
getUserData();
getRoleForSelect();
}, [userPagination.pageNum, userPagination.pageSize]);
// ====================== 角色操作 ======================
const handleAddRole = () => {
roleForm.resetFields();
setCheckedKeys([]);
setEditRole(null);
roleForm.setFieldsValue({ status: true, roleSort: 1, roleLevel: 1 });
setRoleModalVisible(true);
};
const handleEditRole = (record) => {
setEditRole(record);
roleForm.setFieldsValue({ ...record, roleLevel: record.roleLevel });
const getAllLeafKeys = (tree) => {
let leaves: number[] = [];
function traverse(nodes: any[]) {
nodes.forEach(node => {
if (!node.children || node.children.length === 0) {
leaves.push(node.key);
} else traverse(node.children);
});
}
traverse(tree);
return leaves;
};
const leafKeys = getAllLeafKeys(menuTree);
const leafChecked = (record.menuIds || []).map(Number).filter(id => leafKeys.includes(id));
setCheckedKeys(leafChecked);
setRoleModalVisible(true);
};
const handleDeleteRole = (roleId: number) => {
deleteRole([roleId]).then(res => {
if (res.code == 200) {
messageApi.success('删除成功');
getRoleData();
} else messageApi.error(res.msg || '删除失败');
});
};
const handleBatchDeleteRoles = () => {
if (selectedRoleIds.length == 0) return messageApi.warning('请选择要删除的角色');
modal.confirm({
title: '批量删除角色',
content: `确定要删除已选中的 ${selectedRoleIds.length} 个角色吗?`,
okText: '确定删除',
cancelText: '取消',
okType: 'danger',
onOk: () => {
deleteRole(selectedRoleIds).then(res => {
if (res.code === 200) {
messageApi.success('批量删除成功');
setSelectedRoleIds([]);
getRoleData();
} else messageApi.error(res.msg || '删除失败');
});
}
});
};
const handleSaveRole = () => {
roleForm.validateFields().then(values => {
const getParentKeys = (key: number, tree: any[]) => {
for (let node of tree) {
if (node.key === key) return [node.key];
if (node.children) {
const res = getParentKeys(key, node.children);
if (res.length > 0) return [...res, node.key];
}
}
return [];
};
let allMenuIds: number[] = [];
checkedKeys.forEach(key => {
allMenuIds.push(...getParentKeys(key, menuTree));
});
allMenuIds = [...new Set(allMenuIds)];
const params = {
...values,
menuIds: allMenuIds,
status: 1,
roleSort: values.roleSort || 1,
roleLevel: values.roleLevel
};
if (editRole) params.roleId = editRole.roleId;
const api = editRole ? editRoleApi : addRole;
api(params).then(res => {
if (res.code == 200) {
messageApi.success(editRole ? '编辑成功' : '新增成功');
setRoleModalVisible(false);
getRoleData();
getRoleForSelect();
} else messageApi.error(res.msg || '保存失败');
});
});
};
// ====================== 用户操作 ======================
// 新增用户
const handleAddUser = () => {
setCurrentUser(null);
setShowSite(true);
setSiteList([]);
form.resetFields();
const defaultOrgId = userInfo?.orgId ?? '';
const defaultSiteId = userInfo?.siteId ?? '';
form.setFieldsValue({
orgId: defaultOrgId,
siteId: defaultSiteId
});
setSiteDisabled(!!defaultSiteId);
if (defaultOrgId) {
getSiteByOrg(defaultOrgId);
}
setModalVisible(true);
};
// 编辑用户
const handleEditUser = (record: any) => {
setCurrentUser(record);
const userRoleId = record.roles?.[0]?.roleId ?? record.roleId;
const targetRole = rolesOption.find(item => String(item.roleId) === String(userRoleId));
form.setFieldsValue({
...record,
roleIds: targetRole?.roleId ?? userRoleId,
});
const isOrgAdmin = targetRole?.roleKey === 'manager';
setShowSite(!isOrgAdmin);
setSiteList([]);
if (record.orgId) {
getSiteByOrg(record.orgId);
setTimeout(() => {
form.setFieldsValue({ siteId: record.siteId });
}, 200);
}
setModalVisible(true);
};
// 重置密码
const handleResetPassword = (user: any) => {
modal.confirm({
title: '重置密码',
content: '确定将密码重置为 123456 吗?',
okText: '确认',
cancelText: '取消',
onOk: () => {
editUser({ userId: user.userId, password: '123456' }).then(res => {
res.code === 200 ? messageApi.success('密码已重置为:123456') : messageApi.error('重置失败');
});
}
});
};
const handleDeleteUser = (userId: number) => {
deleteUser(userId).then(res => {
if (res.code === 200) {
messageApi.success('删除成功');
getUserData();
} else messageApi.error(res.msg || '删除失败');
});
};
const handleBatchDeleteUsers = () => {
if (selectedUserIds.length === 0) return messageApi.warning('请选择要删除的用户');
modal.confirm({
title: '批量删除用户',
content: `确定要删除已选中的 ${selectedUserIds.length} 个用户吗?`,
okText: '确定删除',
cancelText: '取消',
okType: 'danger',
onOk: () => {
Promise.all(selectedUserIds.map(id => deleteUser(id))).then(() => {
messageApi.success('批量删除成功');
setSelectedUserIds([]);
getUserData();
});
}
});
};
const handleSaveUser = () => {
form.validateFields().then(values => {
const params = {
...values,
roleIds: [values.roleIds].flat()
};
if (currentUser) {
params.userId = currentUser.userId;
delete params.password;
}
const api = currentUser ? editUser : addUser;
api(params).then(res => {
if (res.code === 200) {
messageApi.success(currentUser ? '编辑成功' : '新增成功');
setModalVisible(false);
getUserData();
} else {
messageApi.error(res.msg || '保存失败');
}
});
});
};
// ====================== 页面渲染 ======================
return (
<div style={{
height: '100%',
maxHeight: 'calc(100vh - 64px)',
overflowY: 'auto',
scrollbarWidth: 'none',
msOverflowStyle: 'none',
padding: '20px',
background: '#f5f7fa'
}}>
{contextHolder}
<AntdCard style={{ borderRadius: 12, boxShadow: '0 2px 10px rgba(0,0,0,0.06)' }}>
<Tabs defaultActiveKey="user" type="card" size="large" style={{ marginBottom: 20 }}>
{/* 用户管理 */}
<TabPane tab="用户管理" key="user">
<div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
{selectedUserIds.length > 0 && (
<Button danger onClick={handleBatchDeleteUsers}>
批量删除(已选 {selectedUserIds.length} 项)
</Button>
)}
<Button type="primary" icon={<PlusOutlined />} onClick={handleAddUser}>新增用户</Button>
</div>
<Table
rowKey="userId"
rowSelection={{
type: 'checkbox',
onChange: (selectedRowKeys) => setSelectedUserIds(selectedRowKeys)
}}
columns={[
{ title: '用户账号', dataIndex: 'userName' },
{ title: '用户昵称', dataIndex: 'nickName' },
{ title: '手机号', dataIndex: 'phonenumber' },
{ title: '邮箱', dataIndex: 'email' },
// 所属机构
{
title: '所属机构',
render: (_, r) => {
const org = orgList.find(o => o.id == r.orgId);
return org ? org.orgName : '—';
}
},
// 所属场站(纯缓存匹配,无接口)
{
title: '所属场站',
render: (_, r) => {
if (!r.siteId) return '—';
const site = allSiteList.find(s => s.id == r.siteId);
return site ? site.siteName : '—';
}
},
{
title: '角色',
render: (_, r) => (r.roles || []).map(i => (
<Tag color="blue" key={i.roleId}>{i?.roleKey}</Tag>
))
},
{
title: '状态',
render: (_, s) => s.status === '0'
? <Tag color="green">正常</Tag>
: <Tag color="red">停用</Tag>
},
{
title: '操作',
render: (_, r) => (
<Space>
<Button type="text" icon={<EditOutlined style={{ color: '#1890ff' }} />} onClick={() => handleEditUser(r)}>编辑</Button>
<Popconfirm onConfirm={() => handleDeleteUser(r.userId)} title="确定删除该用户吗?">
<Button type="text" danger icon={<DeleteOutlined />}>删除</Button>
</Popconfirm>
<Button type="text" icon={<UserOutlined style={{ color: '#faad14' }} />} onClick={() => { setCurrentUser(r); handleResetPassword(r); }}>重置密码</Button>
</Space>
)
}
]}
dataSource={userList}
pagination={{
current: userPagination.pageNum,
pageSize: userPagination.pageSize,
total: userPagination.total,
showSizeChanger: true,
showTotal: t => `共 ${t} 条`
}}
onChange={(p) => setUserPagination({ ...userPagination, pageNum: p.current!, pageSize: p.pageSize! })}
bordered
size="middle"
/>
</TabPane>
{/* 角色管理 */}
{userInfo?.userId == 1 && (
<TabPane tab="角色管理" key="role">
<div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
{selectedRoleIds.length > 0 && (
<Button danger onClick={handleBatchDeleteRoles}>
批量删除(已选 {selectedRoleIds.length} 项)
</Button>
)}
<Button type="primary" icon={<PlusOutlined />} onClick={handleAddRole}>新增角色</Button>
</div>
<Row gutter={[16, 16]}>
{roles.length > 0 ? roles.map(r => (
<Col xs={24} sm={12} md={8} lg={6} key={r.roleId}>
<AntdCard
hoverable
style={{ borderRadius: 10, position: 'relative' }}
actions={[
<Button type="text" icon={<EditOutlined />} onClick={() => handleEditRole(r)}>编辑</Button>,
<Popconfirm onConfirm={() => handleDeleteRole(r.roleId)} title="确定删除?">
<Button type="text" danger>删除</Button>
</Popconfirm>
]}
>
<div style={{ position: 'absolute', top: 10, right: 10 }}>
<Checkbox
checked={selectedRoleIds.includes(r.roleId)}
onChange={(e) => {
if (e.target.checked) {
setSelectedRoleIds([...selectedRoleIds, r.roleId]);
} else {
setSelectedRoleIds(selectedRoleIds.filter(id => id !== r.roleId));
}
}}
/>
</div>
<Card.Meta
title={<strong>{r.roleName}</strong>}
description={
<Space direction="vertical" size={2}>
<Text type="secondary">权限:{r.roleKey}</Text>
<Text type="secondary">等级:{r.roleLevel || '-'}</Text>
{/*{r.roleKey == "admin1" && <Tag color="red">超级管理员</Tag>}*/}
</Space>
}
/>
</AntdCard>
</Col>
)) : <EmptyData height={260} />}
</Row>
<div style={{ textAlign: 'right', marginTop: 20 }}>
<Pagination
current={rolePagination.pageNum}
pageSize={rolePagination.pageSize}
total={rolePagination.total}
showSizeChanger
pageSizeOptions={['12', '24', '36', '48', '60']}
showTotal={(t) => `共 ${t} 条`}
onChange={(page, pageSize) => {
setRolePagination({
...rolePagination,
pageNum: page,
pageSize: pageSize,
});
}}
/>
</div>
</TabPane>
)}
</Tabs>
</AntdCard>
{/* 角色弹窗 */}
<Modal
title={editRole ? '编辑角色' : '新增角色'}
open={roleModalVisible}
onCancel={() => setRoleModalVisible(false)}
onOk={handleSaveRole}
width={560}
>
<Form form={roleForm} layout="vertical">
<Row gutter={16}>
<Col span={12}>
<Form.Item name="roleName" label="角色名称" rules={[{ required: true }]}>
<Input />
</Form.Item>
</Col>
<Col span={12}>
<Form.Item name="roleKey" label="权限标识" rules={[{ required: true }]}>
<Input />
</Form.Item>
</Col>
</Row>
<Row gutter={16}>
<Col span={12}>
<Form.Item name="roleSort" label="排序">
<InputNumber style={{ width: '100%' }} min={1} max={100} />
</Form.Item>
</Col>
<Col span={12}>
<Form.Item name="roleLevel" label="角色等级" rules={[{ required: true, message: '请输入角色等级' }]}>
<InputNumber style={{ width: '100%' }} placeholder="1~100" min={1} max={100} />
</Form.Item>
</Col>
</Row>
{userInfo?.roleId == 23 && (
<>
<Divider>菜单权限</Divider>
<Tree
checkable
treeData={menuTree}
checkedKeys={checkedKeys}
onCheck={setCheckedKeys}
defaultExpandAll
checkStrictly={false}
/>
</>
)}
</Form>
</Modal>
{/* 用户弹窗 */}
<Modal
title={currentUser ? '编辑用户' : '新增用户'}
open={modalVisible}
onCancel={() => setModalVisible(false)}
onOk={handleSaveUser}
width={680}
destroyOnClose
>
<Form form={form} layout="vertical">
<Row gutter={16}>
<Col span={12}><Form.Item name="userName" label="账号" rules={[{ required: true }]}><Input /></Form.Item></Col>
<Col span={12}><Form.Item name="nickName" label="昵称" rules={[{ required: true }]}><Input /></Form.Item></Col>
</Row>
<Row gutter={16}>
<Col span={12}><Form.Item name="phonenumber" label="手机"><Input /></Form.Item></Col>
<Col span={12}><Form.Item name="email" label="邮箱"><Input /></Form.Item></Col>
</Row>
<Row gutter={16}>
<Col span={12}>
<Form.Item name="password" label="密码">
<Input.Password placeholder={currentUser ? "编辑不显示,重置为123456" : "请输入密码"} />
</Form.Item>
</Col>
<Col span={12}>
<Form.Item name="language" label="语言">
<Select>
<Select.Option value="zh-CN">中文</Select.Option>
<Select.Option value="en">英语</Select.Option>
</Select>
</Form.Item>
</Col>
</Row>
{/* ====== 自动适应布局:隐藏角色时,状态自动占满一行 ====== */}
<Row gutter={16}>
{!isEditSelf ? (
<>
<Col span={12}>
<Form.Item name="roleIds" label="分配角色" rules={[{ required: true }]}>
<Select
placeholder="选择角色"
key={rolesOption.length}
onChange={(val) => {
const role = rolesOption.find(item => String(item.roleId) === String(val));
if (role?.roleKey === 'manager') {
setShowSite(false);
form.setFieldsValue({ siteId: null });
} else {
setShowSite(true);
}
}}
>
{rolesOption.map(i => (
<Select.Option key={i.roleId} value={i.roleId}>{i.roleName}</Select.Option>
))}
</Select>
</Form.Item>
</Col>
<Col span={12}>
<Form.Item name="status" label="状态" initialValue="0">
<Select>
<Select.Option value="0">正常</Select.Option>
<Select.Option value="1">停用</Select.Option>
</Select>
</Form.Item>
</Col>
</>
) : (
// 编辑自己 → 状态占满一行 span=24
<Col span={24}>
<Form.Item name="status" label="状态" initialValue="0">
<Select>
<Select.Option value="0">正常</Select.Option>
<Select.Option value="1">停用</Select.Option>
</Select>
</Form.Item>
</Col>
)}
</Row>
<Row gutter={16}>
<Col span={12}>
<Form.Item name="sex" label="性别" initialValue="2">
<Select>
<Select.Option value="0">男</Select.Option>
<Select.Option value="1">女</Select.Option>
<Select.Option value="2">未知</Select.Option>
</Select>
</Form.Item>
</Col>
<Col span={12}>
<Form.Item name="orgId" label="所属组织">
<Select
placeholder="请选择组织"
allowClear
onChange={(val) => {
getSiteByOrg(val);
form.setFieldsValue({ siteId: null });
}}
>
{orgList.map(item => (
<Select.Option key={item.id} value={item.id}>{item.orgName}</Select.Option>
))}
</Select>
</Form.Item>
</Col>
{showSite && siteList.length > 0 && (
<Col span={12}>
<Form.Item name="siteId" label="所属场站">
<Select
placeholder="请选择场站"
allowClear
disabled={siteDisabled}
>
{siteList.map(item => (
<Select.Option key={item.id} value={item.id}>{item.siteName}</Select.Option>
))}
</Select>
</Form.Item>
</Col>
)}
</Row>
</Form>
</Modal>
</div>
);
}

View File

@@ -0,0 +1,183 @@
import React, { useState } from 'react';
import {
Card, Table, Tag, Badge, Space, Button,
Modal, Descriptions, Form, Select, Input
} from 'antd';
import { EyeOutlined } from '@ant-design/icons';
const AntdCard = Card as any;
const { Option } = Select;
const { Search } = Input;
// 模拟历史数据
const mockHistory = [
{ id: 1, deviceName: '1#环境传感器', level: 'warn', content: '温度超过阈值 62℃', time: '2026-05-07 08:10:22', status: 'processed' },
{ id: 2, deviceName: '2#阵列区球机', level: 'error', content: '视频信号丢失', time: '2026-05-06 15:30:11', status: 'closed' },
{ id: 3, deviceName: '3#电池供电设备', level: 'info', content: '电量低于20%', time: '2026-05-05 10:20:15', status: 'processed' },
{ id: 4, deviceName: '1#阵列区球机', level: 'error', content: '存储设备故障', time: '2026-05-04 23:10:00', status: 'closed' },
];
const AlarmHistory = () => {
// 详情弹窗
const [detailVisible, setDetailVisible] = useState(false);
const [currentAlarm, setCurrentAlarm] = useState<any>(null);
// 搜索筛选
const [list, setList] = useState(mockHistory);
const [filteredList, setFilteredList] = useState(mockHistory);
const [timeRange, setTimeRange] = useState('today');
const [deviceType, setDeviceType] = useState('all');
// 打开详情
const showDetail = (record: any) => {
setCurrentAlarm(record);
setDetailVisible(true);
};
// 统一筛选逻辑
const handleFilter = (searchValue = '') => {
let res = list.filter(item => {
// 时间筛选
const timeMatch = timeRange === 'all' || true; // 后端可替换
// 设备筛选
const deviceMatch = deviceType === 'all' || item.deviceName.includes(deviceType);
// 搜索筛选
const searchMatch = !searchValue ||
item.deviceName.includes(searchValue) ||
item.content.includes(searchValue) ||
item.level.includes(searchValue);
return timeMatch && deviceMatch && searchMatch;
});
setFilteredList(res);
};
// 搜索
const handleSearch = (value: string) => {
handleFilter(value);
};
// 表格列
const columns = [
{ title: '告警时间', dataIndex: 'time', width: 180 },
{ title: '设备名称', dataIndex: 'deviceName' },
{
title: '告警级别',
render: (row: any) => {
const color = row.level === 'warn' ? 'orange' : row.level === 'error' ? 'red' : 'blue';
const text = row.level === 'warn' ? '警告' : row.level === 'error' ? '严重' : '提示';
return <Tag color={color}>{text}</Tag>;
}
},
{ title: '告警内容', dataIndex: 'content' },
{
title: '处理状态',
render: (row: any) => {
const statusMap = {
processed: { status: 'success', text: '已处理' },
closed: { status: 'default', text: '已关闭' },
};
const s = statusMap[row.status] || { status: 'default', text: '未知' };
return <Badge status={s.status as any} text={s.text} />;
}
},
{
title: '操作',
render: (_: any, record: any) => (
<Button type="link" icon={<EyeOutlined />} onClick={() => showDetail(record)}>
查看详情
</Button>
)
}
];
return (
<div style={{ padding: 24 }}>
<AntdCard title="告警历史">
{/* 统一筛选栏:搜索 + 时间 + 设备 */}
<Space wrap size={16} style={{ marginBottom: 16, width: '100%' }}>
<Search
placeholder="搜索设备/内容/级别"
style={{ width: 260 }}
onSearch={handleSearch}
/>
<Form layout="inline">
<Form.Item label="时间范围">
<Select
value={timeRange}
style={{ width: 160 }}
onChange={(val) => {
setTimeRange(val);
handleFilter();
}}
>
<Option value="today">今日</Option>
<Option value="yesterday">昨日</Option>
<Option value="week">近7天</Option>
<Option value="month">本月</Option>
<Option value="all">全部</Option>
</Select>
</Form.Item>
<Form.Item label="设备类型">
<Select
value={deviceType}
style={{ width: 160 }}
onChange={(val) => {
setDeviceType(val);
handleFilter();
}}
>
<Option value="all">全部设备</Option>
<Option value="传感器">传感器</Option>
<Option value="球机">球机</Option>
<Option value="电池">电池设备</Option>
</Select>
</Form.Item>
</Form>
</Space>
{/* 表格 */}
<Table
rowKey="id"
columns={columns}
dataSource={filteredList}
pagination={{ pageSize: 10 }}
/>
</AntdCard>
{/* 详情弹窗 */}
<Modal
title="告警历史详情"
open={detailVisible}
onCancel={() => setDetailVisible(false)}
footer={null}
width={520}
>
{currentAlarm && (
<Descriptions column={1} bordered>
<Descriptions.Item label="告警时间">{currentAlarm.time}</Descriptions.Item>
<Descriptions.Item label="设备名称">{currentAlarm.deviceName}</Descriptions.Item>
<Descriptions.Item label="告警内容">{currentAlarm.content}</Descriptions.Item>
<Descriptions.Item label="告警级别">
<Tag color={currentAlarm.level === 'warn' ? 'orange' : currentAlarm.level === 'error' ? 'red' : 'blue'}>
{currentAlarm.level === 'warn' ? '警告' : currentAlarm.level === 'error' ? '严重' : '提示'}
</Tag>
</Descriptions.Item>
<Descriptions.Item label="处理状态">
<Badge
status={currentAlarm.status === 'processed' ? 'success' : 'default'}
text={currentAlarm.status === 'processed' ? '已处理' : '已关闭'}
/>
</Descriptions.Item>
</Descriptions>
)}
</Modal>
</div>
);
};
export default AlarmHistory;

View File

@@ -0,0 +1,21 @@
import React from 'react';
import { Card, Row, Col, Space, Empty } from 'antd';
import { AlertOutlined, CloseCircleOutlined, ExclamationCircleOutlined, CheckCircleOutlined } from '@ant-design/icons';
const AntdCard = Card as any;
const AlarmOverview = () => {
return (
<div style={{ padding: 24 }}>
<Row gutter={16} style={{ marginBottom: 24 }}>
<Col span={6}><AntdCard size="small"><Space><div style={{ background: '#e6f4ff', borderRadius: 8, padding: 8 }}><AlertOutlined style={{ color: '#1677ff', fontSize: 20 }} /></div><div><div style={{ fontSize: 13, color: '#666' }}>告警总数</div><div style={{ fontWeight: 600 }}>45</div></div></Space></AntdCard></Col>
<Col span={6}><AntdCard size="small"><Space><div style={{ background: '#fff2f0', borderRadius: 8, padding: 8 }}><CloseCircleOutlined style={{ color: '#ff4d4f', fontSize: 20 }} /></div><div><div style={{ fontSize: 13, color: '#666' }}>严重告警</div><div style={{ fontWeight: 600 }}>12</div></div></Space></AntdCard></Col>
<Col span={6}><AntdCard size="small"><Space><div style={{ background: '#fff7e6', borderRadius: 8, padding: 8 }}><ExclamationCircleOutlined style={{ color: '#fa8c16', fontSize: 20 }} /></div><div><div style={{ fontSize: 13, color: '#666' }}>警告告警</div><div style={{ fontWeight: 600 }}>20</div></div></Space></AntdCard></Col>
<Col span={6}><AntdCard size="small"><Space><div style={{ background: '#f6ffed', borderRadius: 8, padding: 8 }}><CheckCircleOutlined style={{ color: '#52c41a', fontSize: 20 }} /></div><div><div style={{ fontSize: 13, color: '#666' }}>已处理</div><div style={{ fontWeight: 600 }}>13</div></div></Space></AntdCard></Col>
</Row>
<AntdCard title="告警地图"><Empty description="告警地图(可接入GIS)" /></AntdCard>
</div>
);
};
export default AlarmOverview;

View File

@@ -0,0 +1,138 @@
import React, { useState } from 'react';
import {
Card, Table, Tag, Badge, Space, Button,
Modal, Descriptions, Input, Select
} from 'antd';
import { EyeOutlined } from '@ant-design/icons';
const AntdCard = Card as any;
const { Search } = Input;
const { Option } = Select;
// 模拟数据
const mockAlarms = [
{ id: 1, deviceName: '1#环境传感器', level: 'warn', content: '温度超过阈值 62℃', time: '2026-05-07 10:24:00', status: 'unprocessed' },
{ id: 2, deviceName: '2#阵列区球机', level: 'error', content: '视频信号丢失', time: '2026-05-07 10:20:00', status: 'processing' },
{ id: 3, deviceName: '3#电池供电设备', level: 'info', content: '电量低于20%', time: '2026-05-07 09:50:00', status: 'processed' },
];
const AlarmRealtime = () => {
// 弹窗控制
const [detailVisible, setDetailVisible] = useState(false);
const [currentAlarm, setCurrentAlarm] = useState<any>(null);
// 搜索 + 筛选
const [list, setList] = useState(mockAlarms);
const [filteredList, setFilteredList] = useState(mockAlarms);
// 打开详情
const showDetail = (record: any) => {
setCurrentAlarm(record);
setDetailVisible(true);
};
// 搜索筛选
const handleSearch = (value: string) => {
const res = list.filter(item =>
item.deviceName.includes(value) ||
item.content.includes(value) ||
item.level.includes(value)
);
setFilteredList(res);
};
// 表格列
const columns = [
{ title: '时间', dataIndex: 'time', width: 180 },
{ title: '设备', dataIndex: 'deviceName' },
{
title: '级别',
render: (l: any) => {
const color = l.level === 'warn' ? 'orange' : l.level === 'error' ? 'red' : 'blue';
const text = l.level === 'warn' ? '警告' : l.level === 'error' ? '严重' : '提示';
return <Tag color={color}>{text}</Tag>;
}
},
{ title: '内容', dataIndex: 'content' },
{
title: '状态',
render: (r: any) => {
const statusMap = {
unprocessed: { status: 'error', text: '未处理' },
processing: { status: 'warning', text: '处理中' },
processed: { status: 'success', text: '已处理' },
closed: { status: 'default', text: '已关闭' },
};
const s = statusMap[r.status] || statusMap.unprocessed;
return <Badge status={s.status as any} text={s.text} />;
}
},
{
title: '操作',
render: (_: any, record: any) => (
<Button type="link" icon={<EyeOutlined />} onClick={() => showDetail(record)}>
详情
</Button>
)
},
];
return (
<div style={{ padding: 24 }}>
<AntdCard
title="实时告警"
extra={
<Search
placeholder="搜索设备名称/告警内容"
style={{ width: 260 }}
onSearch={handleSearch}
/>
}
>
{/* 表格 */}
<Table
rowKey="id"
columns={columns}
dataSource={filteredList}
pagination={{ pageSize: 10 }}
/>
</AntdCard>
{/* 告警详情弹窗 */}
<Modal
title="告警详情"
open={detailVisible}
onCancel={() => setDetailVisible(false)}
footer={null}
width={500}
>
{currentAlarm && (
<Descriptions column={1} bordered>
<Descriptions.Item label="告警时间">{currentAlarm.time}</Descriptions.Item>
<Descriptions.Item label="设备名称">{currentAlarm.deviceName}</Descriptions.Item>
<Descriptions.Item label="告警内容">{currentAlarm.content}</Descriptions.Item>
<Descriptions.Item label="告警级别">
<Tag color={currentAlarm.level === 'warn' ? 'orange' : currentAlarm.level === 'error' ? 'red' : 'blue'}>
{currentAlarm.level === 'warn' ? '警告' : currentAlarm.level === 'error' ? '严重' : '提示'}
</Tag>
</Descriptions.Item>
<Descriptions.Item label="处理状态">
<Badge
status={
currentAlarm.status === 'unprocessed' ? 'error' :
currentAlarm.status === 'processing' ? 'warning' : 'success'
}
text={
currentAlarm.status === 'unprocessed' ? '未处理' :
currentAlarm.status === 'processing' ? '处理中' : '已处理'
}
/>
</Descriptions.Item>
</Descriptions>
)}
</Modal>
</div>
);
};
export default AlarmRealtime;

View File

@@ -0,0 +1,181 @@
import React, { useState } from 'react';
import {
Card, Table, Button, Space, Popconfirm, Tag, Badge,
Modal, Form, Input, Select, Switch
} from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
const AntdCard = Card as any;
const { Option } = Input;
const { Search } = Input;
// 模拟数据
const mockRules = [
{ id: 1, name: '温度超温', deviceType: 'sensor', level: 'warn', condition: 'temp > 60', status: true },
{ id: 2, name: '视频信号丢失', deviceType: 'camera', level: 'error', condition: 'signal == 0', status: true },
{ id: 3, name: '电池低电量', deviceType: 'battery', level: 'info', condition: 'power < 20', status: false },
];
const AlarmRules = () => {
const [list, setList] = useState(mockRules);
const [filteredList, setFilteredList] = useState(mockRules);
const [modalVisible, setModalVisible] = useState(false);
const [editingId, setEditingId] = useState<number | null>(null);
const [form] = Form.useForm();
// 搜索筛选
const handleSearch = (value: string) => {
const res = list.filter(item =>
item.name.includes(value) ||
item.deviceType.includes(value) ||
item.condition.includes(value)
);
setFilteredList(res);
};
// 打开新增
const openAdd = () => {
setEditingId(null);
form.resetFields();
setModalVisible(true);
};
// 打开编辑
const openEdit = (record: any) => {
setEditingId(record.id);
form.setFieldsValue(record);
setModalVisible(true);
};
// 保存(新增 + 编辑)
const handleSave = () => {
form.validateFields().then(values => {
if (editingId !== null) {
// 编辑
const updated = list.map(item =>
item.id === editingId ? { ...item, ...values } : item
);
setList(updated);
setFilteredList(updated);
} else {
// 新增
const newRule = { ...values, id: Date.now() };
const newList = [...list, newRule];
setList(newList);
setFilteredList(newList);
}
setModalVisible(false);
});
};
// 删除
const handleDelete = (id: number) => {
const newList = list.filter(x => x.id !== id);
setList(newList);
setFilteredList(newList);
};
const columns = [
{ title: '规则名称', dataIndex: 'name' },
{ title: '设备类型', dataIndex: 'deviceType' },
{
title: '告警级别',
render: (r: any) => {
const color = r.level === 'error' ? 'red' : r.level === 'warn' ? 'orange' : 'blue';
const text = r.level === 'error' ? '严重' : r.level === 'warn' ? '警告' : '提示';
return <Tag color={color}>{text}</Tag>;
}
},
{ title: '触发条件', dataIndex: 'condition' },
{
title: '状态',
render: (r: any) => (
<Badge status={r.status ? 'success' : 'error'} text={r.status ? '启用' : '禁用'} />
)
},
{
title: '操作',
render: (r: any) => (
<Space>
<Button type="link" icon={<EditOutlined />} onClick={() => openEdit(r)}>编辑</Button>
<Popconfirm
title="确定删除这条规则吗?"
onConfirm={() => handleDelete(r.id)}
>
<Button type="link" danger icon={<DeleteOutlined />}>删除</Button>
</Popconfirm>
</Space>
)
}
];
return (
<div style={{ padding: 24 }}>
<AntdCard
title="告警规则"
extra={
<Space>
{/* 修复:使用 Input.Search */}
<Search
placeholder="搜索规则名称/设备/条件"
style={{ width: 260 }}
onSearch={handleSearch}
/>
<Button icon={<PlusOutlined />} type="primary" onClick={openAdd}>
新增规则
</Button>
</Space>
}
>
<Table
rowKey="id"
columns={columns}
dataSource={filteredList}
pagination={{ pageSize: 10 }}
/>
</AntdCard>
{/* 新增/编辑 弹窗 */}
<Modal
title={editingId ? '编辑告警规则' : '新增告警规则'}
open={modalVisible}
onCancel={() => setModalVisible(false)}
onOk={handleSave}
maskClosable={false}
>
<Form form={form} layout="vertical">
<Form.Item label="规则名称" name="name" rules={[{ required: true, message: '请输入规则名称' }]}>
<Input placeholder="例如:温度超温告警" />
</Form.Item>
<Form.Item label="设备类型" name="deviceType" rules={[{ required: true }]}>
<Select>
<Select.Option value="sensor">传感器</Select.Option>
<Select.Option value="camera">摄像头</Select.Option>
<Select.Option value="battery">电池设备</Select.Option>
<Select.Option value="inverter">逆变器</Select.Option>
</Select>
</Form.Item>
<Form.Item label="告警级别" name="level" rules={[{ required: true }]}>
<Select>
<Select.Option value="error">严重</Select.Option>
<Select.Option value="warn">警告</Select.Option>
<Select.Option value="info">提示</Select.Option>
</Select>
</Form.Item>
<Form.Item label="触发条件" name="condition" rules={[{ required: true }]}>
<Input placeholder="例如:temp > 60 / power < 20" />
</Form.Item>
<Form.Item label="是否启用" name="status" valuePropName="checked">
<Switch checkedChildren="启用" unCheckedChildren="禁用" />
</Form.Item>
</Form>
</Modal>
</div>
);
};
export default AlarmRules;

View File

@@ -0,0 +1,129 @@
import React, { useEffect, useRef } from 'react';
import { Card, Row, Col, Space } from 'antd';
import { AreaChartOutlined } from '@ant-design/icons';
import * as echarts from 'echarts';
const AntdCard = Card as any;
const AlarmStatistics = () => {
// 图表 ref
const barChartRef = useRef(null);
const pieChartRef = useRef(null);
// 柱状图
useEffect(() => {
if (!barChartRef.current) return;
const barChart = echarts.init(barChartRef.current);
barChart.setOption({
title: { text: '近7天告警趋势' },
xAxis: {
type: 'category',
data: ['1日', '2日', '3日', '4日', '5日', '6日', '7日']
},
yAxis: { type: 'value' },
series: [
{
data: [5, 8, 12, 9, 15, 7, 12],
type: 'bar',
itemStyle: { color: '#1677ff' }
}
]
});
const resizeFn = () => barChart.resize();
window.addEventListener('resize', resizeFn);
return () => {
barChart.dispose();
window.removeEventListener('resize', resizeFn);
};
}, []);
// 饼图
useEffect(() => {
if (!pieChartRef.current) return;
const pieChart = echarts.init(pieChartRef.current);
pieChart.setOption({
title: { text: '告警级别分布' },
tooltip: { trigger: 'item' },
series: [
{
type: 'pie',
radius: '50%',
data: [
{ value: 15, name: '严重告警' },
{ value: 30, name: '警告告警' },
{ value: 25, name: '提示告警' }
]
}
]
});
const resizeFn = () => pieChart.resize();
window.addEventListener('resize', resizeFn);
return () => {
pieChart.dispose();
window.removeEventListener('resize', resizeFn);
};
}, []);
return (
<div style={{ padding: 24 }}>
{/* 顶部统计卡片 保留你原来的图标样式 */}
<AntdCard title="告警概览" style={{ marginBottom: 24 }}>
<Row gutter={16}>
<Col span={8}>
<Space>
<div style={{ background: '#e6f4ff', padding: 8, borderRadius: 8 }}>
<AreaChartOutlined style={{ color: '#1677ff', fontSize: 20 }} />
</div>
<div>
<div style={{ color: '#666' }}>今日告警</div>
<div style={{ fontWeight: 600, fontSize: 18 }}>12</div>
</div>
</Space>
</Col>
<Col span={8}>
<Space>
<div style={{ background: '#fff7e6', padding: 8, borderRadius: 8 }}>
<AreaChartOutlined style={{ color: '#fa8c16', fontSize: 20 }} />
</div>
<div>
<div style={{ color: '#666' }}>本周告警</div>
<div style={{ fontWeight: 600, fontSize: 18 }}>45</div>
</div>
</Space>
</Col>
<Col span={8}>
<Space>
<div style={{ background: '#f6ffed', padding: 8, borderRadius: 8 }}>
<AreaChartOutlined style={{ color: '#52c41a', fontSize: 20 }} />
</div>
<div>
<div style={{ color: '#666' }}>本月告警</div>
<div style={{ fontWeight: 600, fontSize: 18 }}>128</div>
</div>
</Space>
</Col>
</Row>
</AntdCard>
{/* 两个图表 左右各一半 并排显示 不空洞 */}
<Row gutter={16}>
<Col span={12}>
<AntdCard title="告警趋势统计">
<div ref={barChartRef} style={{ width: '100%', height: 350 }} />
</AntdCard>
</Col>
<Col span={12}>
<AntdCard title="告警分类统计">
<div ref={pieChartRef} style={{ width: '100%', height: 350 }} />
</AntdCard>
</Col>
</Row>
</div>
);
};
export default AlarmStatistics;

View File

@@ -0,0 +1,168 @@
import React, { useState } from 'react';
import {
Card, Table, Button, Space, Popconfirm, Tag,
Modal, Form, Input, Select
} from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
const AntdCard = Card as any;
const { Option } = Select;
const { Search } = Input;
// 模拟数据
const mockSub = [
{ id: 1, name: '运维订阅', deviceType: 'all', level: 'all', channels: ['短信'] },
{ id: 2, name: '管理员订阅', deviceType: 'sensor', level: 'error', channels: ['短信', '邮件'] },
{ id: 3, name: '设备订阅', deviceType: 'camera', level: 'warn', channels: ['APP推送'] },
];
const AlarmSubscription = () => {
const [list, setList] = useState(mockSub);
const [filteredList, setFilteredList] = useState(mockSub);
const [modalVisible, setModalVisible] = useState(false);
const [editingId, setEditingId] = useState<number | null>(null);
const [form] = Form.useForm();
// 搜索筛选
const handleSearch = (value) => {
const res = list.filter(item =>
item.name.includes(value) ||
item.deviceType.includes(value) ||
item.level.includes(value)
);
setFilteredList(res);
};
// 打开新增
const openAdd = () => {
setEditingId(null);
form.resetFields();
setModalVisible(true);
};
// 打开编辑(回填数据)
const openEdit = (record) => {
setEditingId(record.id);
form.setFieldsValue(record);
setModalVisible(true);
};
// 保存(新增+编辑)
const handleSave = () => {
form.validateFields().then(values => {
if (editingId !== null) {
// 编辑
const updated = list.map(item =>
item.id === editingId ? { ...item, ...values } : item
);
setList(updated);
setFilteredList(updated);
} else {
// 新增
const newItem = { ...values, id: Date.now() };
const newList = [...list, newItem];
setList(newList);
setFilteredList(newList);
}
setModalVisible(false);
});
};
// 删除
const handleDelete = (id) => {
const newList = list.filter(x => x.id !== id);
setList(newList);
setFilteredList(newList);
};
const columns = [
{ title: '订阅名称', dataIndex: 'name' },
{ title: '设备类型', dataIndex: 'deviceType' },
{ title: '告警级别', dataIndex: 'level' },
{
title: '通知渠道',
render: (r) => r.channels.map(i => <Tag key={i}>{i}</Tag>)
},
{
title: '操作',
render: (r) => (
<Space>
<Button type="link" icon={<EditOutlined />} onClick={() => openEdit(r)}>编辑</Button>
<Popconfirm title="确定删除?" onConfirm={() => handleDelete(r.id)}>
<Button type="link" danger icon={<DeleteOutlined />}>删除</Button>
</Popconfirm>
</Space>
)
}
];
return (
<div style={{ padding: 24 }}>
<AntdCard
title="告警订阅"
extra={
<Space>
<Search
placeholder="搜索订阅/设备/级别"
style={{ width: 260 }}
onSearch={handleSearch}
/>
<Button icon={<PlusOutlined />} type="primary" onClick={openAdd}>
新增订阅
</Button>
</Space>
}
>
<Table
rowKey="id"
columns={columns}
dataSource={filteredList}
pagination={{ pageSize: 10 }}
/>
</AntdCard>
{/* 新增/编辑 弹窗 */}
<Modal
title={editingId ? '编辑告警订阅' : '新增告警订阅'}
open={modalVisible}
onCancel={() => setModalVisible(false)}
onOk={handleSave}
maskClosable={false}
>
<Form form={form} layout="vertical">
<Form.Item label="订阅名称" name="name" rules={[{ required: true }]}>
<Input placeholder="请输入订阅名称" />
</Form.Item>
<Form.Item label="设备类型" name="deviceType" rules={[{ required: true }]}>
<Select>
<Option value="all">全部设备</Option>
<Option value="sensor">传感器</Option>
<Option value="camera">摄像头</Option>
<Option value="battery">电池设备</Option>
</Select>
</Form.Item>
<Form.Item label="告警级别" name="level" rules={[{ required: true }]}>
<Select>
<Option value="all">全部级别</Option>
<Option value="error">严重</Option>
<Option value="warn">警告</Option>
<Option value="info">提示</Option>
</Select>
</Form.Item>
<Form.Item label="通知渠道" name="channels" rules={[{ required: true }]}>
<Select mode="multiple" placeholder="请选择通知渠道">
<Option value="短信">短信</Option>
<Option value="邮件">邮件</Option>
<Option value="APP推送">APP推送</Option>
</Select>
</Form.Item>
</Form>
</Modal>
</div>
);
};
export default AlarmSubscription;