Commit d35c48a5 authored by 陈龙's avatar 陈龙

feat: 新增箱线图、置信区间功能

parent c180e1d5
import React, { memo, useEffect, useMemo, useRef } from 'react'; import React, {memo, useEffect, useMemo, useRef} from 'react';
import { BasicChart } from '@wisdom-components/basicchart'; import {BasicChart} from '@wisdom-components/basicchart';
import PandaEmpty from '@wisdom-components/empty'; import PandaEmpty from '@wisdom-components/empty';
import optionGenerator, { alarmMarkLine, minMaxMarkPoint, offlineArea } from './utils'; import optionGenerator, {alarmMarkLine, minMaxMarkPoint, offlineArea} from './utils';
import { isArray, cloneDeep } from 'lodash'; import {isArray, cloneDeep} from 'lodash';
const SimgleChart = memo((props) => { const SimgleChart = memo((props) => {
const { const {
dataSource, dataSource,
contrast = false, contrast = false,
contrastOption = 'day', contrastOption = 'day',
smooth = true, smooth = true,
curveCenter, curveCenter,
showGridLine = false, showGridLine = false,
deviceAlarmSchemes, deviceAlarmSchemes,
} = props; chartType,
const chartRef = useRef(); justLine
} = props;
const chartRef = useRef();
const option = useMemo(() => { const option = useMemo(() => {
const config = { const config = {
needUnit: true, needUnit: true,
curveCenter, curveCenter,
showGridLine, showGridLine,
deviceAlarmSchemes, deviceAlarmSchemes,
showMarkLine: true, showMarkLine: true,
showPoint: true, showPoint: true,
}; chartType,
return optionGenerator(dataSource, null, contrast, contrastOption, smooth, config); justLine
}, [dataSource, smooth, curveCenter]); };
return optionGenerator(dataSource, null, contrast, contrastOption, smooth, config);
}, [dataSource, smooth, curveCenter]);
useEffect(() => { useEffect(() => {
chartRef.current?.resize?.(); chartRef.current?.resize?.();
const chart = chartRef.current?.getEchartsInstance?.(); const chart = chartRef.current?.getEchartsInstance?.();
function hander(params) { function hander(params) {
const { selected } = params; const {selected} = params;
const count = Object.values(selected || {}).filter((item) => item).length; const count = Object.values(selected || {}).filter((item) => item).length;
const option = cloneDeep(chart.getOption()); const option = cloneDeep(chart.getOption());
const needMarkLine = count === 1; const needMarkLine = count === 1;
option.series.forEach((item, index) => { option.series.forEach((item, index) => {
let offlineAreas = offlineArea(dataSource[index]); let offlineAreas = offlineArea(dataSource[index]);
if (offlineAreas.data?.length) { if (offlineAreas.data?.length) {
option.markArea = null; option.markArea = null;
item.markArea = offlineAreas; item.markArea = offlineAreas;
} }
if (needMarkLine && selected[item.name]) { if (needMarkLine && selected[item.name]) {
item.markLine = alarmMarkLine( item.markLine = alarmMarkLine(
dataSource[index], dataSource[index],
index, index,
[dataSource[index]], [dataSource[index]],
deviceAlarmSchemes, deviceAlarmSchemes,
); );
item.markPoint = minMaxMarkPoint(dataSource[index], index, [dataSource[index]]); item.markPoint = minMaxMarkPoint(dataSource[index], index, [dataSource[index]]);
} else { } else {
item.markLine = {}; item.markLine = {};
item.markPoint = {}; item.markPoint = {};
}
});
chart.setOption(option, true);
} }
});
chart.setOption(option, true);
}
if (!chart) return;
chart.on('legendselectchanged', hander);
return () => {
chart.off('legendselectchanged', hander);
};
}, [dataSource, deviceAlarmSchemes]);
// 网格开关,不更新整个图表 if (!chart) return;
useEffect(() => { chart.on('legendselectchanged', hander);
const chart = chartRef.current?.getEchartsInstance?.(); return () => {
if (!chart) return; chart.off('legendselectchanged', hander);
const option = chart.getOption(); };
// 交互指针 }, [dataSource, deviceAlarmSchemes]);
const tooltip = {
trigger: 'axis', // 网格开关,不更新整个图表
axisPointer: { useEffect(() => {
type: showGridLine ? 'cross' : 'line', const chart = chartRef.current?.getEchartsInstance?.();
}, if (!chart) return;
}; const option = chart.getOption();
// 网格线 // 交互指针
const axisConfig = { const tooltip = {
minorTick: { trigger: 'axis',
show: showGridLine, axisPointer: {
splitNumber: 2, type: showGridLine ? 'cross' : 'line',
}, },
minorSplitLine: { };
show: showGridLine, // 网格线
lineStyle: { const axisConfig = {
type: 'dashed', minorTick: {
}, show: showGridLine,
}, splitNumber: 2,
splitLine: { },
show: showGridLine, minorSplitLine: {
}, show: showGridLine,
}; lineStyle: {
let yAxis = axisConfig; type: 'dashed',
if (isArray(option.yAxis)) { },
yAxis = option.yAxis.map((item) => ({ ...axisConfig })); },
} splitLine: {
let xAxis = axisConfig; show: showGridLine,
chart.setOption({ },
xAxis, };
yAxis, let yAxis = axisConfig;
tooltip, if (isArray(option.yAxis)) {
}); yAxis = option.yAxis.map((item) => ({...axisConfig}));
}, [showGridLine]); }
let xAxis = axisConfig;
chart.setOption({
xAxis,
yAxis,
tooltip,
});
}, [showGridLine]);
// 数据都为空显示缺省页 // 数据都为空显示缺省页
const isEmpty = useMemo( const isEmpty = useMemo(
() => () =>
!dataSource || !dataSource ||
!dataSource.length || !dataSource.length ||
!dataSource.find((e) => e.dataModel && e.dataModel.length > 0), !dataSource.find((e) => e.dataModel && e.dataModel.length > 0),
[dataSource], [dataSource],
); );
return isEmpty ? ( return isEmpty ? (
<PandaEmpty /> <PandaEmpty/>
) : ( ) : (
<BasicChart ref={chartRef} option={option} notMerge style={{ width: '100%', height: '100%' }} /> <BasicChart ref={chartRef} option={option} notMerge style={{width: '100%', height: '100%'}}/>
); );
}); });
export default SimgleChart; export default SimgleChart;
...@@ -2,7 +2,7 @@ import React from 'react'; ...@@ -2,7 +2,7 @@ import React from 'react';
import HistoryView from '../index'; import HistoryView from '../index';
const deviceParams = [ const deviceParams = [
{ /* {
deviceCode: 'EGBF00000146', deviceCode: 'EGBF00000146',
sensors: '进水压力,出水瞬时流量,出水累计流量', sensors: '进水压力,出水瞬时流量,出水累计流量',
deviceType: '二供泵房', deviceType: '二供泵房',
...@@ -13,7 +13,7 @@ const deviceParams = [ ...@@ -13,7 +13,7 @@ const deviceParams = [
sensors: '进水压力,出水瞬时流量,出水累计流量', sensors: '进水压力,出水瞬时流量,出水累计流量',
deviceType: '二供泵房', deviceType: '二供泵房',
pointAddressID: 4, pointAddressID: 4,
}, },*/
{ {
deviceCode: 'EGBF00000002', deviceCode: 'EGBF00000002',
sensors: '进水压力,出水瞬时流量,出水累计流量', sensors: '进水压力,出水瞬时流量,出水累计流量',
......
...@@ -3,17 +3,20 @@ import HistoryView from '../index'; ...@@ -3,17 +3,20 @@ import HistoryView from '../index';
const deviceParams = [ const deviceParams = [
{ {
deviceCode: 'EGBF00000146', deviceCode: 'EGBF00000082',
sensors: '进水压力,出水瞬时流量,出水累计流量', sensors: '进水压力',
// sensors: '出水瞬时流量',
// sensors: '出水累计流量',
// sensors: '进水压力,出水瞬时流量,出水累计流量',
deviceType: '二供泵房', deviceType: '二供泵房',
pointAddressID: 4, pointAddressID: 4,
}, },
{ /* {
deviceCode: 'EGJZ00001113', deviceCode: 'EGBF00000083',
sensors: '出水瞬时流量,出水压力,泵1状态', sensors: '出水瞬时流量,出水压力,泵1状态',
deviceType: '二供机组', deviceType: '二供机组',
pointAddressID: 4, pointAddressID: 4,
}, },*/
// { // {
// deviceCode: 'EGJZ00001113', // deviceCode: 'EGJZ00001113',
// sensors: '出水压力', // sensors: '出水压力',
...@@ -24,7 +27,7 @@ const deviceParams = [ ...@@ -24,7 +27,7 @@ const deviceParams = [
const Demo = () => { const Demo = () => {
return ( return (
<div style={{ height: 700 }}> <div style={{ height: 700 }}>
<HistoryView deviceParams={deviceParams} defaultModel="table" /> <HistoryView deviceParams={deviceParams} defaultModel="curve" />
</div> </div>
); );
}; };
......
import React, { useContext, useEffect, useMemo, useState } from 'react'; import React, {useContext, useEffect, useMemo, useState} from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import classNames from 'classnames'; import classNames from 'classnames';
import { import {
Checkbox, Checkbox,
ConfigProvider, ConfigProvider,
DatePicker, DatePicker,
Radio, Radio,
Select, Select,
Spin, Spin,
Tabs, Tabs,
Tooltip, Tooltip,
Button, Button,
} from 'antd'; } from 'antd';
import { import {
CloseCircleFilled, CloseCircleFilled,
PlusCircleOutlined, PlusCircleOutlined,
QuestionCircleFilled, QuestionCircleFilled,
DownloadOutlined, DownloadOutlined,
} from '@ant-design/icons'; } from '@ant-design/icons';
import moment from 'moment'; import moment from 'moment';
import _ from 'lodash'; import _ from 'lodash';
import TimeRangePicker from '@wisdom-components/timerangepicker'; import TimeRangePicker from '@wisdom-components/timerangepicker';
import PandaEmpty from '@wisdom-components/empty'; import PandaEmpty from '@wisdom-components/empty';
import BasicTable from '@wisdom-components/basictable'; import BasicTable from '@wisdom-components/basictable';
import { getHistoryInfo, getDeviceAlarmScheme, getExportDeviceHistoryUrl } from './apis'; import {getHistoryInfo, getDeviceAlarmScheme, getExportDeviceHistoryUrl} from './apis';
import SimgleChart from './SingleChart'; import SimgleChart from './SingleChart';
import GridChart from './GridChart'; import GridChart from './GridChart';
import './index.less'; import './index.less';
import { globalConfig } from 'antd/lib/config-provider'; import {globalConfig} from 'antd/lib/config-provider';
const { RangePicker } = DatePicker; const {RangePicker} = DatePicker;
const { Option } = Select; const {Option} = Select;
const startFormat = 'YYYY-MM-DD 00:00:00'; const startFormat = 'YYYY-MM-DD 00:00:00';
const endFormat = 'YYYY-MM-DD 23:59:59'; const endFormat = 'YYYY-MM-DD 23:59:59';
...@@ -38,794 +38,837 @@ const timeFormat = 'YYYY-MM-DD HH:mm:ss'; ...@@ -38,794 +38,837 @@ const timeFormat = 'YYYY-MM-DD HH:mm:ss';
const dateFormat = 'YYYYMMDD'; const dateFormat = 'YYYYMMDD';
const timeList = [ const timeList = [
{ {
key: 'twelveHours', key: 'twelveHours',
name: '近12小时', name: '近12小时',
}, },
{ {
key: 'roundClock', key: 'roundClock',
name: '近24小时', name: '近24小时',
}, },
{ {
key: 'oneWeek', key: 'oneWeek',
name: '近1周', name: '近1周',
}, },
{ {
key: 'oneMonth', key: 'oneMonth',
name: '近1月', name: '近1月',
}, },
]; ];
const CheckboxData = [ const CheckboxData = [
{ {
key: 'curveCenter', key: 'curveCenter',
label: '曲线居中', label: '曲线居中',
checked: false, checked: false,
showInCurve: true, showInCurve: true,
showInTable: false, showInTable: false,
}, },
{ {
key: 'chartGrid', key: 'chartGrid',
label: '图表网格', label: '图表网格',
checked: true, checked: true,
showInCurve: true, showInCurve: true,
showInTable: false, showInTable: false,
}, },
{ {
key: 'ignoreOutliers', key: 'ignoreOutliers',
label: '数据滤波', label: '数据滤波',
type: 'updateIgnoreOutliers', type: 'updateIgnoreOutliers',
checked: false, checked: false,
showInCurve: true, showInCurve: true,
showInTable: true, showInTable: true,
tooltip: '数据滤波针对与样本平均值相差2个标准差以上的值进行过滤。', tooltip: '数据滤波针对与样本平均值相差2个标准差以上的值进行过滤。',
}, },
{ {
key: 'dataThin', key: 'justLine',
label: '数据抽稀', label: '仅查看曲线',
type: 'updateDataThin', type: '',
checked: true, checked: false,
showInCurve: false, showInCurve: false,
showInTable: true, showInTable: false,
}, },
{
key: 'dataThin',
label: '数据抽稀',
type: 'updateDataThin',
checked: true,
showInCurve: false,
showInTable: true,
},
]; ];
const timeIntervalList = [ const timeIntervalList = [
{ {
key: '5', key: '5',
zoom: '5', zoom: '5',
unit: 'min', unit: 'min',
name: '5分钟', name: '5分钟',
}, },
{ {
key: '10', key: '10',
zoom: '10', zoom: '10',
unit: 'min', unit: 'min',
name: '10分钟', name: '10分钟',
}, },
{ {
key: '30', key: '30',
zoom: '30', zoom: '30',
unit: 'min', unit: 'min',
name: '30分钟', name: '30分钟',
}, },
{ {
key: '1', key: '1',
zoom: '1', zoom: '1',
unit: 'h', unit: 'h',
name: '1小时', name: '1小时',
}, },
{ {
key: '2', key: '2',
zoom: '2', zoom: '2',
unit: 'h', unit: 'h',
name: '2小时', name: '2小时',
}, },
{ {
key: '4', key: '4',
zoom: '4', zoom: '4',
unit: 'h', unit: 'h',
name: '4小时', name: '4小时',
}, },
{ {
key: '6', key: '6',
zoom: '6', zoom: '6',
unit: 'h', unit: 'h',
name: '6小时', name: '6小时',
}, },
{ {
key: '12', key: '12',
zoom: '12', zoom: '12',
unit: 'h', unit: 'h',
name: '12小时', name: '12小时',
}, },
]; ];
const updateTime = (key) => { const updateTime = (key) => {
let start = ''; let start = '';
let end = ''; let end = '';
if (Array.isArray(key)) { if (Array.isArray(key)) {
start = moment(key[0]).format(timeFormat); start = moment(key[0]).format(timeFormat);
end = moment(key[1]).format(timeFormat); end = moment(key[1]).format(timeFormat);
} else { } else {
switch (key) { switch (key) {
case 'twelveHours': case 'twelveHours':
start = moment().subtract(12, 'hour').format(timeFormat); start = moment().subtract(12, 'hour').format(timeFormat);
end = moment().format(timeFormat); end = moment().format(timeFormat);
break; break;
case 'roundClock': case 'roundClock':
start = moment().subtract(24, 'hour').format(timeFormat); start = moment().subtract(24, 'hour').format(timeFormat);
end = moment().format(timeFormat); end = moment().format(timeFormat);
break; break;
case 'oneWeek': case 'oneWeek':
start = moment().subtract(7, 'day').format(timeFormat); start = moment().subtract(7, 'day').format(timeFormat);
end = moment().format(timeFormat); end = moment().format(timeFormat);
break; break;
case 'oneMonth': case 'oneMonth':
start = moment().subtract(30, 'day').format(timeFormat); start = moment().subtract(30, 'day').format(timeFormat);
end = moment().format(timeFormat); end = moment().format(timeFormat);
break; break;
}
} }
} return [
return [ {
{ dateFrom: start,
dateFrom: start, dateTo: end,
dateTo: end, },
}, ];
];
}; };
const DefaultDatePicker = (value) => [ const DefaultDatePicker = (value) => [
{ {
key: 1, key: 1,
value: moment(), value: moment(),
}, },
{ {
key: 2, key: 2,
value: moment().subtract(1, value), value: moment().subtract(1, value),
}, },
]; ];
const handleBatchTime = (arr, cOption) => { const handleBatchTime = (arr, cOption) => {
let newArr = []; let newArr = [];
arr.forEach((child) => { arr.forEach((child) => {
if (child.value) { if (child.value) {
newArr.push({ newArr.push({
dateFrom: moment(child.value).startOf(cOption).format(startFormat), dateFrom: moment(child.value).startOf(cOption).format(startFormat),
dateTo: moment(child.value).endOf(cOption).format(endFormat), dateTo: moment(child.value).endOf(cOption).format(endFormat),
}); });
} }
}); });
newArr = _.uniqWith(newArr, _.isEqual); // 去掉重复日期时间 newArr = _.uniqWith(newArr, _.isEqual); // 去掉重复日期时间
return newArr; return newArr;
}; };
const timeColumn = { const timeColumn = {
title: '采集时间', title: '采集时间',
dataIndex: 'time', dataIndex: 'time',
key: 'time', key: 'time',
width: 170, width: 170,
fixed: 'left', fixed: 'left',
ellipsis: true, ellipsis: true,
align: 'center', align: 'center',
}; };
const HistoryView = (props) => { const HistoryView = (props) => {
const { getPrefixCls } = useContext(ConfigProvider.ConfigContext); const {getPrefixCls} = useContext(ConfigProvider.ConfigContext);
const prefixCls = getPrefixCls('history-view'); const prefixCls = getPrefixCls('history-view');
const { const {
title, title,
grid, grid,
defaultChecked, defaultChecked,
tableProps, tableProps,
deviceParams, deviceParams,
defaultModel, defaultModel,
showModels, showModels,
needMarkLine, needMarkLine,
} = props; } = props;
const isBoxPlots = deviceParams?.length === 1 && deviceParams[0]?.sensors?.split(',').length === 1;
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [activeTabKey, setActiveTabKey] = useState(defaultModel); const [activeTabKey, setActiveTabKey] = useState(defaultModel);
// 时间模式: 自定义模式/同期对比模式 // 时间模式: 自定义模式/同期对比模式
const [timeValue, setTimeValue] = useState('customer'); const [timeValue, setTimeValue] = useState('customer');
// 自定义模式 // 自定义模式
const [customerChecked, setCustomerChecked] = useState(defaultChecked); // 时间快速选择类型值 const [customerChecked, setCustomerChecked] = useState(defaultChecked); // 时间快速选择类型值
const [customerTime, setCustomerTime] = useState(); // 自定义时间选择值 const [customerTime, setCustomerTime] = useState(); // 自定义时间选择值
// 同期对比模式 // 同期对比模式
const [contrastOption, setContrastOption] = useState('day'); // 对比时间类型: 日/月 const [contrastOption, setContrastOption] = useState('day'); // 对比时间类型: 日/月
const [datePickerArr, setDatePickerArr] = useState(DefaultDatePicker('day')); // 对比时间段配置值 const [datePickerArr, setDatePickerArr] = useState(DefaultDatePicker('day')); // 对比时间段配置值
const [checkboxData, setCheckboxData] = useState(() => [...CheckboxData]); // 曲线设置项 const [checkboxData, setCheckboxData] = useState(() => [...CheckboxData]); // 曲线设置项
const [dataThinKey, setDataThinKey] = useState(timeIntervalList[0].key); // 曲线抽稀时间设置 const [dataThinKey, setDataThinKey] = useState(timeIntervalList[0].key); // 曲线抽稀时间设置
const [columns, setColumns] = useState([]); const [columns, setColumns] = useState([]);
const [tableData, setTableData] = useState([]); const [tableData, setTableData] = useState([]);
const [chartDataSource, setChartDataSource] = useState([]); const [chartDataSource, setChartDataSource] = useState([]);
// 选择的时间范围值 const [chartType, setChartType] = useState('lineChart');
const dateRange = useMemo(() => { // 选择的时间范围值
if (timeValue === 'customer') { const dateRange = useMemo(() => {
return updateTime(customerChecked || customerTime); if (timeValue === 'customer') {
} else { return updateTime(customerChecked || customerTime);
return handleBatchTime(datePickerArr, contrastOption); } else {
} return handleBatchTime(datePickerArr, contrastOption);
}, [contrastOption, customerChecked, customerTime, datePickerArr, timeValue]); }
}, [contrastOption, customerChecked, customerTime, datePickerArr, timeValue]);
const configDependence = checkboxData
.filter((item) => ['curveCenter', 'chartGrid'].indexOf(item.key) === -1) const configDependence = checkboxData
.map((item) => item.checked) .filter((item) => ['curveCenter', 'chartGrid'].indexOf(item.key) === -1)
.join(','); .map((item) => item.checked)
// 数据配置 .join(',');
const dataConfig = useMemo(() => { // 数据配置
const initial = { const dataConfig = useMemo(() => {
ignoreOutliers: false, const initial = {
dataThin: false, ignoreOutliers: false,
zoom: '', // 数据抽稀时间 dataThin: false,
unit: '', // 数据抽稀时间单位 zoom: '', // 数据抽稀时间
unit: '', // 数据抽稀时间单位
};
// 曲线居中,过滤异常值,数据抽稀
const config = checkboxData.reduce(
(pre, item) => (item.key !== 'curveCenter' && (pre[item.key] = item.checked), pre),
initial,
);
// 数据抽稀时间单位
const dataThin = timeIntervalList.find((item) => item.key === dataThinKey);
config.zoom = activeTabKey === 'curve' ? '' : dataThin?.zoom ?? '';
config.unit = activeTabKey === 'curve' ? '' : dataThin?.unit ?? '';
config.dataThin = activeTabKey === 'curve' ? true : config.dataThin; // 曲线强制抽稀
return config;
}, [configDependence, dataThinKey, activeTabKey]);
// 图表居中
const [curveCenter, chartGrid] = useMemo(() => {
const curveCenter = checkboxData.find((item) => item.key === 'curveCenter')?.checked;
const chartGrid = checkboxData.find((item) => item.key === 'chartGrid')?.checked;
return [curveCenter, chartGrid];
}, [checkboxData]);
// 自定义模式: 快速选择
const onCustomerTimeChange = (key) => {
setCustomerChecked(key);
!!customerTime && setCustomerTime(null);
}; };
// 曲线居中,过滤异常值,数据抽稀
const config = checkboxData.reduce(
(pre, item) => (item.key !== 'curveCenter' && (pre[item.key] = item.checked), pre),
initial,
);
// 数据抽稀时间单位
const dataThin = timeIntervalList.find((item) => item.key === dataThinKey);
config.zoom = activeTabKey === 'curve' ? '' : dataThin?.zoom ?? '';
config.unit = activeTabKey === 'curve' ? '' : dataThin?.unit ?? '';
config.dataThin = activeTabKey === 'curve' ? true : config.dataThin; // 曲线强制抽稀
return config;
}, [configDependence, dataThinKey, activeTabKey]);
// 图表居中
const [curveCenter, chartGrid] = useMemo(() => {
const curveCenter = checkboxData.find((item) => item.key === 'curveCenter')?.checked;
const chartGrid = checkboxData.find((item) => item.key === 'chartGrid')?.checked;
return [curveCenter, chartGrid];
}, [checkboxData]);
// 自定义模式: 快速选择
const onCustomerTimeChange = (key) => {
setCustomerChecked(key);
!!customerTime && setCustomerTime(null);
};
// 自定义模式: 自定义时间选择
const onCustomerRangeChange = (value) => {
if (!value) {
// 时间清空,回到默认时间选择
setCustomerChecked(defaultChecked);
setCustomerTime(value);
} else {
setCustomerChecked(null);
setCustomerTime(value);
}
};
// 同期对比模式: 选择(日/月) // 自定义模式: 自定义时间选择
const onContrastChange = (value) => { const onCustomerRangeChange = (value) => {
setContrastOption(value); if (!value) {
setDatePickerArr([...DefaultDatePicker(value)]); // 时间清空,回到默认时间选择
}; setCustomerChecked(defaultChecked);
setCustomerTime(value);
} else {
setCustomerChecked(null);
setCustomerTime(value);
}
};
// 同期对比模式: 时间段选择 // 同期对比模式: 选择(日/月)
const onContrastPickerChange = (date, dateString, item) => { const onContrastChange = (value) => {
const arr = [...datePickerArr]; setContrastOption(value);
arr.forEach((child) => { setDatePickerArr([...DefaultDatePicker(value)]);
if (child.key === item.key) { };
child.value = date;
}
});
setDatePickerArr(arr);
};
// 同期对比模式: 新增日期选择组件
const handleAddDatePicker = () => {
setDatePickerArr([
...datePickerArr,
{
key: datePickerArr[datePickerArr.length - 1].key + 1,
value: '',
},
]);
};
// 同期对比模式: 删除日期选择组件
const handleDeleteDatePicker = (index) => {
const arr = [...datePickerArr];
arr.splice(index, 1);
setDatePickerArr(arr);
};
// 时间设置切换(自定义/同期对比)
const onTimeSetChange = (e) => {
setTimeValue(e.target.value);
if (e.target.value === 'contrast') {
// 同期对比
onContrastChange(contrastOption);
} else {
// 自定义
// 不需要处理
}
};
const renderTimeOption = () => { // 同期对比模式: 时间段选择
return ( const onContrastPickerChange = (date, dateString, item) => {
<div className={classNames(`${prefixCls}-date`)}> const arr = [...datePickerArr];
<div className={classNames(`${prefixCls}-label`)}>时间选择</div> arr.forEach((child) => {
<Radio.Group value={timeValue} onChange={onTimeSetChange}> if (child.key === item.key) {
<Radio.Button value="customer">自定义</Radio.Button> child.value = date;
<Radio.Button value="contrast">同期对比</Radio.Button> }
</Radio.Group> });
{timeValue === 'customer' && ( // 自定义 setDatePickerArr(arr);
<> };
<TimeRangePicker
onChange={onCustomerTimeChange}
value={customerChecked}
dataSource={timeList}
/>
<RangePicker
className={classNames(`${prefixCls}-custime-customer`)}
onChange={onCustomerRangeChange}
value={customerTime}
showTime
/>
</>
)}
{timeValue === 'contrast' && ( // 同期对比
<>
<Select value={contrastOption} style={{ width: 60 }} onChange={onContrastChange}>
<Option value="day"></Option>
<Option value="month"></Option>
</Select>
{datePickerArr.map((child, index) => (
<div key={child.key} className={classNames(`${prefixCls}-contrast-list`)}>
<div className={classNames(`${prefixCls}-contrast-wrap`)}>
<DatePicker
picker={contrastOption}
value={child.value}
onChange={(date, dateString) => onContrastPickerChange(date, dateString, child)}
/>
{datePickerArr.length > 2 && (
<div
className={classNames(`${prefixCls}-contrast-delete`)}
onClick={() => handleDeleteDatePicker(index)}
>
<CloseCircleFilled />
</div>
)}
</div>
{index < datePickerArr.length - 1 && (
<div className={classNames(`${prefixCls}-contrast-connect`)}></div>
)}
</div>
))}
{datePickerArr.length < 5 && <PlusCircleOutlined onClick={handleAddDatePicker} />}
</>
)}
</div>
);
};
// 曲线设置项选择/取消
const onCheckboxChange = (e, key) => {
let data = [...checkboxData];
data.forEach((item) => {
if (item.key === key) {
item.checked = e.target.checked;
}
});
setCheckboxData(data);
};
// 数据抽稀时间间隔 // 同期对比模式: 新增日期选择组件
const onTimeIntervalChange = (value) => { const handleAddDatePicker = () => {
setDataThinKey(value); setDatePickerArr([
}; ...datePickerArr,
{
key: datePickerArr[datePickerArr.length - 1].key + 1,
value: '',
},
]);
};
const renderCheckbox = (child) => { // 同期对比模式: 删除日期选择组件
const curveAccess = activeTabKey === 'curve' && child.showInCurve; const handleDeleteDatePicker = (index) => {
const tableAccess = activeTabKey === 'table' && child.showInTable; const arr = [...datePickerArr];
const gridOptions = ['curveCenter']; arr.splice(index, 1);
setDatePickerArr(arr);
};
if (grid && curveAccess && gridOptions.indexOf(child.key) === -1) return null; // 时间设置切换(自定义/同期对比)
return ( const onTimeSetChange = (e) => {
(curveAccess || tableAccess) && ( setTimeValue(e.target.value);
<> if (e.target.value === 'contrast') {
<Checkbox checked={child.checked} onChange={(e) => onCheckboxChange(e, child.key)}> // 同期对比
{child.label} onContrastChange(contrastOption);
</Checkbox> } else {
{child.tooltip && ( // 自定义
<Tooltip title={child.tooltip}> // 不需要处理
<QuestionCircleFilled className={`${prefixCls}-question`} /> }
</Tooltip> };
)}
</>
)
);
};
const renderCurveOption = () => { const renderTimeOption = () => {
return ( return (
<div className={classNames(`${prefixCls}-cover`)}> <div className={classNames(`${prefixCls}-date`)}>
<div className={classNames(`${prefixCls}-label`)}>曲线设置</div> <div className={classNames(`${prefixCls}-label`)}>时间选择</div>
{checkboxData.map((child) => { <Radio.Group value={timeValue} onChange={onTimeSetChange}>
const box = renderCheckbox(child); <Radio.Button value="customer">自定义</Radio.Button>
if (!box) return null; <Radio.Button value="contrast">同期对比</Radio.Button>
return ( </Radio.Group>
<div key={child.key} className={`${prefixCls}-cover-item`}> {timeValue === 'customer' && ( // 自定义
{box} <>
<TimeRangePicker
onChange={onCustomerTimeChange}
value={customerChecked}
dataSource={timeList}
/>
<RangePicker
className={classNames(`${prefixCls}-custime-customer`)}
onChange={onCustomerRangeChange}
value={customerTime}
showTime
/>
</>
)}
{timeValue === 'contrast' && ( // 同期对比
<>
<Select value={contrastOption} style={{width: 60}} onChange={onContrastChange}>
<Option value="day"></Option>
<Option value="month"></Option>
</Select>
{datePickerArr.map((child, index) => (
<div key={child.key} className={classNames(`${prefixCls}-contrast-list`)}>
<div className={classNames(`${prefixCls}-contrast-wrap`)}>
<DatePicker
picker={contrastOption}
value={child.value}
onChange={(date, dateString) => onContrastPickerChange(date, dateString, child)}
/>
{datePickerArr.length > 2 && (
<div
className={classNames(`${prefixCls}-contrast-delete`)}
onClick={() => handleDeleteDatePicker(index)}
>
<CloseCircleFilled/>
</div>
)}
</div>
{index < datePickerArr.length - 1 && (
<div className={classNames(`${prefixCls}-contrast-connect`)}></div>
)}
</div>
))}
{datePickerArr.length < 5 && <PlusCircleOutlined onClick={handleAddDatePicker}/>}
</>
)}
</div> </div>
); );
})} };
{activeTabKey === 'table' && (
<Select
value={dataThinKey}
style={{ width: 90 }}
onChange={onTimeIntervalChange}
disabled={!dataConfig.dataThin}
>
{timeIntervalList.map((child) => (
<Option key={child.key} unit={child.unit} value={child.key}>
{child.name}
</Option>
))}
</Select>
)}
</div>
);
};
const exportExcelBtn = () => {
deviceParams.forEach((i, r) => {
let timeFrom = dateRange[r]?.dateFrom || moment().format(startFormat);
let timeTo = dateRange[r]?.dateTo || moment().format(timeFormat);
let fileName = `数据报表-${i.deviceType}-${i.deviceCode}-${moment(timeFrom).format(
dateFormat,
)}${moment(timeTo).format(dateFormat)}`;
getExportDeviceHistoryUrl({
deviceType: i.deviceType,
deviceCode: i.deviceCode,
quotas: i.sensors,
startTime: timeFrom,
endTime: timeTo,
fileName: fileName,
})
.then((res) => {
if (res && res.code === -1) return message.error(res.msg);
const url = `${window.location.origin}/PandaCore/GCK/FileHandleContoller/Download/name?name=${res.data}&_site=${globalConfig?.userInfo?.site}`;
const aDom = document.createElement('a');
aDom.href = url;
aDom.click();
aDom.remove();
})
.catch((err) => {});
});
};
const handleTableData = (data) => { // 曲线设置项选择/取消
const ignoreOutliers = checkboxData.find((item) => item.key === 'ignoreOutliers').checked; const onCheckboxChange = (e, key) => {
const dataIndexAccess = (dataItem, index) => { let data = [...checkboxData];
const { stationCode, sensorName } = dataItem; let _index = data.findIndex(item => item.key === 'justLine'); // 仅查看曲线会在勾选了数据滤波后展示
return `${stationCode}-${sensorName}-${index}`; let _index1 = data.findIndex(item => item.key === 'ignoreOutliers'); // 仅查看曲线会在勾选了数据滤波后展示
data.forEach((item) => {
if (item.key === key) {
item.checked = e.target.checked;
}
});
if (key === 'ignoreOutliers') {
data[_index].showInCurve = e.target.checked;
data[_index].checked = e.target.checked;
}
if (key === 'chartType') {
data[_index1].showInCurve = e.target.value;
data[_index1].checked = false;
}
debugger
setCheckboxData(data);
}; };
let format = timeFormat; // 数据抽稀时间间隔
if (timeValue === 'contrast') { const onTimeIntervalChange = (value) => {
format = contrastOption === 'day' ? '2020-01-01 HH:mm:00' : '2020-01-DD HH:mm:00'; setDataThinKey(value);
} };
// 处理表头数据 const renderCheckbox = (child) => {
const columnsData = data.map((item, index) => { const curveAccess = activeTabKey === 'curve' && child.showInCurve;
const { stationCode, equipmentName, sensorName, unit, dataModel } = item; const tableAccess = activeTabKey === 'table' && child.showInTable;
const dataIndex = dataIndexAccess(item, index); const gridOptions = ['curveCenter'];
let col = {
title: `${equipmentName}-${sensorName}${unit ? `(${unit})` : ''}`, if (grid && curveAccess && gridOptions.indexOf(child.key) === -1) return null;
dataIndex: dataIndex, return (
key: dataIndex, (curveAccess || tableAccess) && (
ellipsis: true, <>
align: 'center', <Checkbox checked={child.checked} onChange={(e) => onCheckboxChange(e, child.key)}>
}; {child.label}
// 同期对比 </Checkbox>
if (timeValue === 'contrast' && dataModel[0]) { {child.tooltip && (
const time = item.dataModel[0].pt <Tooltip title={child.tooltip}>
.slice(0, contrastOption === 'day' ? 10 : 7) <QuestionCircleFilled className={`${prefixCls}-question`}/>
.replace(/-/g, ''); </Tooltip>
col.title = `${equipmentName}-${sensorName}-${time}`; )}
} </>
return col; )
}); );
};
// 格式化时间对齐数据, 生成行数 const renderCurveOption = (isChart, isSingle) => {
const timeData = {}; return (
<div className={classNames(`${prefixCls}-cover`)}>
{
isChart && isSingle ? <>
<div className={classNames(`${prefixCls}-label`)}>曲线形态</div>
<Radio.Group value={chartType} onChange={(e) => {
let _value = e.target.value;
setChartType(_value);
onCheckboxChange({target: {value: _value !== 'boxChart'}}, 'chartType')
}}>
<Radio.Button value={'lineChart'}>线形图</Radio.Button>
<Radio.Button value={'boxChart'}>箱线图</Radio.Button>
</Radio.Group></> : ''
}
<div className={classNames(`${prefixCls}-label`)}>曲线设置</div>
{checkboxData.map((child) => {
const box = renderCheckbox(child);
if (!box) return null;
return (
<div key={child.key} className={`${prefixCls}-cover-item`}>
{box}
</div>
);
})}
{activeTabKey === 'table' && (
<Select
value={dataThinKey}
style={{width: 90}}
onChange={onTimeIntervalChange}
disabled={!dataConfig.dataThin}
>
{timeIntervalList.map((child) => (
<Option key={child.key} unit={child.unit} value={child.key}>
{child.name}
</Option>
))}
</Select>
)}
</div>
);
};
const buildDefaultData = (time) => { const exportExcelBtn = () => {
const obj = { key: time, time: time }; deviceParams.forEach((i, r) => {
data.forEach((item, index) => { let timeFrom = dateRange[r]?.dateFrom || moment().format(startFormat);
const dataIndex = dataIndexAccess(item, index); let timeTo = dateRange[r]?.dateTo || moment().format(timeFormat);
obj[dataIndex] = ''; let fileName = `数据报表-${i.deviceType}-${i.deviceCode}-${moment(timeFrom).format(
}); dateFormat,
return obj; )}${moment(timeTo).format(dateFormat)}`;
getExportDeviceHistoryUrl({
deviceType: i.deviceType,
deviceCode: i.deviceCode,
quotas: i.sensors,
startTime: timeFrom,
endTime: timeTo,
fileName: fileName,
})
.then((res) => {
if (res && res.code === -1) return message.error(res.msg);
const url = `${window.location.origin}/PandaCore/GCK/FileHandleContoller/Download/name?name=${res.data}&_site=${globalConfig?.userInfo?.site}`;
const aDom = document.createElement('a');
aDom.href = url;
aDom.click();
aDom.remove();
})
.catch((err) => {
});
});
}; };
data.forEach((item, index) => {
const { stationCode, sensorName, dataModel } = item;
dataModel.forEach((data) => {
const formatTime = moment(data.pt).format(format);
let time = formatTime; const handleTableData = (data) => {
const ignoreOutliers = checkboxData.find((item) => item.key === 'ignoreOutliers').checked;
const dataIndexAccess = (dataItem, index) => {
const {stationCode, sensorName} = dataItem;
return `${stationCode}-${sensorName}-${index}`;
};
let format = timeFormat;
if (timeValue === 'contrast') { if (timeValue === 'contrast') {
time = time.slice(contrastOption === 'day' ? 11 : 8, 16); format = contrastOption === 'day' ? '2020-01-01 HH:mm:00' : '2020-01-DD HH:mm:00';
} }
timeData[formatTime] = timeData[formatTime] || buildDefaultData(time); // 处理表头数据
}); const columnsData = data.map((item, index) => {
}); const {stationCode, equipmentName, sensorName, unit, dataModel} = item;
const dataIndex = dataIndexAccess(item, index);
let col = {
title: `${equipmentName}-${sensorName}${unit ? `(${unit})` : ''}`,
dataIndex: dataIndex,
key: dataIndex,
ellipsis: true,
align: 'center',
};
// 同期对比
if (timeValue === 'contrast' && dataModel[0]) {
const time = item.dataModel[0].pt
.slice(0, contrastOption === 'day' ? 10 : 7)
.replace(/-/g, '');
col.title = `${equipmentName}-${sensorName}-${time}`;
}
return col;
});
// 处理表格数据 // 格式化时间对齐数据, 生成行数
data.forEach((child, index) => { const timeData = {};
const { dataModel } = child;
const dataIndex = dataIndexAccess(child, index); const buildDefaultData = (time) => {
dataModel.forEach((value, j) => { const obj = {key: time, time: time};
const formatTime = moment(value.pt).format(format); data.forEach((item, index) => {
const dataRow = timeData[formatTime]; const dataIndex = dataIndexAccess(item, index);
if (dataRow) { obj[dataIndex] = '';
dataRow[dataIndex] = value.pv === null || value.pv === undefined ? '' : value.pv; });
} return obj;
}); };
}); data.forEach((item, index) => {
const timeSort = (a, b) => { const {stationCode, sensorName, dataModel} = item;
let aa = a, dataModel.forEach((data) => {
bb = b; const formatTime = moment(data.pt).format(format);
if (timeValue === 'contrast') {
aa = a.slice(contrastOption === 'day' ? 11 : 8, 16); let time = formatTime;
bb = b.slice(contrastOption === 'day' ? 11 : 8, 16); if (timeValue === 'contrast') {
} time = time.slice(contrastOption === 'day' ? 11 : 8, 16);
return aa.localeCompare(bb); }
timeData[formatTime] = timeData[formatTime] || buildDefaultData(time);
});
});
// 处理表格数据
data.forEach((child, index) => {
const {dataModel} = child;
const dataIndex = dataIndexAccess(child, index);
dataModel.forEach((value, j) => {
const formatTime = moment(value.pt).format(format);
const dataRow = timeData[formatTime];
if (dataRow) {
dataRow[dataIndex] = value.pv === null || value.pv === undefined ? '' : value.pv;
}
});
});
const timeSort = (a, b) => {
let aa = a,
bb = b;
if (timeValue === 'contrast') {
aa = a.slice(contrastOption === 'day' ? 11 : 8, 16);
bb = b.slice(contrastOption === 'day' ? 11 : 8, 16);
}
return aa.localeCompare(bb);
};
const times = Object.keys(timeData).sort(timeSort);
const tableData = times.map((time) => timeData[time]);
setColumns([timeColumn, ...columnsData]);
setTableData(tableData);
}; };
const times = Object.keys(timeData).sort(timeSort);
const tableData = times.map((time) => timeData[time]); const [deviceAlarmSchemes, setDeviceAlarmSchemes] = useState([]);
setColumns([timeColumn, ...columnsData]); const beforChangeParams = (value = {}) => {
setTableData(tableData); if (!needMarkLine) return Promise.resolve();
}; return getDeviceAlarmScheme({
data: deviceParams.map((item) => ({
const [deviceAlarmSchemes, setDeviceAlarmSchemes] = useState([]); deviceType: item.deviceType,
const beforChangeParams = (value = {}) => { deviceCode: item.deviceCode,
if (!needMarkLine) return Promise.resolve(); pointAddressID: item.pointAddressID,
return getDeviceAlarmScheme({ sensorName: item.sensors,
data: deviceParams.map((item) => ({ })),
deviceType: item.deviceType, })
deviceCode: item.deviceCode, .then((res) => {
pointAddressID: item.pointAddressID, if (res.code === 0) setDeviceAlarmSchemes(res.data || []);
sensorName: item.sensors, else setDeviceAlarmSchemes([]);
})), return Promise.resolve();
}) })
.then((res) => { .catch((err) => {
if (res.code === 0) setDeviceAlarmSchemes(res.data || []); setDeviceAlarmSchemes([]);
else setDeviceAlarmSchemes([]); return Promise.resolve();
return Promise.resolve();
})
.catch((err) => {
setDeviceAlarmSchemes([]);
return Promise.resolve();
});
};
const handleDataThinKey = (diffDays) => {
// edit by zy 根据选择的时长控制抽稀频度
if (diffDays >= 7 && diffDays < 15) {
return { unit: 'h', zoom: '2' };
} else if (diffDays >= 15 && diffDays < 30) {
return { unit: 'h', zoom: '4' };
} else if (diffDays >= 30) {
return { unit: 'h', zoom: '6' };
} else {
return {};
}
};
// 处理接口服务参数的变化
const onChangeParams = (value = {}) => {
const { dateRange, isDilute, ignoreOutliers, zoom, unit } = value;
const requestArr = [];
const acrossTables = [];
deviceParams.forEach((i) => {
if (i.sensors && i.deviceCode && i.deviceCode)
acrossTables.push(_.omit(i, ['pointAddressID']));
});
if (!acrossTables?.length) {
handleTableData([]);
setChartDataSource([]);
return;
}
dateRange.forEach((item) => {
const param = {
isDilute,
zoom,
unit,
ignoreOutliers,
isVertical: false, // 是否查询竖表
dateFrom: item.dateFrom,
dateTo: item.dateTo,
acrossTables,
};
let diffDays = moment(item.dateTo).diff(moment(item.dateFrom), 'days');
let zoomParam = activeTabKey === 'curve' ? handleDataThinKey(diffDays) : {};
requestArr.push(getHistoryInfo({ ...param, ...zoomParam }));
});
setLoading(true);
Promise.all(requestArr).then((results) => {
if (results.length) {
let data = [];
results.forEach((res, index) => {
const { dateFrom, dateTo } = dateRange?.[index] ?? {};
if (res.code === 0 && res.data.length) {
res.data.forEach((d) => {
d.dateFrom = dateFrom;
d.dateTo = dateTo;
}); });
deviceParams.forEach((p) => { };
// 返回数据按查询指标顺序排序
const sensors = p.sensors?.split(',') ?? []; const handleDataThinKey = (diffDays) => {
const list = sensors.map((s) => { // edit by zy 根据选择的时长控制抽稀频度
const dataItem = res.data.find( if (diffDays >= 7 && diffDays < 15) {
(d) => d.stationCode === p.deviceCode && d.sensorName === s, return {unit: 'h', zoom: '2'};
); } else if (diffDays >= 15 && diffDays < 30) {
dataItem.dateFrom = dateFrom; return {unit: 'h', zoom: '4'};
dataItem.dateTo = dateTo; } else if (diffDays >= 30) {
return dataItem; return {unit: 'h', zoom: '6'};
}); } else if (diffDays < 7 && diffDays >= 2) {
data = data.concat(list); return {unit: 'min', zoom: '40'};
} else if (diffDays < 2 && diffDays >= 1) {
return {unit: 'min', zoom: '30'};
} else {
return {unit: 'min', zoom: '10'};
}
};
// 处理接口服务参数的变化
const onChangeParams = (value = {}) => {
const {dateRange, isDilute, ignoreOutliers, zoom, unit} = value;
const requestArr = [];
const acrossTables = [];
deviceParams.forEach((i) => {
if (i.sensors && i.deviceCode && i.deviceCode)
acrossTables.push(_.omit(i, ['pointAddressID']));
});
if (!acrossTables?.length) {
handleTableData([]);
setChartDataSource([]);
return;
}
dateRange.forEach((item) => {
let _showLine = checkboxData.find(item => item.key === 'justLine');
const param = {
isDilute,
zoom,
unit,
ignoreOutliers,
isVertical: false, // 是否查询竖表
dateFrom: item.dateFrom,
dateTo: item.dateTo,
acrossTables,
isBoxPlots: isBoxPlots
};
let diffDays = moment(item.dateTo).diff(moment(item.dateFrom), 'days');
let zoomParam = activeTabKey === 'curve' ? handleDataThinKey(diffDays) : {};
requestArr.push(getHistoryInfo({...param, ...zoomParam}));
});
setLoading(true);
Promise.all(requestArr).then((results) => {
if (results.length) {
let data = [];
results.forEach((res, index) => {
const {dateFrom, dateTo} = dateRange?.[index] ?? {};
if (res.code === 0 && res.data.length) {
res.data.forEach((d) => {
d.dateFrom = dateFrom;
d.dateTo = dateTo;
});
deviceParams.forEach((p) => {
// 返回数据按查询指标顺序排序
const sensors = p.sensors?.split(',') ?? [];
const list = sensors.map((s) => {
const dataItem = res.data.find(
(d) => d.stationCode === p.deviceCode && d.sensorName === s,
);
dataItem.dateFrom = dateFrom;
dataItem.dateTo = dateTo;
return dataItem;
});
data = data.concat(list);
});
}
});
setLoading(false);
handleTableData(data);
setChartDataSource(data);
}
});
};
useEffect(() => {
const {dataThin, ignoreOutliers, zoom, unit} = dataConfig;
beforChangeParams().finally(() => {
onChangeParams({
isDilute: dataThin,
ignoreOutliers,
zoom,
unit,
dateRange,
isBoxPlots: isBoxPlots
}); });
}
}); });
setLoading(false); }, [dateRange, dataConfig, deviceParams, chartType]);
handleTableData(data);
setChartDataSource(data); const renderPanel = (model) => {
} if (model === 'curve') {
}); return (
}; <>
<div className={`${prefixCls}-options`}>
useEffect(() => { {renderTimeOption()}
const { dataThin, ignoreOutliers, zoom, unit } = dataConfig; {renderCurveOption(true, (deviceParams?.length === 1 && deviceParams[0]?.sensors?.split(',').length === 1))}
beforChangeParams().finally(() => { </div>
onChangeParams({ <div className={`${prefixCls}-content`}>
isDilute: dataThin, {!chartDataSource.length ? (
ignoreOutliers, <PandaEmpty/>
zoom, ) : grid === true ? (
unit, <GridChart
dateRange, curveCenter={curveCenter}
}); prefixCls={prefixCls}
}); dataSource={chartDataSource}
}, [dateRange, dataConfig, deviceParams]); contrast={timeValue === 'contrast'}
contrastOption={contrastOption}
const renderPanel = (model) => { deviceAlarmSchemes={deviceAlarmSchemes}
if (model === 'curve') { />
return ( ) : (
<> <SimgleChart
<div className={`${prefixCls}-options`}> curveCenter={curveCenter}
{renderTimeOption()} showGridLine={chartGrid}
{renderCurveOption()} prefixCls={prefixCls}
</div> dataSource={chartDataSource}
<div className={`${prefixCls}-content`}> justLine={!!checkboxData.find(item => item.key === 'justLine' && item.checked)}
{!chartDataSource.length ? ( chartType={isBoxPlots ? chartType : null}
<PandaEmpty /> contrast={timeValue === 'contrast'}
) : grid === true ? ( contrastOption={contrastOption}
<GridChart deviceAlarmSchemes={deviceAlarmSchemes}
curveCenter={curveCenter} />
prefixCls={prefixCls} )}
dataSource={chartDataSource} </div>
contrast={timeValue === 'contrast'} </>
contrastOption={contrastOption} );
deviceAlarmSchemes={deviceAlarmSchemes} }
/> if (model === 'table') {
) : ( return (
<SimgleChart <>
curveCenter={curveCenter} <div className={`${prefixCls}-options`}>
showGridLine={chartGrid} {renderTimeOption()}
prefixCls={prefixCls} {renderCurveOption()}
dataSource={chartDataSource} </div>
contrast={timeValue === 'contrast'} <div className={`${prefixCls}-content`}>
contrastOption={contrastOption} {chartDataSource.length > 0 ? (
deviceAlarmSchemes={deviceAlarmSchemes} <BasicTable
/> dataSource={tableData}
)} columns={columns}
</div> {...tableProps}
</> pagination={false}
); onChange={() => {
} }}
if (model === 'table') { />
return ( ) : (
<> <PandaEmpty/>
<div className={`${prefixCls}-options`}> )}
{renderTimeOption()} </div>
{renderCurveOption()} </>
</div> );
<div className={`${prefixCls}-content`}> }
{chartDataSource.length > 0 ? ( };
<BasicTable
dataSource={tableData} return (
columns={columns} <div className={classNames(prefixCls)}>
{...tableProps} <Spin spinning={loading} wrapperClassName={classNames(`${prefixCls}-spin`)}>
pagination={false} {showModels.length === 1 && (
onChange={() => {}} <div className={`${prefixCls}-single-panel`}>{renderPanel(showModels[0])}</div>
/> )}
) : ( {showModels.length > 1 && (
<PandaEmpty /> <Tabs
)} activeKey={activeTabKey}
</div> onChange={(key) => setActiveTabKey(key)}
</> centered
); tabBarExtraContent={{
} left: <h3>{title}</h3>,
}; right: (
<div className={`${prefixCls}-extra-right`}>
return ( {activeTabKey === 'table' && (
<div className={classNames(prefixCls)}> <Button type="link" onClick={exportExcelBtn}>
<Spin spinning={loading} wrapperClassName={classNames(`${prefixCls}-spin`)}> <DownloadOutlined/>
{showModels.length === 1 && ( 下载
<div className={`${prefixCls}-single-panel`}>{renderPanel(showModels[0])}</div> </Button>
)} )}
{showModels.length > 1 && ( </div>
<Tabs ),
activeKey={activeTabKey} }}
onChange={(key) => setActiveTabKey(key)} >
centered <Tabs.TabPane key="curve" tab="曲线">
tabBarExtraContent={{ {renderPanel('curve')}
left: <h3>{title}</h3>, </Tabs.TabPane>
right: ( <Tabs.TabPane key="table" tab="表格">
<div className={`${prefixCls}-extra-right`}> {renderPanel('table')}
{activeTabKey === 'table' && ( </Tabs.TabPane>
<Button type="link" onClick={exportExcelBtn}> </Tabs>
<DownloadOutlined /> )}
下载 </Spin>
</Button> </div>
)} );
</div>
),
}}
>
<Tabs.TabPane key="curve" tab="曲线">
{renderPanel('curve')}
</Tabs.TabPane>
<Tabs.TabPane key="table" tab="表格">
{renderPanel('table')}
</Tabs.TabPane>
</Tabs>
)}
</Spin>
</div>
);
}; };
HistoryView.propTypes = { HistoryView.propTypes = {
grid: PropTypes.bool, grid: PropTypes.bool,
title: PropTypes.string, title: PropTypes.string,
defaultChecked: PropTypes.oneOf(['twelveHours', 'roundClock', 'oneWeek', 'oneMonth']), defaultChecked: PropTypes.oneOf(['twelveHours', 'roundClock', 'oneWeek', 'oneMonth']),
tableProps: PropTypes.object, tableProps: PropTypes.object,
deviceParams: PropTypes.arrayOf( deviceParams: PropTypes.arrayOf(
PropTypes.objectOf({ PropTypes.objectOf({
deviceCode: PropTypes.string, deviceCode: PropTypes.string,
sensors: PropTypes.string, sensors: PropTypes.string,
deviceType: PropTypes.string, deviceType: PropTypes.string,
pointAddressID: PropTypes.number, // 可选,配置了将会查询相关报警方案配置 pointAddressID: PropTypes.number, // 可选,配置了将会查询相关报警方案配置
}), }),
), ),
defaultModel: PropTypes.oneOf(['curve', 'table']), defaultModel: PropTypes.oneOf(['curve', 'table']),
showModels: PropTypes.arrayOf(PropTypes.oneOf(['curve', 'table'])), showModels: PropTypes.arrayOf(PropTypes.oneOf(['curve', 'table'])),
}; };
HistoryView.defaultProps = { HistoryView.defaultProps = {
grid: false, grid: false,
title: '指标曲线', title: '指标曲线',
defaultChecked: 'roundClock', defaultChecked: 'roundClock',
tableProps: {}, tableProps: {},
defaultModel: 'curve', defaultModel: 'curve',
showModels: ['curve', 'table'], showModels: ['curve', 'table'],
needMarkLine: true, needMarkLine: true,
}; };
export default HistoryView; export default HistoryView;
...@@ -13,13 +13,13 @@ const axisWidth = 40; ...@@ -13,13 +13,13 @@ const axisWidth = 40;
* @returns * @returns
*/ */
const nameFormatter = (data, contrast, contrastOption, nameWithSensor) => { const nameFormatter = (data, contrast, contrastOption, nameWithSensor) => {
const { equipmentName, sensorName, unit, dataModel, dateFrom, dateTo } = data; const {equipmentName, sensorName, unit, dataModel, dateFrom, dateTo} = data;
let name = nameWithSensor ? `${equipmentName}-${sensorName}` : equipmentName; let name = nameWithSensor ? `${equipmentName}-${sensorName}` : equipmentName;
if (contrast) { if (contrast) {
const time = dateFrom.slice(0, contrastOption === 'day' ? 10 : 7).replace(/-/g, ''); const time = dateFrom.slice(0, contrastOption === 'day' ? 10 : 7).replace(/-/g, '');
name = `${name}-${time}`; name = `${name}-${time}`;
} }
return name; return name;
}; };
/** /**
...@@ -31,12 +31,12 @@ const nameFormatter = (data, contrast, contrastOption, nameWithSensor) => { ...@@ -31,12 +31,12 @@ const nameFormatter = (data, contrast, contrastOption, nameWithSensor) => {
* @returns 图表系列数据, [[DateTime, value]] * @returns 图表系列数据, [[DateTime, value]]
*/ */
const dataAccessor = (data, contrast, contrastOption) => { const dataAccessor = (data, contrast, contrastOption) => {
const { dataModel } = data; const {dataModel} = data;
const formatStr = contrastOption === 'day' ? '2020-01-01 HH:mm:00' : '2020-01-DD HH:mm:00'; const formatStr = contrastOption === 'day' ? '2020-01-01 HH:mm:00' : '2020-01-DD HH:mm:00';
return dataModel.map((item) => { return dataModel.map((item) => {
const time = contrast ? moment(item.pt).format(formatStr) : item.pt; const time = contrast ? moment(item.pt).format(formatStr) : item.pt;
return [moment(time).valueOf(), item.pv]; return [moment(time).valueOf(), item.pv];
}); });
}; };
/** /**
...@@ -46,8 +46,8 @@ const dataAccessor = (data, contrast, contrastOption) => { ...@@ -46,8 +46,8 @@ const dataAccessor = (data, contrast, contrastOption) => {
* @returns Null/areaStyle, 为null显示曲线图, 为areaStyle对象显示为面积图. * @returns Null/areaStyle, 为null显示曲线图, 为areaStyle对象显示为面积图.
*/ */
const areaStyleFormatter = (data) => { const areaStyleFormatter = (data) => {
const { sensorName } = data; const {sensorName} = data;
return sensorName && sensorName.indexOf('流量') > -1 ? {} : null; return sensorName && sensorName.indexOf('流量') > -1 ? {} : null;
}; };
/** /**
...@@ -57,110 +57,110 @@ const areaStyleFormatter = (data) => { ...@@ -57,110 +57,110 @@ const areaStyleFormatter = (data) => {
* @returns * @returns
*/ */
const minMax = (data) => { const minMax = (data) => {
const { dataModel } = data; const {dataModel} = data;
let min = Number.MAX_SAFE_INTEGER; let min = Number.MAX_SAFE_INTEGER;
let max = Number.MIN_SAFE_INTEGER; let max = Number.MIN_SAFE_INTEGER;
dataModel.forEach((item) => { dataModel.forEach((item) => {
min = Math.min(min, item.pv ?? 0); min = Math.min(min, item.pv ?? 0);
max = Math.max(max, item.pv ?? 0); max = Math.max(max, item.pv ?? 0);
}); });
return [min, max]; return [min, max];
}; };
const markLineItem = (name, value, color) => { const markLineItem = (name, value, color) => {
return { return {
name: name, name: name,
yAxis: value, yAxis: value,
value: value, value: value,
lineStyle: { lineStyle: {
color: color || '#000', color: color || '#000',
}, },
label: { label: {
position: 'insideEndTop', position: 'insideEndTop',
color: color || '#000', color: color || '#000',
formatter: function () { formatter: function () {
return `${name}:${value}`; return `${name}:${value}`;
}, },
}, },
}; };
}; };
export const alarmMarkLine = (dataItem, index, dataSource, schemes) => { export const alarmMarkLine = (dataItem, index, dataSource, schemes) => {
// 只有一个数据曲线时显示markline // 只有一个数据曲线时显示markline
if (!dataItem || !schemes || dataSource.length !== 1) return {}; if (!dataItem || !schemes || dataSource.length !== 1) return {};
const { deviceType, stationCode, sensorName, decimalPoint } = dataItem; const {deviceType, stationCode, sensorName, decimalPoint} = dataItem;
const curSchemes = schemes.filter( const curSchemes = schemes.filter(
(item) => (item) =>
item.deviceCode === stationCode && item.deviceCode === stationCode &&
item.sensorName === sensorName && item.sensorName === sensorName &&
item.valueType === '直接取值', item.valueType === '直接取值',
); );
const data = []; const data = [];
curSchemes.forEach((scheme) => { curSchemes.forEach((scheme) => {
const { hLimit, hhLimit, lLimit, llLimit } = scheme; const {hLimit, hhLimit, lLimit, llLimit} = scheme;
lLimit !== null && lLimit !== void 0 && data.push(markLineItem('低限', lLimit, '#fa8c16')); lLimit !== null && lLimit !== void 0 && data.push(markLineItem('低限', lLimit, '#fa8c16'));
hLimit !== null && hLimit !== void 0 && data.push(markLineItem('高限', hLimit, '#fa8c16')); hLimit !== null && hLimit !== void 0 && data.push(markLineItem('高限', hLimit, '#fa8c16'));
llLimit !== null && llLimit !== void 0 && data.push(markLineItem('低低限', llLimit, '#FF0000')); llLimit !== null && llLimit !== void 0 && data.push(markLineItem('低低限', llLimit, '#FF0000'));
hhLimit !== null && hhLimit !== void 0 && data.push(markLineItem('高高限', hhLimit, '#FF0000')); hhLimit !== null && hhLimit !== void 0 && data.push(markLineItem('高高限', hhLimit, '#FF0000'));
}); });
data.push({ data.push({
name: '平均线', name: '平均线',
type: 'average', type: 'average',
lineStyle: { lineStyle: {
color: '#00b8b1', color: '#00b8b1',
type: 'solid', type: 'solid',
}, },
label: { label: {
position: 'insideEndTop', position: 'insideEndTop',
color: '#00b8b1', color: '#00b8b1',
formatter: function (param) { formatter: function (param) {
return `平均值:${param.value}`; return `平均值:${param.value}`;
}, },
}, },
}); });
return { return {
symbol: ['none', 'none'], symbol: ['none', 'none'],
data, data,
}; };
}; };
export const minMaxMarkPoint = (dataItem, index, dataSource) => { export const minMaxMarkPoint = (dataItem, index, dataSource) => {
// 只有一个数据曲线时显示markline // 只有一个数据曲线时显示markline
if (!dataItem || dataSource.length !== 1) return {}; if (!dataItem || dataSource.length !== 1) return {};
const data = []; const data = [];
data.push({ type: 'min', name: '最小: ' }); data.push({type: 'min', name: '最小: '});
data.push({ type: 'max', name: '最大: ' }); data.push({type: 'max', name: '最大: '});
return { return {
symbolSize: 1, symbolSize: 1,
symbolOffset: [0, '50%'], symbolOffset: [0, '50%'],
label: { label: {
formatter: '{b|{b} }{c|{c}}', formatter: '{b|{b} }{c|{c}}',
backgroundColor: backgroundColor:
window.globalConfig && window.globalConfig &&
window.globalConfig && window.globalConfig &&
window.globalConfig.variableTheme?.primaryColor window.globalConfig.variableTheme?.primaryColor
? window.globalConfig.variableTheme.primaryColor ? window.globalConfig.variableTheme.primaryColor
: '#0087F7', : '#0087F7',
borderColor: '#ccc', borderColor: '#ccc',
borderWidth: 1, borderWidth: 1,
borderRadius: 4, borderRadius: 4,
padding: [2, 10], padding: [2, 10],
lineHeight: 22, lineHeight: 22,
position: 'top', position: 'top',
distance: 10, distance: 10,
rich: { rich: {
b: { b: {
color: '#fff', color: '#fff',
}, },
c: { c: {
color: '#fff', color: '#fff',
fontSize: 16, fontSize: 16,
fontWeight: 700, fontWeight: 700,
},
},
}, },
}, data,
}, };
data,
};
}; };
/** /**
...@@ -169,27 +169,27 @@ export const minMaxMarkPoint = (dataItem, index, dataSource) => { ...@@ -169,27 +169,27 @@ export const minMaxMarkPoint = (dataItem, index, dataSource) => {
* @param {any} axis * @param {any} axis
*/ */
export const decorateAxisGridLine = (axis, showGrid) => { export const decorateAxisGridLine = (axis, showGrid) => {
if (!axis) return; if (!axis) return;
axis.minorTick = { axis.minorTick = {
lineStyle: { lineStyle: {
color: '#e2e2e2', color: '#e2e2e2',
}, },
...(axis.minorTick || {}), ...(axis.minorTick || {}),
show: showGrid, show: showGrid,
splitNumber: 2, splitNumber: 2,
}; };
axis.minorSplitLine = { axis.minorSplitLine = {
lineStyle: { lineStyle: {
color: '#e2e2e2', color: '#e2e2e2',
type: 'dashed', type: 'dashed',
}, },
...(axis.minorSplitLine || {}), ...(axis.minorSplitLine || {}),
show: showGrid, show: showGrid,
}; };
axis.splitLine = { axis.splitLine = {
...(axis.splitLine || {}), ...(axis.splitLine || {}),
show: showGrid, show: showGrid,
}; };
}; };
/** /**
...@@ -198,35 +198,35 @@ export const decorateAxisGridLine = (axis, showGrid) => { ...@@ -198,35 +198,35 @@ export const decorateAxisGridLine = (axis, showGrid) => {
* @param {any} dataItem * @param {any} dataItem
*/ */
export const offlineArea = (dataItem) => { export const offlineArea = (dataItem) => {
if (!dataItem) return {}; if (!dataItem) return {};
const { dataModel } = dataItem; const {dataModel} = dataItem;
let datas = new Array(); let datas = new Array();
let offlineData = []; let offlineData = [];
let hasOffline = false; let hasOffline = false;
dataModel.forEach((item) => { dataModel.forEach((item) => {
if (!item.pv && !hasOffline) { if (!item.pv && !hasOffline) {
offlineData = [ offlineData = [
{ {
name: '离线', name: '离线',
xAxis: new Date(item.pt), xAxis: new Date(item.pt),
},
];
hasOffline = true;
} else if (item.pv && hasOffline) {
offlineData.push({
xAxis: new Date(item.pt),
});
datas.push(offlineData);
offlineData = [];
hasOffline = false;
}
});
return {
itemStyle: {
color: '#eee',
}, },
]; data: datas,
hasOffline = true; };
} else if (item.pv && hasOffline) {
offlineData.push({
xAxis: new Date(item.pt),
});
datas.push(offlineData);
offlineData = [];
hasOffline = false;
}
});
return {
itemStyle: {
color: '#eee',
},
data: datas,
};
}; };
/** /**
...@@ -240,148 +240,206 @@ export const offlineArea = (dataItem) => { ...@@ -240,148 +240,206 @@ export const offlineArea = (dataItem) => {
* @param {any} config 额外配置信息 * @param {any} config 额外配置信息
*/ */
const optionGenerator = (dataSource, cusOption, contrast, contrastOption, smooth, config) => { const optionGenerator = (dataSource, cusOption, contrast, contrastOption, smooth, config) => {
const needUnit = _.get(config, 'needUnit', false); const needUnit = _.get(config, 'needUnit', false);
const curveCenter = _.get(config, 'curveCenter', false); const curveCenter = _.get(config, 'curveCenter', false);
const nameWithSensor = _.get(config, 'nameWithSensor', true); const nameWithSensor = _.get(config, 'nameWithSensor', true);
const showGridLine = _.get(config, 'showGridLine', false); const showGridLine = _.get(config, 'showGridLine', false);
const showMarkLine = _.get(config, 'showMarkLine', false); const showMarkLine = _.get(config, 'showMarkLine', false);
const showPoint = _.get(config, 'showPoint', false); const showPoint = _.get(config, 'showPoint', false);
const deviceAlarmSchemes = _.get(config, 'deviceAlarmSchemes', []); const deviceAlarmSchemes = _.get(config, 'deviceAlarmSchemes', []);
const chartType = _.get(config, 'chartType', null);
const justLine = _.get(config, 'justLine', false);
// 自定义属性
const restOption = _.pick(cusOption, ['title', 'legend']);
// 自定义属性 // 一种指标一个y轴
const restOption = _.pick(cusOption, ['title', 'legend']); const yAxisMap = new Map();
dataSource.forEach((item, index) => {
const {sensorName, unit} = item;
const key = sensorName;
// 一种指标一个y轴 if (!yAxisMap.has(key)) {
const yAxisMap = new Map(); const i = yAxisMap.size;
dataSource.forEach((item, index) => { const axis = {
const { sensorName, unit } = item; type: 'value',
const key = sensorName; name: needUnit ? unit : null,
position: i % 2 === 0 ? 'left' : 'right',
offset: Math.floor(i / 2) * axisWidth,
axisLabel: {
formatter: (value) => (value > 100000 ? `${value / 1000}k` : value),
},
axisLine: {
show: true,
},
nameTextStyle: {
align: i % 2 === 0 ? 'right' : 'left',
},
minorTick: {
lineStyle: {
color: '#e2e2e2',
},
},
minorSplitLine: {
lineStyle: {
color: '#e2e2e2',
type: 'dashed',
},
},
};
yAxisMap.set(key, axis);
}
if (!yAxisMap.has(key)) { // 曲线居中
const i = yAxisMap.size; if (curveCenter && item.dataModel && item.dataModel.length > 0) {
const axis = { const [min, max] = minMax(item);
type: 'value', const axis = yAxisMap.get(key);
name: needUnit ? unit : null, axis.min = axis.min === void 0 ? min : Math.min(min, axis.min);
position: i % 2 === 0 ? 'left' : 'right', axis.max = axis.max === void 0 ? max : Math.max(max, axis.max);
offset: Math.floor(i / 2) * axisWidth, }
axisLabel: {
formatter: (value) => (value > 100000 ? `${value / 1000}k` : value),
},
axisLine: {
show: true,
},
nameTextStyle: {
align: i % 2 === 0 ? 'right' : 'left',
},
minorTick: {
lineStyle: {
color: '#e2e2e2',
},
},
minorSplitLine: {
lineStyle: {
color: '#e2e2e2',
type: 'dashed',
},
},
};
yAxisMap.set(key, axis);
}
// 曲线居中 // 网格显示
if (curveCenter && item.dataModel && item.dataModel.length > 0) { const axis = yAxisMap.get(key);
const [min, max] = minMax(item); decorateAxisGridLine(axis, showGridLine);
const axis = yAxisMap.get(key); });
axis.min = axis.min === void 0 ? min : Math.min(min, axis.min); const yAxis = yAxisMap.size > 0 ? [...yAxisMap.values()] : {type: 'value'};
axis.max = axis.max === void 0 ? max : Math.max(max, axis.max);
}
// 网格显示 // 根据y轴个数调整边距
const axis = yAxisMap.get(key); const leftNum = Math.ceil(yAxisMap.size / 2);
decorateAxisGridLine(axis, showGridLine); const rightNum = Math.floor(yAxisMap.size / 2);
}); const grid = {
const yAxis = yAxisMap.size > 0 ? [...yAxisMap.values()] : { type: 'value' }; top: needUnit ? 80 : 60,
left: 10 + leftNum * axisWidth,
right: rightNum === 0 ? 20 : rightNum * axisWidth,
};
// 根据y轴个数调整边距 // 根据"指标名称"分类yAxis
const leftNum = Math.ceil(yAxisMap.size / 2); const yAxisInterator = (() => {
const rightNum = Math.floor(yAxisMap.size / 2); const map = new Map();
const grid = { let current = -1;
top: needUnit ? 80 : 60, const get = (name) => (map.has(name) ? map.get(name) : map.set(name, ++current).get(name));
left: 10 + leftNum * axisWidth, return {get};
right: rightNum === 0 ? 20 : rightNum * axisWidth, })();
}; let series = dataSource.map((item, index) => {
const {sensorName, unit} = item;
const name = nameFormatter(item, contrast, contrastOption, nameWithSensor);
const data = dataAccessor(item, contrast, contrastOption);
const type = 'line';
const areaStyle = areaStyleFormatter(item);
const yAxisIndex = yAxisInterator.get(sensorName);
const markLine = showMarkLine ? alarmMarkLine(item, index, dataSource, deviceAlarmSchemes) : {};
const markPoint = showPoint ? minMaxMarkPoint(item, index, dataSource) : {};
let markArea = null;
let offlineAreas = offlineArea(item);
if (offlineAreas.data?.length) {
restOption.markArea = null;
markArea = offlineAreas;
}
return {
notMerge: true,
name,
type,
data,
areaStyle,
yAxisIndex,
smooth,
unit,
markLine,
markPoint,
markArea,
};
});
// 根据"指标名称"分类yAxis // 由于series更新后,没有的数据曲线仍然停留在图表区上,导致图表可视区范围有问题
const yAxisInterator = (() => { const min = Math.min(
const map = new Map(); ...series.map((item) => item.data?.[0]?.[0]).filter((item) => item !== undefined),
let current = -1; );
const get = (name) => (map.has(name) ? map.get(name) : map.set(name, ++current).get(name)); const max = Math.max(
return { get }; ...series
})(); .map((item) => item.data?.[item.data.length - 1]?.[0])
.filter((item) => item !== undefined),
);
let xAxis = {type: 'time', min, max};
decorateAxisGridLine(xAxis, showGridLine);
const series = dataSource.map((item, index) => { const tooltipTimeFormat = !contrast
const { sensorName, unit } = item; ? 'YYYY-MM-DD HH:mm:ss'
const name = nameFormatter(item, contrast, contrastOption, nameWithSensor); : contrastOption === 'day'
const data = dataAccessor(item, contrast, contrastOption); ? 'HH:mm'
const type = 'line'; : 'DD HH:mm';
const areaStyle = areaStyleFormatter(item); const tooltip = {
const yAxisIndex = yAxisInterator.get(sensorName); timeFormat: tooltipTimeFormat,
const markLine = showMarkLine ? alarmMarkLine(item, index, dataSource, deviceAlarmSchemes) : {}; // trigger: 'axis',
const markPoint = showPoint ? minMaxMarkPoint(item, index, dataSource) : {}; // axisPointer: {
let markArea = null; // type: 'cross'
let offlineAreas = offlineArea(item); // }
if (offlineAreas.data?.length) { };
restOption.markArea = null; // 增加箱线图的逻辑,单曲线才存在
markArea = offlineAreas; if (!justLine && chartType) {
if (chartType === 'boxChart') {
const otherData = dataSource?.[0]?.dataModel.map(item => {
const {firstPV, lastPV, maxPV, minPV} = item;
return [firstPV, lastPV, minPV, maxPV]
}) || []; //当存在othersData的时候,只是单曲线
series = series.map(item => {
let _item = {...item, symbol: false};
_item.data = _item?.data?.map(d => {
return d[1] || null
}) || [];
return _item;
})
series.push({
type: 'candlestick',
name: '箱线图',
symbol: false,
data: otherData
});
} else {
let _maxData = [];
let _minData = [];
dataSource?.[0]?.dataModel.forEach(item => {
const {firstPV, lastPV, maxPV, minPV} = item;
_maxData.push(maxPV);
_minData.push(minPV);
}); //当存在othersData的时候,只是单曲线
series = series.map(item => {
let _item = {...item, symbol: false};
_item.data = _item?.data?.map(d => {
return d[1] || null
}) || [];
return _item;
});
[[..._minData], [..._maxData]].forEach((item, index) => {
series.push({
name: index === 0 ? '最小值' : '最大值',
type: 'line',
data: item,
lineStyle: {
opacity: 0
},
...(index !== 0 ? {
areaStyle: {
color: '#ccc'
}
} : {}),
stack: 'confidence-band',
symbol: 'none'
});
})
}
xAxis = {type: 'category', data: series[0].data.map(item => moment(item[0]).format('YYYY-MM-DD'))};
tooltip.formatter = (e) => {
console.log(e);
}
} }
debugger
return { return {
notMerge: true, yAxis,
name, grid,
type, xAxis,
data, series,
areaStyle, tooltip,
yAxisIndex, ...restOption,
smooth,
unit,
markLine,
markPoint,
markArea,
}; };
});
// 由于series更新后,没有的数据曲线仍然停留在图表区上,导致图表可视区范围有问题
const min = Math.min(
...series.map((item) => item.data?.[0]?.[0]).filter((item) => item !== undefined),
);
const max = Math.max(
...series
.map((item) => item.data?.[item.data.length - 1]?.[0])
.filter((item) => item !== undefined),
);
const xAxis = { type: 'time', min, max };
decorateAxisGridLine(xAxis, showGridLine);
const tooltipTimeFormat = !contrast
? 'YYYY-MM-DD HH:mm:ss'
: contrastOption === 'day'
? 'HH:mm'
: 'DD HH:mm';
const tooltip = {
timeFormat: tooltipTimeFormat,
// trigger: 'axis',
// axisPointer: {
// type: 'cross'
// }
};
return {
yAxis,
grid,
xAxis,
series,
tooltip,
...restOption,
};
}; };
export default optionGenerator; export default optionGenerator;
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment