Jelajahi Sumber

AI: 模拟设备 API

D8D AI 1 tahun lalu
induk
melakukan
221c60de8e

+ 65 - 0
src/hooks/useDeviceManagement.ts

@@ -0,0 +1,65 @@
+import { useState, useEffect } from 'react';
+import { Device } from '../types/device';
+import { message } from 'antd';
+import { mockDeviceApi } from '../services/mockDeviceApi';
+
+export const useDeviceManagement = () => {
+  const [devices, setDevices] = useState<Device[]>([]);
+  const [loading, setLoading] = useState(false);
+
+  useEffect(() => {
+    loadDevices();
+  }, []);
+
+  const loadDevices = async () => {
+    setLoading(true);
+    try {
+      const fetchedDevices = await mockDeviceApi.getAllDevices();
+      setDevices(fetchedDevices);
+    } catch (error) {
+      message.error('加载设备列表失败');
+    } finally {
+      setLoading(false);
+    }
+  };
+
+  const addDevice = async (device: Omit<Device, 'id'>) => {
+    try {
+      const newDevice = await mockDeviceApi.addDevice(device);
+      setDevices([...devices, newDevice]);
+      message.success('设备添加成功');
+    } catch (error) {
+      message.error('添加设备失败');
+    }
+  };
+
+  const updateDevice = async (updatedDevice: Device) => {
+    try {
+      await mockDeviceApi.updateDevice(updatedDevice);
+      setDevices(devices.map(device => 
+        device.id === updatedDevice.id ? updatedDevice : device
+      ));
+      message.success('设备信息更新成功');
+    } catch (error) {
+      message.error('更新设备信息失败');
+    }
+  };
+
+  const deleteDevice = async (deviceId: string) => {
+    try {
+      await mockDeviceApi.deleteDevice(deviceId);
+      setDevices(devices.filter(device => device.id !== deviceId));
+      message.success('设备删除成功');
+    } catch (error) {
+      message.error('删除设备失败');
+    }
+  };
+
+  return {
+    devices,
+    loading,
+    addDevice,
+    updateDevice,
+    deleteDevice
+  };
+};

+ 84 - 35
src/pages/DeviceManagement.tsx

@@ -1,53 +1,102 @@
-import React from 'react';
-import { Table, Button, Tag } from 'antd';
+import React, { useState } from 'react';
+import { Table, Button, Modal, Form, Input, Select, Spin } from 'antd';
+import { useDeviceManagement } from '../hooks/useDeviceManagement';
+import { Device } from '../types/device';
+
+const { Option } = Select;
 
 const DeviceManagement: React.FC = () => {
+  const { devices, loading, addDevice, updateDevice, deleteDevice } = useDeviceManagement();
+  const [isModalVisible, setIsModalVisible] = useState(false);
+  const [form] = Form.useForm();
+
   const columns = [
-    {
-      title: '设备ID',
-      dataIndex: 'id',
-      key: 'id',
-    },
-    {
-      title: 'IP地址',
-      dataIndex: 'ip',
-      key: 'ip',
-    },
-    {
-      title: '状态',
-      dataIndex: 'status',
-      key: 'status',
-      render: (status: string) => (
-        <Tag color={status === '在线' ? 'green' : 'red'}>
-          {status}
-        </Tag>
-      ),
-    },
+    { title: '设备名称', dataIndex: 'name', key: 'name' },
+    { title: 'IP地址', dataIndex: 'ipAddress', key: 'ipAddress' },
+    { title: '状态', dataIndex: 'status', key: 'status' },
+    { title: '最后在线时间', dataIndex: 'lastSeen', key: 'lastSeen' },
     {
       title: '操作',
       key: 'action',
-      render: () => (
-        <Button type="link">配置</Button>
+      render: (text: string, record: Device) => (
+        <span>
+          <Button type="link" onClick={() => handleEdit(record)}>编辑</Button>
+          <Button type="link" onClick={() => handleDelete(record.id)}>删除</Button>
+        </span>
       ),
     },
   ];
 
-  const data = [
-    {
-      key: '1',
-      id: 'DEVICE001',
-      ip: '192.168.1.100',
-      status: '在线',
-    },
-    // 更多数据...
-  ];
+  const showModal = () => {
+    setIsModalVisible(true);
+  };
+
+  const handleOk = () => {
+    form.validateFields().then(values => {
+      const device = {
+        ...values,
+        lastSeen: new Date().toISOString(),
+      };
+      if (form.getFieldValue('id')) {
+        updateDevice(device as Device);
+      } else {
+        addDevice(device);
+      }
+      setIsModalVisible(false);
+      form.resetFields();
+    });
+  };
+
+  const handleCancel = () => {
+    setIsModalVisible(false);
+    form.resetFields();
+  };
+
+  const handleEdit = (device: Device) => {
+    form.setFieldsValue(device);
+    setIsModalVisible(true);
+  };
+
+  const handleDelete = (id: string) => {
+    Modal.confirm({
+      title: '确认删除',
+      content: '确定要删除这个设备吗?',
+      onOk: () => deleteDevice(id),
+    });
+  };
 
   return (
     <div>
       <h1>设备管理</h1>
-      <Table columns={columns} dataSource={data} />
+      <Button type="primary" onClick={showModal} style={{ marginBottom: 16 }}>
+        添加设备
+      </Button>
+      {loading ? (
+        <Spin size="large" />
+      ) : (
+        <Table columns={columns} dataSource={devices} rowKey="id" />
+      )}
+      <Modal title="设备信息" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
+        <Form form={form} layout="vertical">
+          <Form.Item name="id" hidden>
+            <Input />
+          </Form.Item>
+          <Form.Item name="name" label="设备名称" rules={[{ required: true }]}>
+            <Input />
+          </Form.Item>
+          <Form.Item name="ipAddress" label="IP地址" rules={[{ required: true }]}>
+            <Input />
+          </Form.Item>
+          <Form.Item name="status" label="状态" rules={[{ required: true }]}>
+            <Select>
+              <Option value="online">在线</Option>
+              <Option value="offline">离线</Option>
+            </Select>
+          </Form.Item>
+        </Form>
+      </Modal>
     </div>
   );
-}
+};
 
 export default DeviceManagement;

+ 70 - 0
src/services/mockDeviceApi.ts

@@ -0,0 +1,70 @@
+import { Device } from '../types/device';
+
+// 生成唯一ID
+const generateId = (): string => {
+  return Date.now().toString(36) + Math.random().toString(36).substr(2);
+};
+
+// 从 localStorage 获取设备列表
+const getDevices = (): Device[] => {
+  const devices = localStorage.getItem('devices');
+  return devices ? JSON.parse(devices) : [];
+};
+
+// 保存设备列表到 localStorage
+const saveDevices = (devices: Device[]): void => {
+  localStorage.setItem('devices', JSON.stringify(devices));
+};
+
+// 模拟 API 延迟
+const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
+
+export const mockDeviceApi = {
+  // 获取所有设备
+  getAllDevices: async (): Promise<Device[]> => {
+    await delay(500); // 模拟网络延迟
+    return getDevices();
+  },
+
+  // 添加新设备
+  addDevice: async (device: Omit<Device, 'id'>): Promise<Device> => {
+    await delay(500);
+    const newDevice = { ...device, id: generateId() };
+    const devices = getDevices();
+    devices.push(newDevice);
+    saveDevices(devices);
+    return newDevice;
+  },
+
+  // 更新设备
+  updateDevice: async (updatedDevice: Device): Promise<Device> => {
+    await delay(500);
+    const devices = getDevices();
+    const index = devices.findIndex(d => d.id === updatedDevice.id);
+    if (index !== -1) {
+      devices[index] = updatedDevice;
+      saveDevices(devices);
+      return updatedDevice;
+    }
+    throw new Error('Device not found');
+  },
+
+  // 删除设备
+  deleteDevice: async (id: string): Promise<void> => {
+    await delay(500);
+    const devices = getDevices();
+    const updatedDevices = devices.filter(d => d.id !== id);
+    saveDevices(updatedDevices);
+  },
+
+  // 获取单个设备
+  getDevice: async (id: string): Promise<Device> => {
+    await delay(500);
+    const devices = getDevices();
+    const device = devices.find(d => d.id === id);
+    if (device) {
+      return device;
+    }
+    throw new Error('Device not found');
+  }
+};

+ 7 - 0
src/types/device.ts

@@ -0,0 +1,7 @@
+export interface Device {
+  id: string;
+  name: string;
+  ipAddress: string;
+  status: 'online' | 'offline';
+  lastSeen: string;
+}