ota管理界面

This commit is contained in:
mmc
2026-09-22 19:37:13 +08:00
parent 300e2c221d
commit 8a7e239bd6
13 changed files with 2325 additions and 0 deletions

View File

@@ -0,0 +1,553 @@
import React, { useState, useEffect, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import {
Typography,
Card,
Upload,
Input,
Button,
Form,
Table,
Space,
Tag,
App,
Modal,
Select,
Popconfirm,
Tooltip,
} from 'antd';
import {
UploadOutlined,
ReloadOutlined,
ArrowUpOutlined,
ArrowDownOutlined,
DeleteOutlined,
InboxOutlined,
} from '@ant-design/icons';
import type { UploadProps } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import {
getMachineVersionList,
getFirmwarePackageList,
uploadFirmwarePackage,
deleteFirmwarePackage,
upgradeMachines,
rollbackMachines,
type MachineVersion,
type FirmwarePackage,
} from '@/api/ota';
const { Title, Text } = Typography;
const { TextArea } = Input;
const VERSION_PATTERN = /^v\d+\.\d+\.\d+$/;
function formatFileSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
}
export default function OTAManagement() {
const { t } = useTranslation();
const { modal, message } = App.useApp();
const [uploadForm] = Form.useForm();
const [machineList, setMachineList] = useState<MachineVersion[]>([]);
const [firmwareList, setFirmwareList] = useState<FirmwarePackage[]>([]);
const [loadingMachines, setLoadingMachines] = useState(false);
const [loadingFirmwares, setLoadingFirmwares] = useState(false);
const [submitting, setSubmitting] = useState(false);
const [selectedMachineIds, setSelectedMachineIds] = useState<React.Key[]>([]);
const [pendingFile, setPendingFile] = useState<File | null>(null);
const fetchMachines = async () => {
setLoadingMachines(true);
try {
const res = await getMachineVersionList();
if (res.code === 200) setMachineList(res.data);
} finally {
setLoadingMachines(false);
}
};
const fetchFirmwares = async () => {
setLoadingFirmwares(true);
try {
const res = await getFirmwarePackageList();
if (res.code === 200) setFirmwareList(res.data);
} finally {
setLoadingFirmwares(false);
}
};
useEffect(() => {
fetchMachines();
fetchFirmwares();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const refreshAll = () => {
fetchMachines();
fetchFirmwares();
};
const hasSelection = selectedMachineIds.length > 0;
// ====== 上传 ======
const uploadProps: UploadProps = {
accept: '.bin,.zip',
maxCount: 1,
beforeUpload: (file) => {
const isValidType = /\.(bin|zip)$/i.test(file.name);
if (!isValidType) {
message.error(t('systemSetting.ota.invalidFileType'));
return Upload.LIST_IGNORE;
}
setPendingFile(file);
return false; // 阻止自动上传
},
onRemove: () => {
setPendingFile(null);
},
file: pendingFile ? [pendingFile as any] : [],
};
const handleUploadSubmit = async () => {
try {
const values = await uploadForm.validateFields();
if (!pendingFile) {
message.warning(t('systemSetting.ota.noFileSelected'));
return;
}
setSubmitting(true);
const res = await uploadFirmwarePackage({
file: pendingFile,
version: values.version,
description: values.description,
});
if (res.code === 200) {
message.success(t('systemSetting.ota.uploadSuccess'));
uploadForm.resetFields();
setPendingFile(null);
fetchFirmwares();
}
} catch (err) {
// 表单校验失败
} finally {
setSubmitting(false);
}
};
const handleDeleteFirmware = async (record: FirmwarePackage) => {
await deleteFirmwarePackage(record.id);
message.success(t('common.deleteSuccess'));
fetchFirmwares();
};
// ====== 升级 ======
const showUpgradeModal = () => {
if (!hasSelection) {
message.warning(t('systemSetting.ota.noSelection'));
return;
}
if (firmwareList.length === 0) {
message.warning(t('systemSetting.ota.noFirmware'));
return;
}
let selectedVersion = firmwareList[0].version;
const content = (
<Form layout="vertical">
<Form.Item label={t('systemSetting.ota.selectTargetVersion')} required>
<Select
options={firmwareList.map(f => ({ label: `${f.version} (${f.fileName})`, value: f.version }))}
defaultValue={selectedVersion}
onChange={(v) => (selectedVersion = v)}
style={{ width: '100%' }}
/>
</Form.Item>
<Text type="secondary" style={{ fontSize: 12 }}>
{t('systemSetting.ota.confirmUpgrade', { count: selectedMachineIds.length, version: '—' })}
</Text>
</Form>
);
modal.confirm({
title: t('systemSetting.ota.batchUpgrade'),
content,
okText: t('common.confirm'),
cancelText: t('common.cancel'),
onOk: async () => {
setSubmitting(true);
try {
const res = await upgradeMachines({
machineIds: selectedMachineIds as number[],
targetVersion: selectedVersion,
});
if (res.code === 200) {
message.success(t('systemSetting.ota.upgradeSuccess'));
setSelectedMachineIds([]);
// 立即刷新一次显示 UPGRADING 状态,再延迟刷新为 SUCCESS
fetchMachines();
setTimeout(fetchMachines, 1800);
}
} finally {
setSubmitting(false);
}
},
});
};
const handleSingleUpgrade = (record: MachineVersion) => {
if (firmwareList.length === 0) {
message.warning(t('systemSetting.ota.noFirmware'));
return;
}
let selectedVersion = firmwareList[0].version;
modal.confirm({
title: t('systemSetting.ota.batchUpgrade'),
content: (
<Form layout="vertical">
<Form.Item label={t('systemSetting.ota.selectTargetVersion')} required>
<Select
options={firmwareList.map(f => ({ label: `${f.version} (${f.fileName})`, value: f.version }))}
defaultValue={selectedVersion}
onChange={(v) => (selectedVersion = v)}
style={{ width: '100%' }}
/>
</Form.Item>
</Form>
),
okText: t('common.confirm'),
cancelText: t('common.cancel'),
onOk: async () => {
setSubmitting(true);
try {
const res = await upgradeMachines({
machineIds: [record.id],
targetVersion: selectedVersion,
});
if (res.code === 200) {
message.success(t('systemSetting.ota.upgradeSuccess'));
fetchMachines();
setTimeout(fetchMachines, 1800);
}
} finally {
setSubmitting(false);
}
},
});
};
// ====== 回退 ======
const handleBatchRollback = () => {
if (!hasSelection) {
message.warning(t('systemSetting.ota.noSelection'));
return;
}
modal.confirm({
title: t('systemSetting.ota.batchRollback'),
content: t('systemSetting.ota.confirmRollback', { count: selectedMachineIds.length }),
okText: t('common.confirm'),
cancelText: t('common.cancel'),
onOk: async () => {
setSubmitting(true);
try {
const res = await rollbackMachines({ machineIds: selectedMachineIds as number[] });
if (res.code === 200) {
if (res.data.skippedNames.length > 0) {
message.warning(
res.data.skippedNames
.map(n => t('systemSetting.ota.noPreviousVersion', { name: n }))
.join(';')
);
}
if (res.data.rolledBack.length > 0) {
message.success(t('systemSetting.ota.rollbackSuccess'));
}
setSelectedMachineIds([]);
fetchMachines();
setTimeout(fetchMachines, 1800);
}
} finally {
setSubmitting(false);
}
},
});
};
const handleSingleRollback = (record: MachineVersion) => {
if (!record.previousVersion) {
message.warning(t('systemSetting.ota.noPreviousVersion', { name: record.name }));
return;
}
modal.confirm({
title: t('systemSetting.ota.batchRollback'),
content: t('systemSetting.ota.confirmRollback', { count: 1 }),
okText: t('common.confirm'),
cancelText: t('common.cancel'),
onOk: async () => {
setSubmitting(true);
try {
const res = await rollbackMachines({ machineIds: [record.id] });
if (res.code === 200) {
if (res.data.rolledBack.length > 0) {
message.success(t('systemSetting.ota.rollbackSuccess'));
}
fetchMachines();
setTimeout(fetchMachines, 1800);
}
} finally {
setSubmitting(false);
}
},
});
};
// ====== 列定义 ======
const firmwareColumns: ColumnsType<FirmwarePackage> = [
{ title: t('systemSetting.ota.version'), dataIndex: 'version', key: 'version', width: 120 },
{ title: t('systemSetting.ota.fileName'), dataIndex: 'fileName', key: 'fileName', ellipsis: true },
{
title: t('systemSetting.ota.fileSize'),
dataIndex: 'fileSize',
key: 'fileSize',
width: 120,
render: (v: number) => formatFileSize(v),
},
{ title: t('systemSetting.ota.description'), dataIndex: 'description', key: 'description', ellipsis: true },
{ title: t('systemSetting.ota.uploadTime'), dataIndex: 'uploadTime', key: 'uploadTime', width: 180 },
{
title: t('roles.actions'),
key: 'action',
width: 100,
render: (_: any, record: FirmwarePackage) => (
<Popconfirm
title={t('systemSetting.ota.deleteConfirm', { version: record.version })}
onConfirm={() => handleDeleteFirmware(record)}
okText={t('common.confirm')}
cancelText={t('common.cancel')}
>
<Button type="link" danger icon={<DeleteOutlined />}>
{t('roles.delete')}
</Button>
</Popconfirm>
),
},
];
const machineColumns: ColumnsType<MachineVersion> = [
{ title: t('systemSetting.ota.machineCode'), dataIndex: 'code', key: 'code', width: 120 },
{ title: t('devices.deviceName'), dataIndex: 'name', key: 'name', ellipsis: true },
{ title: t('common.type'), dataIndex: 'type', key: 'type', width: 140 },
{
title: t('devices.online'),
dataIndex: 'online',
key: 'online',
width: 100,
render: (v: string) => <Tag color={v === 'ONLINE' ? 'green' : 'red'}>{v}</Tag>,
},
{
title: t('systemSetting.ota.currentVersion'),
dataIndex: 'currentVersion',
key: 'currentVersion',
width: 130,
render: (v: string) => <Tag color="blue">{v}</Tag>,
},
{
title: t('systemSetting.ota.previousVersion'),
dataIndex: 'previousVersion',
key: 'previousVersion',
width: 130,
render: (v: string | null) => (v ? <Tag>{v}</Tag> : <Text type="secondary">—</Text>),
},
{
title: t('systemSetting.ota.lastUpgradeTime'),
dataIndex: 'lastUpgradeTime',
key: 'lastUpgradeTime',
width: 180,
render: (v: string | null) => v || <Text type="secondary">—</Text>,
},
{
title: t('systemSetting.ota.upgradeStatus'),
dataIndex: 'status',
key: 'status',
width: 110,
render: (v: MachineVersion['status']) => {
const map: Record<string, { color: string; key: string }> = {
IDLE: { color: 'default', key: 'statusIdle' },
UPGRADING: { color: 'processing', key: 'statusUpgrading' },
FAILED: { color: 'red', key: 'statusFailed' },
SUCCESS: { color: 'green', key: 'statusSuccess' },
};
const cfg = map[v] || map.IDLE;
return <Tag color={cfg.color}>{t(`systemSetting.ota.${cfg.key}`)}</Tag>;
},
},
{
title: t('roles.actions'),
key: 'action',
width: 160,
render: (_: any, record: MachineVersion) => (
<Space>
<Button
type="link"
size="small"
icon={<ArrowUpOutlined />}
onClick={() => handleSingleUpgrade(record)}
>
{t('systemSetting.ota.batchUpgrade')}
</Button>
<Button
type="link"
size="small"
icon={<ArrowDownOutlined />}
onClick={() => handleSingleRollback(record)}
disabled={!record.previousVersion}
>
{t('systemSetting.ota.batchRollback')}
</Button>
</Space>
),
},
];
const machineRowSelection = {
selectedRowKeys: selectedMachineIds,
onChange: (keys: React.Key[]) => setSelectedMachineIds(keys),
};
const uploadCard = (
<Card size="small" style={{ marginBottom: 12 }}>
<Title level={5} style={{ marginTop: 0, marginBottom: 12 }}>
{t('systemSetting.ota.uploadCard')}
</Title>
<Form form={uploadForm} layout="inline" style={{ flexWrap: 'wrap', gap: 8 }}>
<Form.Item
name="version"
label={t('systemSetting.ota.version')}
rules={[
{ required: true, message: t('systemSetting.ota.versionRequired') },
{ pattern: VERSION_PATTERN, message: t('systemSetting.ota.versionPatternHint') },
]}
>
<Input placeholder={t('systemSetting.ota.versionPlaceholder')} style={{ width: 200 }} />
</Form.Item>
<Form.Item name="description" label={t('systemSetting.ota.description')}>
<TextArea
placeholder={t('systemSetting.ota.descriptionPlaceholder')}
style={{ width: 320, minHeight: 32 }}
autoSize={{ minRows: 1, maxRows: 2 }}
/>
</Form.Item>
<Form.Item label={t('systemSetting.ota.firmwareFile')} required>
<Upload.Dragger
{...uploadProps}
multiple={false}
style={{ width: 320, padding: '8px 12px' }}
>
<p className="ant-upload-drag-icon">
<InboxOutlined />
</p>
<p className="ant-upload-text" style={{ fontSize: 12 }}>
{t('systemSetting.ota.dragHint')}
</p>
</Upload.Dragger>
</Form.Item>
<Form.Item>
<Button
type="primary"
icon={<UploadOutlined />}
loading={submitting}
onClick={handleUploadSubmit}
>
{t('systemSetting.ota.uploadBtn')}
</Button>
</Form.Item>
</Form>
</Card>
);
const firmwareCard = (
<Card size="small" style={{ marginBottom: 12 }}>
<Title level={5} style={{ marginTop: 0, marginBottom: 12 }}>
{t('systemSetting.ota.firmwareList')}
</Title>
<Table
rowKey="id"
size="small"
columns={firmwareColumns}
dataSource={firmwareList}
loading={loadingFirmwares}
pagination={{ pageSize: 10, showSizeChanger: true, showTotal: (total) => `${t('common.total')} ${total} ${t('common.items')}` }}
/>
</Card>
);
const machineCard = (
<Card size="small">
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12, flexWrap: 'wrap', gap: 8 }}>
<Title level={5} style={{ margin: 0 }}>
{t('systemSetting.ota.machineVersionList')}
</Title>
<Space wrap>
<Button
type="primary"
icon={<ArrowUpOutlined />}
onClick={showUpgradeModal}
disabled={!hasSelection}
loading={submitting}
>
{t('systemSetting.ota.batchUpgrade')}
{hasSelection ? ` (${selectedMachineIds.length})` : ''}
</Button>
<Button
icon={<ArrowDownOutlined />}
onClick={handleBatchRollback}
disabled={!hasSelection}
loading={submitting}
>
{t('systemSetting.ota.batchRollback')}
{hasSelection ? ` (${selectedMachineIds.length})` : ''}
</Button>
<Button icon={<ReloadOutlined />} onClick={refreshAll}>
{t('common.refresh')}
</Button>
</Space>
</div>
<Table
rowKey="id"
size="small"
columns={machineColumns}
dataSource={machineList}
loading={loadingMachines}
rowSelection={machineRowSelection}
scroll={{ x: 1200 }} // 添加这行
pagination={{
pageSize: 10,
showSizeChanger: true,
showQuickJumper: true,
showTotal: (total) => `${t('common.total')} ${total} ${t('common.items')}`,
}}
/>
</Card>
);
return (
<div style={{ padding: '8px 0' }}>
<div style={{ padding: '0 0 4px' }}>
<Title level={4} style={{ margin: 0, fontSize: 'clamp(14px, 1.2vw, 18px)' }}>
{t('systemSetting.ota.title')}
</Title>
</div>
{uploadCard}
{firmwareCard}
{machineCard}
</div>
);
}