告警中心 初始化

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

@@ -1,323 +1,90 @@
import React, { useState } from 'react';
import React, { useState, useEffect } from 'react';
import { Layout, Menu, Typography } from 'antd';
import {
Table,
Tag,
Input,
Button,
Row,
Col,
Card,
Typography,
Space,
Statistic,
Select,
DatePicker,
List,
Layout,
} from 'antd';
import {
BellOutlined,
AlertOutlined,
SyncOutlined,
CheckCircleOutlined,
ClockCircleOutlined,
RiseOutlined,
FallOutlined,
CloseOutlined,
AlertOutlined, ClockCircleOutlined, FileTextOutlined, BarChartOutlined,
SettingOutlined, BellOutlined
} from '@ant-design/icons';
import { getMenuList } from '../api/mune';
import AlarmOverview from '../components/alerts/AlarmOverview';
import AlarmRealtime from '../components/alerts/AlarmRealtime';
import AlarmHistory from '../components/alerts/AlarmHistory';
import AlarmStatistics from '../components/alerts/AlarmStatistics';
import AlarmRules from '../components/alerts/AlarmRules';
import AlarmSubscription from '../components/alerts/AlarmSubscription';
const { Header, Content } = Layout;
const { Text } = Typography;
const { RangePicker } = DatePicker;
const AntdCard = Card as any;
// 模拟数据
const alertList = [
{
id: 'AL20250525001',
content: '逆变器停机',
device: '逆变器 12 (组串式)',
level: '严重',
time: '2025-05-25 09:18:32',
duration: '2小时18分',
status: '处理中',
handler: '张运维',
},
{
id: 'AL20250525002',
content: '发电量下降 > 15%',
device: '汇流箱 05',
level: '重要',
time: '2025-05-25 08:46:11',
duration: '3小时50分',
status: '处理中',
handler: '李工程师',
},
{
id: 'AL20250525003',
content: '逆变器温度过高',
device: '逆变器 07 (组串式)',
level: '重要',
time: '2025-05-25 07:32:45',
duration: '4小时24分',
status: '待处理',
handler: '-',
},
];
export default function AlarmCenterPage() {
const [activeTab, setActiveTab] = useState('overview');
const [rawMenuList, setRawMenuList] = useState([]);
const [showTabs, setShowTabs] = useState([]);
const stats = [
{
title: '今日告警总数',
value: 36,
change: '+28.6%',
up: true,
extra: '昨日 28',
icon: <BellOutlined style={{ color: '#ff4d4f' }} />,
},
{
title: '严重告警',
value: 8,
change: '+33.3%',
up: true,
extra: '昨日 6',
icon: <AlertOutlined style={{ color: '#ff4d4f' }} />,
},
{
title: '处理中',
value: 12,
change: '+20.0%',
up: true,
extra: '昨日 10',
icon: <SyncOutlined style={{ color: '#fa8c16' }} />,
},
{
title: '已关闭',
value: 16,
change: '+45.5%',
up: true,
extra: '昨日 11',
icon: <CheckCircleOutlined style={{ color: '#52c41a' }} />,
},
{
title: '平均响应时长',
value: '18分32秒',
change: '-12.6%',
up: false,
extra: '昨日 21分12秒',
icon: <ClockCircleOutlined style={{ color: '#1890ff' }} />,
},
];
// 获取菜单(和系统设置一模一样)
const getMenuListApi = () => {
const params = { pageNum: 1, pageSize: 99999 };
return getMenuList(params);
};
export default function Alerts() {
// 控制右侧详情面板
const [showDetail, setShowDetail] = useState(false);
const [selectedAlert, setSelectedAlert] = useState<any>(null);
// 动态生成 tab
useEffect(() => {
getMenuListApi().then(res => {
if (res.code === 200) {
const data = res.rows || [];
// 告警中心 parentId 你自己改成你数据库里的 ID
const alarmChild = data.filter(m => m.parentId == 3388);
const columns = [
{ title: '告警编号', dataIndex: 'id', key: 'id', width: 120 },
{ title: '告警内容', dataIndex: 'content', key: 'content' },
{ title: '来源设备', dataIndex: 'device', key: 'device', width: 160 },
{
title: '告警级别',
dataIndex: 'level',
key: 'level',
width: 80,
render: (level: string) => {
const colorMap: Record<string, string> = {
严重: 'red',
重要: 'orange',
一般: 'gold',
提示: 'blue',
};
return <Tag color={colorMap[level]}>{level}</Tag>;
},
},
{ title: '发生时间', dataIndex: 'time', key: 'time', width: 160 },
{ title: '持续时长', dataIndex: 'duration', key: 'duration', width: 110 },
{
title: '处理状态',
dataIndex: 'status',
key: 'status',
width: 100,
render: (status: string) => {
const colorMap: Record<string, string> = {
处理中: 'blue',
待处理: 'orange',
已关闭: 'green',
};
return <Tag color={colorMap[status]}>{status}</Tag>;
},
},
{ title: '负责人', dataIndex: 'handler', key: 'handler', width: 90 },
{
title: '操作',
key: 'action',
width: 80,
render: (_, record) => (
<Button
type="link"
size="small"
onClick={() => {
setSelectedAlert(record);
setShowDetail(true);
}}
>
查看
</Button>
),
},
];
alarmChild.sort((a, b) => (a.orderNum || 0) - (b.orderNum || 0));
const tabs = alarmChild.map(item => {
if (item.path === '/alerts/all') return { key: 'overview', label: '告警总览', icon: <AlertOutlined /> };
if (item.path === '/alerts/time') return { key: 'realtime', label: '实时告警', icon: <ClockCircleOutlined /> };
if (item.path === '/alerts/history') return { key: 'history', label: '告警历史', icon: <FileTextOutlined /> };
if (item.path === '/alerts/counts') return { key: 'statistics', label: '告警统计', icon: <BarChartOutlined /> };
if (item.path === '/alerts/rules') return { key: 'rules', label: '告警规则', icon: <SettingOutlined /> };
if (item.path === '/alerts/subscribe') return { key: 'subscription', label: '告警订阅', icon: <BellOutlined /> };
return null;
}).filter(Boolean);
setShowTabs(tabs);
if (tabs.length > 0) setActiveTab(tabs[0].key);
}
});
}, []);
// 渲染对应组件
const renderTabContent = () => {
switch (activeTab) {
case 'overview': return <AlarmOverview />;
case 'realtime': return <AlarmRealtime />;
case 'history': return <AlarmHistory />;
case 'statistics': return <AlarmStatistics />;
case 'rules': return <AlarmRules />;
case 'subscription': return <AlarmSubscription />;
default: return <div style={{ padding: 20 }}><Text>请选择菜单</Text></div>;
}
};
return (
<div style={{ background: '#f4f7f9', minHeight: '100%' }}>
<Layout style={{ background: 'transparent' }}>
{/* 左侧主内容区:宽度动态变化 */}
<Layout.Content
style={{
padding: '16px',
transition: 'width 0.3s ease',
width: showDetail ? 'calc(100% - 460px)' : '100%',
}}
>
<div style={{ fontSize: 16, fontWeight: 600, marginBottom: 12 }}>告警中心</div>
<Layout style={{ minHeight: '100vh', background: '#fff', overflow: 'hidden' }}>
<Header style={{ background: '#fff', padding: 0, borderBottom: '1px solid #f0f0f0', position: 'sticky', top: 0, zIndex: 10 }}>
<Menu
mode="horizontal"
selectedKeys={[activeTab]}
onClick={({ key }) => setActiveTab(key)}
items={showTabs}
style={{ border: 0, height: 64, lineHeight: '64px' }}
/>
</Header>
{/* 筛选栏 */}
<AntdCard size="small" style={{ borderRadius: 8, marginBottom: 16 }}>
<Row gutter={[16, 16]} align="middle">
<Col span={4}><Select placeholder="告警级别" style={{ width: '100%' }} /></Col>
<Col span={4}><Select placeholder="告警类型" style={{ width: '100%' }} /></Col>
<Col span={4}><Select placeholder="设备类型" style={{ width: '100%' }} /></Col>
<Col span={6}><RangePicker style={{ width: '100%' }} /></Col>
<Col span={6}><Select placeholder="处理状态" style={{ width: '100%' }} /></Col>
<Col span={24} style={{ display: 'flex', gap: 8, marginTop: 8 }}>
<Input placeholder="搜索" style={{ width: 220 }} />
<Button>重置</Button>
<Button type="primary">查询</Button>
</Col>
</Row>
</AntdCard>
{/* 统计卡片 */}
<Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
{stats.map((stat, idx) => (
<Col xs={24} sm={12} md={8} lg={4} key={idx}>
<AntdCard size="small" style={{ borderRadius: 8 }}>
<Statistic
title={<span style={{ fontSize: 13 }}>{stat.title}</span>}
value={stat.value}
valueStyle={{ fontSize: 20, fontWeight: 600 }}
prefix={stat.icon}
/>
<div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 4 }}>
<Text type="secondary" style={{ fontSize: 12 }}>{stat.extra}</Text>
<Text style={{ color: stat.up ? '#ff4d4f' : '#52c41a', fontSize: 12 }}>
{stat.change} {stat.up ? <RiseOutlined /> : <FallOutlined />}
</Text>
</div>
</AntdCard>
</Col>
))}
</Row>
{/* 告警列表 */}
<AntdCard
size="small"
title={
<div style={{ fontSize: 14, fontWeight: 600 }}>
<span style={{ color: '#165DFF' }}>告警列表</span>
<span style={{ color: '#333' }}>(共36条)</span>
</div>
}
style={{ borderRadius: 8 }}
>
<Table
size="small"
columns={columns}
dataSource={alertList}
pagination={{ pageSize: 10 }}
rowKey="id"
onRow={(record) => ({
onClick: () => {
setSelectedAlert(record);
setShowDetail(true);
},
})}
/>
</AntdCard>
</Layout.Content>
{/* 右侧详情面板:推挤式,非覆盖 */}
{showDetail && (
<Layout.Sider
width={460}
style={{
background: '#fff',
padding: '16px',
height: 'calc(100vh - 50px)',
overflow: 'auto',
boxShadow: '-2px 0 8px rgba(0,0,0,0.08)',
}}
>
{selectedAlert && (
<div>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
<Text strong style={{ fontSize: 16 }}>告警详情</Text>
<Button
type="text"
icon={<CloseOutlined />}
onClick={() => setShowDetail(false)}
style={{ fontSize: 16 }}
/> </div>
<div style={{ marginBottom: 16 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
<BellOutlined style={{ color: '#ff4d4f', fontSize: 20 }} />
<Text strong style={{ fontSize: 16 }}>{selectedAlert.content}</Text>
<Tag color="red">{selectedAlert.level}</Tag>
</div>
<div style={{ fontSize: 12, color: '#666', lineHeight: 1.8 }}>
<div>告警编号:{selectedAlert.id}</div>
<div>来源设备:{selectedAlert.device}</div>
<div>发生时间:{selectedAlert.time}</div>
<div>持续时长:{selectedAlert.duration}</div>
<div>处理状态:{selectedAlert.status}</div>
<div>负责人:{selectedAlert.handler}</div>
</div>
</div>
<div style={{ marginBottom: 16 }}>
<Text strong style={{ fontSize: 13, marginBottom: 8, display: 'block' }}>根因分析建议</Text>
<List
size="small"
dataSource={[
'逆变器内部保护触发(IGBT/继电器故障)',
'交流侧电压异常或并网不稳定',
'散热风扇故障导致过温保护',
]}
renderItem={(item) => <List.Item style={{ padding: '4px 0' }}>{item}</List.Item>}
/>
</div>
<div style={{ marginBottom: 16 }}>
<Text strong style={{ fontSize: 13, marginBottom: 8, display: 'block' }}>推荐处理措施</Text>
<List
size="small"
dataSource={[
'现场检查逆变器告警记录及指示灯状态',
'检查散热风扇运行及通风条件',
'检查交流侧电压及并网条件',
]}
renderItem={(item) => <List.Item style={{ padding: '4px 0' }}>{item}</List.Item>}
/>
</div>
<Button type="primary" block style={{ marginTop: 16 }}>
标记为已解决
</Button>
</div>
)}
</Layout.Sider>
)}
</Layout>
</div>
<Content style={{
maxHeight: 'calc(100vh - 64px)', overflowY: 'auto', background: '#f5f7fa',
scrollbarWidth: 'none', msOverflowStyle: 'none',
}}>
{renderTabContent()}
</Content>
</Layout>
);
}

View File

@@ -1,595 +0,0 @@
import { useState } from 'react';
import {
Card, Table, Button, Space, Form, Modal, Input, Select, InputNumber,
Tabs, Tag, Popconfirm, message, Divider, Switch, Checkbox
} 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: '电量、电压监测' },
];
// 物模型详情:属性增加 isAlarm(是否作为告警参数)
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: []
}
};
// 字段映射数据
const mappingInitList = [
{ id: 1, productId: 1, standardCode: 'device_online', sourceField: 'online_flag', convertRule: 'value==1?true:false' },
];
const deviceList = [
{
id: 1,
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,
createTime: '2026-05-07 10:23:45'
},
{
id: 2,
name: '1#电池设备',
sn: 'BAT001',
productId: 3,
productName: '通用MQTT设备',
modelId: 12,
modelName: '电池供电设备',
protocolType: 'mqtt',
mqttServer: 'tcp://192.168.1.200',
mqttPort: 1883,
clientId: 'bat_001',
alarmConfig: {
batteryMax: 100, batteryMin: 10,
voltageMax: 24, voltageMin: 12
},
onlineStatus: 1,
createTime: '2026-05-07 10:25:10'
}
];
const alarmList = [
{ id: 1, deviceId: 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 [protocol, setProtocol] = useState('onvif');
// 物模型详情
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<any[]>(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') {
setProtocol(record.protocolType);
// 加载对应模型详情,用于动态生成告警项
setModelDetail(modelDetailList[record.modelId] || { props: [] });
}
} else {
setModelDetail({ props: [], events: [], actions: [] });
}
setVisible(true);
};
// 主表单保存
const handleSubmit = () => {
form.validateFields().then(() => {
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]];
if (val.id) {
const idx = list.findIndex(x => x.id === val.id);
idx >= 0 && (list[idx] = val);
} else {
list.push({ ...val, id: Date.now() });
}
setModelDetail({ ...modelDetail, [itemType]: list });
setItemModal(false);
message.success('保存成功');
});
};
const deleteItem = (type: 'props' | 'events' | 'actions', id: number) => {
const list = modelDetail[type].filter(x => x.id !== id);
setModelDetail({ ...modelDetail, [type]: list });
message.success('删除成功');
};
// ========== 字段映射 增删改 ==========
const openMappingModal = (record: any, row?: any) => {
setVisible(false);
mappingForm.resetFields();
if (row) {
mappingForm.setFieldsValue(row);
} else {
mappingForm.setFieldsValue({ productId: record.id });
}
setMappingModal(true);
};
const saveMapping = () => {
mappingForm.validateFields().then((val) => {
const list = [...mappingList];
if (val.id) {
const idx = list.findIndex(item => item.id === val.id);
list[idx] = val;
} else {
list.push({ ...val, id: Date.now() });
}
setMappingList(list);
setMappingModal(false);
setTimeout(() => setVisible(true), 300);
message.success('字段映射保存成功');
});
};
const delMapping = (id: number) => {
const list = mappingList.filter(item => item.id !== id);
setMappingList(list);
message.success('删除成功');
};
// 获取当前模型的告警属性(isAlarm=true)
const getAlarmProps = () => {
if (!modelDetail?.props) return [];
return 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: string) => <Tag>{t.toUpperCase()}</Tag> },
{ title: '状态', dataIndex: 'onlineStatus', render: (s: number) => <Tag color={s === 1 ? 'green' : 'red'}>{s === 1 ? '在线' : '离线'}</Tag> },
{
title: '操作', render: (r: any) => (
<Space>
<Button type="text" icon={<EditOutlined />} onClick={() => openModal('device', r)}>编辑</Button>
</Space>
)
}
];
const productColumns = [
{ title: '产品名称', dataIndex: 'name' },
{ title: '产品编码', dataIndex: 'code' },
{ title: '厂商', dataIndex: 'manufacturer' },
{ title: '协议类型', dataIndex: 'protocolType', render: (t: string) => <Tag>{t.toUpperCase()}</Tag> },
{ title: '上报Topic', dataIndex: 'publishTopic' },
{ title: '订阅Topic', dataIndex: 'subscribeTopic' },
{
title: '操作', render: (r: any) => (
<Space>
<Button type="text" icon={<EditOutlined />} onClick={() => openModal('product', r)}>编辑</Button>
<Button type="text" icon={<SwapOutlined />} onClick={() => openModal('mapping', r)}>字段映射</Button>
</Space>
)
}
];
const modelColumns = [
{ title: '模型名称', dataIndex: 'name' },
{ title: '模型编码', dataIndex: 'code' },
{ title: '描述', dataIndex: 'desc' },
{ title: '操作', render: (r: any) => <Button type="text" icon={<EditOutlined />} onClick={() => openModal('model', r)}>编辑</Button> }
];
const mappingColumns = [
{ title: '标准模型字段', dataIndex: 'standardCode' },
{ title: '厂商原始字段', dataIndex: 'sourceField' },
{ title: '转换规则', dataIndex: 'convertRule' },
{
title: '操作', render: (r: any) => (
<Space>
<Button type="text" icon={<EditOutlined />} onClick={() => openMappingModal(editData, r)}>编辑</Button>
<Popconfirm title="确定删除该映射?" onConfirm={() => delMapping(r.id)}>
<Button type="text" danger icon={<DeleteOutlined />}>删除</Button>
</Popconfirm>
</Space>
)
}
];
const alarmColumns = [
{ title: '设备名称', dataIndex: 'deviceName' },
{ title: '告警级别', dataIndex: 'level' },
{ title: '告警内容', dataIndex: 'content' },
{ title: '告警时间', dataIndex: 'time' },
];
const propColumns = [
{ title: '字段编码', dataIndex: 'code' },
{ title: '字段名称', dataIndex: 'name' },
{ title: '数据类型', dataIndex: 'type' },
{ title: '读写类型', dataIndex: 'rw' },
{
title: '告警参数', render: (r: any) => (
<Checkbox checked={r.isAlarm} disabled>启用</Checkbox>
)
},
{
title: '操作', render: (r: any) => (
<Space>
<Button type="text" onClick={() => openItemModal('props', r)}>编辑</Button>
<Popconfirm title="确定删除?" onConfirm={() => deleteItem('props', r.id)}>
<Button type="text" danger>删除</Button>
</Popconfirm>
</Space>
)
}
];
const eventActionColumns = [
{ title: '编码', dataIndex: 'code' },
{ title: '名称', dataIndex: 'name' },
{
title: '操作', render: (r: any) => (
<Space>
<Button type="text" onClick={() => openItemModal(itemType, r)}>编辑</Button>
<Popconfirm title="确定删除?" onConfirm={() => deleteItem(itemType, r.id)}>
<Button type="text" danger>删除</Button>
</Popconfirm>
</Space>
)
}
];
return (
<div className="bg-[#f5f7fa] min-h-screen p-5">
<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" />
<TabPane tab={<span><AlertOutlined />告警列表</span>} key="alarm" />
</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} pagination={{ pageSize: 10 }} />
</Card>
)}
{/* 产品管理 */}
{activeTab === 'product' && (
<Card>
<Space className="mb-3">
<Button type="primary" icon={<PlusOutlined />} onClick={() => openModal('product')}>新增产品</Button>
</Space>
<Table rowKey="id" columns={productColumns} dataSource={productList} pagination={{ pageSize: 10 }} />
</Card>
)}
{/* 物模型管理 */}
{activeTab === 'model' && (
<Card>
<Space className="mb-3">
<Button type="primary" icon={<PlusOutlined />} onClick={() => openModal('model')}>新增物模型</Button>
</Space>
<Table rowKey="id" columns={modelColumns} dataSource={modelList} pagination={{ pageSize: 10 }} />
</Card>
)}
{/* 告警列表 */}
{activeTab === 'alarm' && (
<Card>
<Table rowKey="id" columns={alarmColumns} dataSource={alarmList} pagination={{ pageSize: 10 }} />
</Card>
)}
{/* 主弹窗:设备/产品/物模型 */}
<Modal
open={visible}
title={
modalType === 'device' ? '设备接入配置' :
modalType === 'product' ? '产品配置' :
modalType === 'model' ? '物模型配置' :
modalType === 'mapping' ? '字段映射管理' : ''
}
onCancel={() => setVisible(false)}
onOk={handleSubmit}
width={800}
destroyOnClose
>
<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 onChange={(_, o: any) => setProtocol(o.protocolType)}>
{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">
{protocol === '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>
</>
)}
{protocol === 'rtsp' && (
<Form.Item label="RTSP流地址" name="rtspUrl"><Input placeholder="rtsp://xxx" /></Form.Item>
)}
{protocol === 'mqtt' && (
<>
<Card size="small" title="MQTT连接配置" className="mb-2">
<Form.Item label="MQTT服务器" name="mqttServer"><Input placeholder="tcp://192.168.1.200" /></Form.Item>
<Form.Item label="端口" name="mqttPort"><InputNumber className="w-full" defaultValue={1883} /></Form.Item>
<Form.Item label="ClientID" name="clientId"><Input placeholder="设备唯一标识" /></Form.Item>
<Form.Item label="用户名" name="mqttUsername"><Input /></Form.Item>
<Form.Item label="密码" name="mqttPassword"><Input.Password /></Form.Item>
</Card>
<Card size="small" title="MQTT Topic配置(继承自产品)">
<div className="text-sm">上报主题:{editData?.publishTopic || '未配置'}</div>
<div className="text-sm">订阅主题:{editData?.subscribeTopic || '未配置'}</div>
</Card>
</>
)}
</TabPane>
{/* 报警阈值:动态渲染当前模型的告警属性 */}
<TabPane tab="报警阈值" key="alarmThreshold">
<div className="text-sm mb-2">当前物模型:{editData?.modelName},仅显示告警参数</div>
{getAlarmProps().map((item: any) => (
<div key={item.code}>
<Form.Item label={`${item.name} 上限`} name={['alarmConfig', `${item.code}Max`]}>
<InputNumber className="w-full" placeholder={`单位:${item.type === 'float' ? '数值' : '整数'}`} />
</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>
)}
{/* 产品配置 + MQTT Topic */}
{modalType === 'product' && (
<>
<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="protocolType" rules={[{ required: true }]}>
<Select>
<Option value="onvif">ONVIF</Option>
<Option value="rtsp">RTSP</Option>
<Option value="mqtt">MQTT</Option>
</Select>
</Form.Item>
<Form.Item label="厂商名称" name="manufacturer"><Input /></Form.Item>
<Divider>厂商级 MQTT Topic 配置</Divider>
<Form.Item label="设备上报主题(Publish)" name="publishTopic"><Input placeholder="/iot/device/upload" /></Form.Item>
<Form.Item label="平台下发主题(Subscribe)" name="subscribeTopic"><Input placeholder="/iot/device/cmd" /></Form.Item>
</>
)}
{/* 物模型完整编辑(含告警参数勾选) */}
{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 orientation="left">属性列表(可勾选作为告警参数)</Divider>
<Button size="small" type="primary" icon={<PlusOutlined />} onClick={() => openItemModal('props')} className="mb-2">新增属性</Button>
<Table size="small" rowKey="id" columns={propColumns} dataSource={modelDetail.props} pagination={false} />
<Divider orientation="left">事件列表</Divider>
<Button size="small" type="primary" icon={<PlusOutlined />} onClick={() => openItemModal('events')} className="mb-2">新增事件</Button>
<Table size="small" rowKey="id" columns={eventActionColumns} dataSource={modelDetail.events} pagination={false} />
<Divider orientation="left">服务/指令</Divider>
<Button size="small" type="primary" icon={<PlusOutlined />} onClick={() => openItemModal('actions')} className="mb-2">新增指令</Button>
<Table size="small" rowKey="id" columns={eventActionColumns} dataSource={modelDetail.actions} pagination={false} />
</>
)}
</Form>
{/* 字段映射列表 */}
{modalType === 'mapping' && (
<div className="mt-4">
<Divider orientation="left">{editData?.name} - 字段映射配置</Divider>
<Space className="mb-3">
<Button type="primary" size="small" icon={<PlusOutlined />} onClick={() => openMappingModal(editData)}>新增映射</Button>
</Space>
<Table size="small" rowKey="id" columns={mappingColumns} dataSource={mappingList.filter(item => item.productId === editData?.id)} pagination={false} />
</div>
)}
</Modal>
{/* 物模型子项编辑弹窗(属性增加isAlarm) */}
<Modal
open={itemModal}
title={itemType === 'props' ? '属性配置' : itemType === 'events' ? '事件配置' : '指令配置'}
onCancel={() => setItemModal(false)}
onOk={saveItem}
width={520}
>
<Form form={itemForm} layout="vertical">
<Form.Item name="id" hidden><Input /></Form.Item>
<Form.Item label="字段编码" name="code" rules={[{ required: true }]}><Input placeholder="如:temp" /></Form.Item>
<Form.Item label="字段名称" name="name" rules={[{ required: true }]}><Input placeholder="如:温度" /></Form.Item>
{itemType === 'props' && (
<>
<Form.Item label="数据类型" name="type" rules={[{ required: true }]}>
<Select>
<Option value="bool">布尔 bool</Option>
<Option value="int">数字 int</Option>
<Option value="float">浮点 float</Option>
<Option value="string">字符串 string</Option>
</Select>
</Form.Item>
<Form.Item label="读写权限" name="rw" rules={[{ required: true }]}>
<Select>
<Option value="r">只读</Option>
<Option value="rw">读写</Option>
</Select>
</Form.Item>
<Form.Item label="作为告警参数" name="isAlarm" valuePropName="checked">
<Switch />
</Form.Item>
</>
)}
</Form>
</Modal>
{/* 字段映射弹窗 */}
<Modal
open={mappingModal}
title="字段映射配置"
onCancel={() => setMappingModal(false)}
onOk={saveMapping}
width={600}
destroyOnClose
>
<Form form={mappingForm} layout="vertical">
<Form.Item name="id" hidden><Input /></Form.Item>
<Form.Item name="productId" hidden><Input /></Form.Item>
<Form.Item label="平台标准字段" name="standardCode" rules={[{ required: true }]}>
<Select placeholder="请选择标准字段">
{modelDetail.props?.map((item: any) => (
<Option key={item.code} value={item.code}>{item.name}({item.code})</Option>
))}
</Select>
</Form.Item>
<Form.Item label="厂商原始字段" name="sourceField" rules={[{ required: true }]}>
<Input placeholder="例如:temperature" />
</Form.Item>
<Form.Item label="转换规则" name="convertRule">
<Input placeholder="例如:value>50" />
</Form.Item>
</Form>
</Modal>
</div>
);
}

