import React, { useState, useEffect } from 'react';
import {
Table,
Input,
Button,
Form,
Select,
Space,
Tag,
message,
Modal,
Tabs,
Card,
InputNumber,
Checkbox,
Tooltip,
Row,
Col,
App,
} from 'antd';
import {
SearchOutlined,
ReloadOutlined,
PlusOutlined,
EditOutlined,
DeleteOutlined,
LinkOutlined,
DisconnectOutlined,
} from '@ant-design/icons';
import SerialNumGenerate from "./SerialNumGenerate"
import { getPlaneDeviceList, bindDrone, unbindDrone } from '@/api/device';
import { getOrgList } from '@/api/organization/index';
import { getSiteByOrgId, getStationList } from '@/api/stationManage/index';
import { getUser } from '@/api/user/index';
import { useSelector } from 'react-redux';
import { RootState } from '@/src/store';
import utils from '@/lib/utils';
// 模拟数据
const allDeviceList = [
{ id: 1, code: 'CAM-01', name: '摄像头 CAM-01', type: 'CAMERA', online: 'ONLINE', status: 'NORMAL' },
{ id: 2, code: 'CAM-02', name: '摄像头 CAM-02', type: 'CAMERA', online: 'OFFLINE', status: 'FAULT' },
{ id: 3, code: 'CAM-03', name: '摄像头 CAM-03', type: 'CAMERA', online: 'ONLINE', status: 'NORMAL' },
{ id: 4, code: 'CLEAN-01', name: '清洗机器人 CLEAN-01', type: 'CLEANING_DEVICE', online: 'ONLINE', status: 'IDLE' },
{ id: 5, code: 'CMB-A01', name: '汇流箱 CMB-A01', type: 'COMBINER_BOX', online: 'ONLINE', status: 'WARNING' },
{ id: 6, code: 'CMB-A02', name: '汇流箱 CMB-A02', type: 'COMBINER_BOX', online: 'ONLINE', status: 'NORMAL' },
{ id: 7, code: 'INV-A01', name: '逆变器 INV-A01', type: 'INVERTER', online: 'ONLINE', status: 'NORMAL' },
{ id: 8, code: 'INV-A02', name: '逆变器 INV-A02', type: 'INVERTER', online: 'ONLINE', status: 'WARNING' },
{ id: 9, code: 'INV-B01', name: '逆变器 INV-B01', type: 'INVERTER', online: 'ONLINE', status: 'NORMAL' },
{ id: 10, code: 'METER-01', name: '电表 METER-01', type: 'METER', online: 'ONLINE', status: 'NORMAL' },
{ id: 11, code: 'ROBOT-01', name: '运维机器人 ROBOT-01', type: 'ROBOT', online: 'ONLINE', status: 'IDLE' },
{ id: 12, code: 'DRONE-01', name: '无人机 DRONE-01', type: 'DRONE', online: 'OFFLINE', status: 'FAULT' },
{ id: 13, code: 'WEATHER-01', name: '气象站 WEATHER-01', type: 'WEATHER_STATION', online: 'ONLINE', status: 'NORMAL' },
];
// Tab 配置
const tabs = [
{ key: 'all', label: '设备管理', filter: () => true },
{ key: 'camera', label: '摄像头管理', filter: (item) => item.type === 'CAMERA' },
{ key: 'smart', label: '智能装备', filter: (item) => ['CLEANING_DEVICE', 'ROBOT', 'DRONE'].includes(item.type) },
];
export default function DeviceManagementPage() {
const [activeTab, setActiveTab] = useState('all');
const { modal } = App.useApp();
const [form] = Form.useForm();
const [loading, setLoading] = useState(false);
const [deviceList, setDeviceList] = useState(allDeviceList);
// 无人机相关状态
const { userInfo } = useSelector((state: RootState) => state.user);
const [droneList, setDroneList] = useState([]);
const [bindModalVisible, setBindModalVisible] = useState(false);
const [bindForm] = Form.useForm();
const [selectedDroneKeys, setSelectedDroneKeys] = useState([]);
// 下拉数据状态
const [orgOptions, setOrgOptions] = useState([]);
const [siteOptions, setSiteOptions] = useState([]);
const [userOptions, setUserOptions] = useState([]);
// ✅ 新增:全局匹配用的全量数据状态
const [allOrgOptions, setAllOrgOptions] = useState([]);
const [allSiteOptions, setAllSiteOptions] = useState([]);
const [allUserOptions, setAllUserOptions] = useState([]);
const fetchDroneList = async () => {
setLoading(true);
try {
const res: any = await getPlaneDeviceList();
if (res.code === 200) {
setDroneList(res.data?.detail || res.data || []);
}
} catch (err) {
utils.message.error('获取无人机列表失败');
} finally {
setLoading(false);
}
};
// 获取组织列表
const fetchOrgs = async () => {
try {
const res: any = await getOrgList({});
if (res.code === 200) {
setOrgOptions(res.rows || []);
}
} catch (err) {
console.error('获取组织列表失败', err);
}
};
// 根据组织获取场站
const fetchSites = async (orgId) => {
setSiteOptions([]);
try {
const res: any = await getSiteByOrgId({ id: orgId });
if (res.code === 200) {
setSiteOptions(res.data || []);
}
} catch (err) {
console.error('获取场站列表失败', err);
}
};
// 获取用户列表
const fetchUsers = async (siteId) => {
try {
const res: any = await getUser({ siteId, pageNum: 1, pageSize: 1000 });
if (res.code === 200) {
setUserOptions(res.rows || []);
}
} catch (err) {
console.error('获取用户列表失败', err);
}
};
// ✅ 新增:初始化时获取全量数据用于列表匹配
const fetchAllDataForMapping = async () => {
try {
const [orgRes, siteRes, userRes]: any = await Promise.all([
getOrgList({ pageNum: 1, pageSize: 1000 }),
getStationList({ pageNum: 1, pageSize: 1000 }),
getUser({ pageNum: 1, pageSize: 10000 })
]);
if (orgRes.code === 200) setAllOrgOptions(orgRes.rows || []);
if (siteRes.code === 200) setAllSiteOptions(siteRes.rows || []);
if (userRes.code === 200) setAllUserOptions(userRes.rows || []);
} catch (err) {
console.error('初始化全量数据失败', err);
}
};
useEffect(() => {
if (activeTab === 'drone') {
fetchDroneList();
fetchAllDataForMapping(); // 进入无人机管理时获取全量匹配数据
}
}, [activeTab]);
// 打开绑定弹窗
const openBindModal = async () => {
if (selectedDroneKeys.length === 0) {
return utils.message.warning('请先在列表中选中需要绑定的无人机');
}
setBindModalVisible(true);
await fetchOrgs();
// ✅ 修改:不再回显,仅填入已选 SN
bindForm.setFieldsValue({
sns: selectedDroneKeys.join(', '),
orgId: undefined,
siteId: undefined,
userId: undefined,
});
setSiteOptions([]);
setUserOptions([]);
};
const handleBind = async (values) => {
try {
const payload = {
siteId: values.siteId,
orgId: values.orgId,
userId: values.userId,
sns: values.sns.split(',').map(s => s.trim()),
};
const res: any = await bindDrone(payload);
if (res.code === 200 && res.data == true) {
utils.message.success('绑定成功');
setBindModalVisible(false);
setSelectedDroneKeys([]);
bindForm.resetFields();
fetchDroneList();
} else {
utils.message.error(res.msg || '绑定失败');
}
} catch (err) {
utils.message.error('操作异常');
}
};
const handleUnbind = (sns, type) => {
// ✅ 关键:过滤掉空、null、undefined、纯空格的项
const validSns = (sns || []).filter(item =>
item !== null &&
item !== undefined &&
item !== '' &&
item.trim() !== ''
);
// 如果过滤完没有有效SN,直接提示
if (validSns.length === 0) {
return utils.message.warning('未选择有效设备,无法解绑');
}
const typeText = { 1: '人员', 2: '场站', 3: '组织' }[type];
modal.confirm({
title: '确认解绑',
content: `确定要为选中的无人机清除${typeText}绑定吗?`,
okText: '确定',
cancelText: '取消',
onOk: async () => {
try {
// ✅ 传给接口的是过滤后的有效数组
const res: any = await unbindDrone({ sns: validSns, type });
if (res.code === 200) {
utils.message.success('解绑成功');
fetchDroneList();
setSelectedDroneKeys([]);
} else {
utils.message.error(res.msg || '解绑失败');
}
} catch (err) {
utils.message.error('操作异常');
}
}
});
};
const droneColumns = [
{
title: '设备名称', width: 150, dataIndex: 'drone_callsign', key: 'name'
},
//{ title: 'SN码', dataIndex: 'device_sn', key: 'sn' },
//{ title: '网关SN', dataIndex: 'gateway_sn', key: 'gsn' },
{
title: '所属组织',
key: 'orgName',
width: 150,
render: (_, record) => {
const org = allOrgOptions.find(o => o.id == record.orgId);
return (org?.orgName || org?.name || "未绑定");
},
},
{
title: '所属场站',
key: 'siteName',
width: 150,
render: (_, record) => {
const site = allSiteOptions.find(s => s.id == record.siteId);
return (site?.siteName || site?.name || "未绑定");
},
},
{
title: '负责人',
key: 'userName',
width: 150,
render: (_, record) => {
const user = allUserOptions.find(u => u.userId == record.userId);
return (user?.nickName || user?.userName || "未绑定")
},
},
{
title: '状态', width: 150,
dataIndex: 'onlineStatus', key: 'status', render: s =>