diff --git a/src/api/machine.ts b/src/api/machine.ts new file mode 100644 index 0000000..1a6f877 --- /dev/null +++ b/src/api/machine.ts @@ -0,0 +1,9 @@ +import request from './request'; + +export function getDeviceRunningHistoryStatistics(data) { + return request({ + url: `/iot/device/runningHistoryStatistics`, + method: 'post', + data, + }); +} diff --git a/src/components/reports/MachineDataReport.tsx b/src/components/reports/MachineDataReport.tsx new file mode 100644 index 0000000..97a6f76 --- /dev/null +++ b/src/components/reports/MachineDataReport.tsx @@ -0,0 +1,388 @@ +import React, { useEffect, useState, useMemo, useCallback } from 'react'; +import { + Card, Row, Col, Select, DatePicker, Button, Space, Checkbox, Table, Tag, + Typography, message, Empty, Spin +} from 'antd'; +import { + RobotOutlined, SearchOutlined, DownloadOutlined, LineChartOutlined +} from '@ant-design/icons'; +import dayjs from 'dayjs'; +import { useTranslation } from 'react-i18next'; +import { useSelector } from 'react-redux'; +import { RootState } from '../../store'; +import { getSiteDevice } from '../../api/device'; +import { getDeviceRunningHistoryStatistics } from '../../api/machine'; +import { UniversalLineChart } from '../recharts'; +import utils from '@/lib/utils'; + + +const { RangePicker } = DatePicker; +const { Option } = Select; +const { Title } = Typography; + +// 参数配置:i18n key + 后端字段 + 单位 + 颜色 +const PARAM_CONFIG = [ + { key: 'voltage', labelKey: 'devices.rtVoltage', unit: 'V', color: '#1677ff' }, + { key: 'leftCurrent', labelKey: 'devices.rtLeftMotor', unit: 'A', color: '#52c41a' }, + { key: 'rightCurrent', labelKey: 'devices.rtRightMotor', unit: 'A', color: '#fa8c16' }, + { key: 'leftMeasureSpeed', labelKey: 'devices.rtLeftSpeed', unit: 'rpm', color: '#eb2f96' }, + { key: 'rightMeasureSpeed', labelKey: 'devices.rtRightSpeed', unit: 'rpm', color: '#722ed1' }, + { key: 'leftMotorTemp', labelKey: 'devices.rtLeftTemp', unit: '℃', color: '#13c2c2' }, + { key: 'rightMotorTemp', labelKey: 'devices.rtRightTemp', unit: '℃', color: '#f5222d' }, + { key: 'chipTemp', labelKey: 'devices.rtMainTemp', unit: '℃', color: '#2f54eb' }, +]; + +// 默认选中全部参数 +const DEFAULT_PARAM_KEYS = PARAM_CONFIG.map(p => p.key); + +// 兼容多种时间字段 +function getRowTime(row: any): string { + const t = row.createTime || row.ts || row.timestamp || row.time || row.recordTime || row.collectTime; + if (!t) return ''; + return dayjs(typeof t === 'number' ? t : String(t)).format('YYYY-MM-DD HH:mm:ss'); +} + +// 兼容多种返回结构 +function extractRows(res: any): any[] { + if (!res) return []; + if (Array.isArray(res)) return res; + if (Array.isArray(res.rows)) return res.rows; + if (Array.isArray(res.data)) return res.data; + if (res.data && Array.isArray(res.data.list)) return res.data.list; + if (res.data && Array.isArray(res.data.records)) return res.data.records; + return []; +} + +export default function MachineDataReport() { + const { t } = useTranslation(); + const { stationId, currentStation } = useSelector((state: RootState) => state.station); + + const [deviceList, setDeviceList] = useState([]); + const [deviceLoading, setDeviceLoading] = useState(false); + const [selectedDeviceSn, setSelectedDeviceSn] = useState(); + const [dateRange, setDateRange] = useState<[dayjs.Dayjs, dayjs.Dayjs]>([ + dayjs().startOf('day'), + dayjs(), + ]); + const [selectedParams, setSelectedParams] = useState(DEFAULT_PARAM_KEYS); + const [loading, setLoading] = useState(false); + const [rawRows, setRawRows] = useState([]); + + // 获取机器人列表 + const fetchDevices = useCallback(async () => { + if (!stationId) return; + setDeviceLoading(true); + try { + const res = await getSiteDevice({ + siteId: stationId, + pageSize: 9999, + pageNum: 1, + orgId: currentStation?.orgId, + }); + const rows = res?.code === 200 ? (res.rows || []) : []; + setDeviceList(rows); + if (rows.length > 0) { + setSelectedDeviceSn(rows[0].serialNumber); + } else { + setSelectedDeviceSn(undefined); + } + } catch (e) { + console.error('fetch devices failed', e); + } finally { + setDeviceLoading(false); + } + }, [stationId, currentStation, selectedDeviceSn]); + + useEffect(() => { + fetchDevices(); + }, [fetchDevices]); + + // 查询报表数据 + const handleQuery = useCallback(async () => { + if (!selectedDeviceSn) { + utils.message.warning(t('report.selectRobot')); + return; + } + if (selectedParams.length === 0) { + utils.message.warning(t('report.selectParameters')); + return; + } + setLoading(true); + try { + const params: any = { + deviceId: selectedDeviceSn, + + startTime: dateRange[0].format('YYYY-MM-DD HH:mm:ss'), + endTime: dateRange[1].format('YYYY-MM-DD HH:mm:ss'), + }; + const res = await getDeviceRunningHistoryStatistics(params); + const rows = extractRows(res); + setRawRows(rows); + if (rows.length === 0) { + utils.message.info(t('common.noData')); + } + } catch (e) { + console.error('fetch intraday data failed', e); + utils.message.error(t('common.noData')); + setRawRows([]); + } finally { + setLoading(false); + } + }, [selectedDeviceSn, dateRange, selectedParams, t]); + + // 进入页面自动查询一次(如果有默认设备) + useEffect(() => { + if (selectedDeviceSn && dateRange) { + handleQuery(); + } + }, [selectedDeviceSn]); + + // 整理图表数据:每行 { time, [paramKey]: value } + const chartData = useMemo(() => { + return rawRows.map(row => { + const item: any = { time: getRowTime(row) }; + selectedParams.forEach(k => { + const v = row[k]; + item[k] = (typeof v === 'number') ? v : (v != null ? Number(v) : null); + }); + return item; + }).sort((a, b) => (a.time < b.time ? -1 : a.time > b.time ? 1 : 0)); + }, [rawRows, selectedParams]); + + // 图表 series 配置 + const chartSeries = useMemo(() => { + return PARAM_CONFIG + .filter(p => selectedParams.includes(p.key)) + .map(p => ({ + key: p.key, + name: `${t(p.labelKey)}(${p.unit})`, + color: p.color, + })); + }, [selectedParams, t]); + + // 表格列 + const tableColumns = useMemo(() => { + const cols: any[] = [ + { + title: t('report.generateTime') || '时间', + dataIndex: '_time', + key: '_time', + width: 180, + fixed: 'left', + render: (v: string) => v || '-', + }, + ]; + PARAM_CONFIG + .filter(p => selectedParams.includes(p.key)) + .forEach(p => { + cols.push({ + title: `${t(p.labelKey)}(${p.unit})`, + dataIndex: p.key, + key: p.key, + width: 140, + render: (v: any) => (v != null && !isNaN(Number(v))) ? Number(v).toFixed(2) : '-', + }); + }); + return cols; + }, [selectedParams, t]); + + // 表格数据源 + const tableData = useMemo(() => { + return rawRows.map((row, idx) => { + const item: any = { + key: idx, + _time: getRowTime(row), + }; + PARAM_CONFIG.forEach(p => { + const v = row[p.key]; + item[p.key] = (typeof v === 'number') ? v : (v != null ? Number(v) : null); + }); + return item; + }).sort((a, b) => (a._time < b._time ? -1 : a._time > b._time ? 1 : 0)); + }, [rawRows]); + + // 导出 CSV + const handleExport = useCallback(() => { + if (tableData.length === 0) { + utils.message.warning(t('common.noData')); + return; + } + const headers = tableColumns.map((c: any) => c.title); + const keys = tableColumns.map((c: any) => c.dataIndex); + const lines = [headers.join(',')]; + tableData.forEach(row => { + lines.push(keys.map(k => { + const v = row[k]; + if (v == null) return ''; + const s = typeof v === 'number' ? v.toFixed(2) : String(v); + return `"${s.replace(/"/g, '""')}"`; + }).join(',')); + }); + const csv = '\uFEFF' + lines.join('\r\n'); + const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + const deviceName = deviceList.find(d => d.serialNumber === selectedDeviceSn)?.deviceAlias || selectedDeviceSn || 'machine'; + a.href = url; + a.download = `machine_data_${deviceName}_${dayjs().format('YYYYMMDD_HHmmss')}.csv`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); + }, [tableData, tableColumns, deviceList, selectedDeviceSn, t]); + + const cardStyle = { + borderRadius: 12, + border: '1px solid #f0f0f0', + boxShadow: '0 4px 12px rgba(0,0,0,0.05)', + }; + + return ( +
+ {/* 筛选栏 */} + +
+
+ + {t('report.selectRobot')}: + + +
+ +
+ + {t('common.timeRange')}: + + v && v[0] && v[1] && setDateRange([v[0], v[1]])} + style={{ width: 380 }} + /> +
+ +
+ + {t('report.selectParameters')}: + + setSelectedParams(v as string[])} + style={{ maxWidth: 700 }} + > + + {PARAM_CONFIG.map(p => ( + + {t(p.labelKey)} + + ))} + + +
+ +
+ + + + +
+
+
+ + {/* 统计曲线图 */} + + + + {t('report.aiAnalysisStatistics')} + + + } + extra={ + selectedParams.length > 0 && ( + + {t('common.total', { count: chartData.length })} {t('report.unitItem')} + + ) + } + > + + {chartData.length > 0 && chartSeries.length > 0 ? ( + + ) : ( + + )} + + + + {/* 数据表格 */} + + {t('report.machineRecords')} + + } + > + `${total}` }} + className="compact-table" + locale={{ emptyText: t('common.noData') }} + /> + + + ); +} diff --git a/src/locales/en/index.ts b/src/locales/en/index.ts index eecbeeb..e5f34af 100644 --- a/src/locales/en/index.ts +++ b/src/locales/en/index.ts @@ -2327,7 +2327,12 @@ const en = { totalWorkOrders: 'Total Work Orders', completionRate: 'Completion Rate', averageEfficiency: 'Average Efficiency', - aiAnalysisReport: 'ai Analysis Report', + machineAnalysisReport: 'Machine Data Report', + selectRobot: 'Select Robot', + selectParameters: 'Select Parameters', + query: 'Query', + exportTable: 'Export Table', + machineRecords: 'Machine Records', aiAnalysisStatistics: 'ai Analysis Statistics', aiDiagnosisDaily: 'ai Diagnosis Daily', alarmCount: 'Alarm Count', diff --git a/src/locales/zh/index.ts b/src/locales/zh/index.ts index 25efc40..2c89516 100644 --- a/src/locales/zh/index.ts +++ b/src/locales/zh/index.ts @@ -2360,7 +2360,13 @@ const zh = { totalWorkOrders: '工单总数', completionRate: '完成率', averageEfficiency: '平均效率', - aiAnalysisReport: 'AI分析报表', + machineAnalysisReport: '机器数据报表', + selectRobot: '机器人', + selectParameters: '选择参数', + query: '查询', + exportTable: '导出表格', + machineRecords: '机器记录', + aiAnalysisStatistics: 'AI分析统计', aiDiagnosisDaily: 'AI诊断每日', alarmCount: '告警数量', diff --git a/src/pages/ReportCenter.tsx b/src/pages/ReportCenter.tsx index 4f0d3f8..4fe44d4 100644 --- a/src/pages/ReportCenter.tsx +++ b/src/pages/ReportCenter.tsx @@ -20,6 +20,7 @@ import dayjs from 'dayjs'; import { ChevronRight } from 'lucide-react'; import { UniversalBarChart, UniversalLineChart, UniversalPieChart } from '../components/recharts'; import { useTranslation } from 'react-i18next'; +import MachineDataReport from '../components/reports/MachineDataReport'; const { TabPane } = Tabs; const { RangePicker } = DatePicker; @@ -207,405 +208,409 @@ export default function ReportCenterPage() { - + - - - - {overviewCards.map((card, idx) => ( - - - {/* 左侧文字区域 */} -
-
- {card.title} -
-
- {card.value} - {card.unit} -
- {/* 底部环比/备注 */} -
- {card.trend} -
-
- - {/* 右侧圆形图标区域 */} - -
- {card.icon} -
- -
- - ))} - - - {/* 筛选栏 */} -
-
- {t('report.reportCycle')}: - -
-
- {t('report.reportType')}: - -
-
- {t('report.dateRange')}: - -
-
- - - - - -
-
- - - {/* 左侧主内容区 */} - - {/* 月度综合经营分析 */} - {t('report.monthlyOperationAnalysis')}}> - - -
-
{t('report.generation')} (MWh)
-
{t('report.predictedGeneration')} (MWh)
-
PR (%)
-
- - - -
-
- {[ - { label: t('report.monthlyAccumulatedGeneration'), value: '138.6', unit: 'MWh' }, - { label: t('report.theoreticalGeneration'), value: '166.8', unit: 'MWh' }, - { label: t('report.prAverage'), value: '82.8', unit: '%' }, - { label: t('report.generationDeviation'), value: '-3.4', unit: '%', color: '#F53F3F' }, - { label: t('report.averageIrradiance'), value: '5.3', unit: t('report.unitIrradiancePerDay') }, - ].map((item, idx) => ( -
- {item.label} - {item.value} {item.unit} -
- ))} + {activeTab === 'ai' ? ( + + ) : ( + <> + + {overviewCards.map((card, idx) => ( +
+ + {/* 左侧文字区域 */} +
+
+ {card.title} +
+
+ {card.value} + {card.unit} +
+ {/* 底部环比/备注 */} +
+ {card.trend} +
- + + {/* 右侧圆形图标区域 */} + +
+ {card.icon} +
+ +
- - + ))} + - {/* 第二排:三个图表 */} - - - {t('report.generationMeteorology')}} - > -
- - - - - -
- + {/* 筛选栏 */} +
+
+ {t('report.reportCycle')}: + +
+
+ {t('report.reportType')}: + +
+
+ {t('report.dateRange')}: + +
+
+ + + + + +
+
+ + + {/* 左侧主内容区 */} +
+ {/* 月度综合经营分析 */} + {t('report.monthlyOperationAnalysis')}}> + + +
+
{t('report.generation')} (MWh)
+
{t('report.predictedGeneration')} (MWh)
+
PR (%)
+
+ + + +
+
+ {[ + { label: t('report.monthlyAccumulatedGeneration'), value: '138.6', unit: 'MWh' }, + { label: t('report.theoreticalGeneration'), value: '166.8', unit: 'MWh' }, + { label: t('report.prAverage'), value: '82.8', unit: '%' }, + { label: t('report.generationDeviation'), value: '-3.4', unit: '%', color: '#F53F3F' }, + { label: t('report.averageIrradiance'), value: '5.3', unit: t('report.unitIrradiancePerDay') }, + ].map((item, idx) => ( +
+ {item.label} + {item.value} {item.unit} +
+ ))} +
+
+ + - - - {t('report.workOrderAlertClosure')}} - > -
- - - - - -
- -
- + {/* 第二排:三个图表 */} + + + {t('report.generationMeteorology')}} + > +
+ + + + + +
+ +
+ - - {t('report.aiAnalysisStatistics')}} - > -
- +
+ {t('report.workOrderAlertClosure')}} + > +
+ + + + + +
+ +
+ -
- {aiAnalysisData.map((item, idx) => ( -
+ {t('report.aiAnalysisStatistics')}} + > +
+ + +
- -
- {item.type} -
- - {item.value} {t('report.unitItem')} - + {aiAnalysisData.map((item, idx) => ( +
+ +
+ {item.type} +
+ + {item.value} {t('report.unitItem')} + +
+ ))}
- ))} -
-
+
+ + + + {/* 订阅与分发 */} + {t('report.subscriptionDispatch')}}> + + +
{t('report.subscribers', { count: 6 })}
+
+ {[ + { name: '张运维', role: t('report.roleOmSupervisor'), img: 'https://img.icons8.com/fluency/48/user-male-circle.png' }, + { name: '李工程师', role: t('report.roleStationEngineer'), img: 'https://img.icons8.com/fluency/48/user-male-circle.png' }, + { name: '王运维', role: t('report.roleDeviceOm'), img: 'https://img.icons8.com/fluency/48/user-male-circle.png' }, + { name: '陈经理', role: t('report.roleOmManager'), img: 'https://img.icons8.com/fluency/48/user-male-circle.png' }, + ].map((p, idx) => ( + + + + ))} + +2 +
+ + + +
{t('report.dispatchChannels')}
+ + + + + + + + +
{t('report.sendPlan')}
+
+ + + {t('report.weeklyAutoSend')} + + +
+ + + + + + {/* 右侧边栏 */} + + {/* 报表目录 / 快捷下载 */} + {t('report.reportDirectory')}} extra={}> +
{text} + }, + { + title: t('roles.status'), dataIndex: 'status', width: 80, + render: (v) => {v} + }, + { + title: t('roles.actions'), width: 120, + render: () => ( + }> + + + + ) + } + ]} + dataSource={reportFileList} + pagination={false} + size="small" + className="compact-table" + /> + + + {/* 模板中心 */} + {t('report.templateCenter')}} extra={}> + + {reportTemplates.map((tpl, idx) => ( + +
+
+
+ {tpl.icon} +
+
{tpl.name}
+
+
{tpl.desc}
+
+ + ))} + + + + {/* 报表生成记录 */} + {t('report.generationRecords')}} extra={}> +
{v} + }, + { + title: t('roles.actions'), width: 90, + render: () => ( + + -
{t('report.subscribers', { count: 6 })}
-
- {[ - { name: '张运维', role: t('report.roleOmSupervisor'), img: 'https://img.icons8.com/fluency/48/user-male-circle.png' }, - { name: '李工程师', role: t('report.roleStationEngineer'), img: 'https://img.icons8.com/fluency/48/user-male-circle.png' }, - { name: '王运维', role: t('report.roleDeviceOm'), img: 'https://img.icons8.com/fluency/48/user-male-circle.png' }, - { name: '陈经理', role: t('report.roleOmManager'), img: 'https://img.icons8.com/fluency/48/user-male-circle.png' }, - ].map((p, idx) => ( - - - - ))} - +2 -
- - - -
{t('report.dispatchChannels')}
- - - - - - - - -
{t('report.sendPlan')}
-
- - - {t('report.weeklyAutoSend')} - - -
- - - - - - {/* 右侧边栏 */} - - {/* 报表目录 / 快捷下载 */} - {t('report.reportDirectory')}} extra={}> -
{text} - }, - { - title: t('roles.status'), dataIndex: 'status', width: 80, - render: (v) => {v} - }, - { - title: t('roles.actions'), width: 120, - render: () => ( - }> - - - - ) - } - ]} - dataSource={reportFileList} - pagination={false} - size="small" - className="compact-table" - /> - - - {/* 模板中心 */} - {t('report.templateCenter')}} extra={}> - - {reportTemplates.map((tpl, idx) => ( - -
-
-
- {tpl.icon} -
-
{tpl.name}
-
-
{tpl.desc}
-
- - ))} - - - - {/* 报表生成记录 */} - {t('report.generationRecords')}} extra={}> -
{v} - }, - { - title: t('roles.actions'), width: 90, - render: () => ( - -