View File

@@ -334,7 +334,8 @@ export default function Home() {
extra={<Button type="link" size="small">更多&gt;</Button>}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
<Progress percent={58} type="circle" size={80} strokeColor="#52c41a" successPercent={25} />
<Progress percent={58} type="circle" size={80} strokeColor="#52c41a" success={{ percent: 25 }} // ✅ 新写法
/>
<div style={{ fontSize: 12 }}>
<div><span style={{ color: '#52c41a' }}>●</span> 已完成 7 (58%)</div>
<div><span style={{ color: '#faad14' }}>●</span> 进行中 3 (25%)</div>

View File

@@ -1,272 +0,0 @@
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

@@ -1,226 +0,0 @@
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

@@ -1,399 +0,0 @@
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

@@ -11,12 +11,12 @@ import {
ExperimentOutlined,
EnvironmentOutlined
} from '@ant-design/icons';
import UserRolePage from './UserPage';
import MenuList from './MenuList';
import Organization from './Organization';
import StationManage from './StationManage';
import UserRolePage from '../components/SystemSetting/UserPage';
import MenuList from '../components/SystemSetting/MenuList';
import Organization from '../components/SystemSetting/Organization';
import StationManage from '../components/SystemSetting/StationManage';
import { getMenuList } from '../api/mune';
import DeviceAccessPage from './DeviceAccessPage';
import DeviceAccessPage from '../components/SystemSetting/DeviceAccessPage';
const { Header, Content } = Layout;
const { Text } = Typography;

View File

@@ -1,723 +0,0 @@
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 '../components/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>
);
}