index.js 67.2 KB
Newer Older
1 2 3 4 5
/**
 * 走influxdb版本的,不抽稀通过zoom和unit传空字符串实现;
 * 非influxdb版本的接口,使用isDilute=false实现;
 * 建议:不抽稀的时候,传isDilute=false&zoom=''&unit=''
 * */
6
import React, {useContext, useEffect, useMemo, useState, useCallback, useRef} from 'react';
7 8
import PropTypes from 'prop-types';
import classNames from 'classnames';
张瑶's avatar
张瑶 committed
9
import {
10 11 12 13 14 15 16 17 18 19 20
    Checkbox,
    ConfigProvider,
    DatePicker,
    Radio,
    Select,
    Spin,
    Tabs,
    Tooltip,
    Button,
    message,
    Progress,
张瑶's avatar
张瑶 committed
21 22
} from 'antd';
import {
23 24 25 26
    CloseCircleFilled,
    PlusCircleOutlined,
    QuestionCircleFilled,
    DownloadOutlined,
张瑶's avatar
张瑶 committed
27
} from '@ant-design/icons';
28 29 30
import moment from 'moment';
import _ from 'lodash';
import TimeRangePicker from '@wisdom-components/timerangepicker';
31
import PandaEmpty from '@wisdom-components/empty';
陈龙's avatar
陈龙 committed
32
import {
33 34 35 36 37
    getHistoryInfo,
    getDeviceAlarmScheme,
    getExportDeviceHistoryUrl,
    getDictionaryInfoAll,
    getPointAddress,
38
    getPointAddressEntry, getPredicateSensor,
陈龙's avatar
陈龙 committed
39
} from './apis';
40
import SingleChart from './SingleChart';
41
import GridChart from './GridChart';
陈龙's avatar
陈龙 committed
42
import BIStyles from './indexForBI.less';
43 44 45
import {globalConfig} from 'antd/lib/config-provider';
import {getSensorType} from './apis/index';
import {ExportExcel} from '@wisdom-components/exportexcel';
46

47
import VirtualTable from './VirtualTable';
陈龙's avatar
陈龙 committed
48

49 50
const {RangePicker} = DatePicker;
const {Option} = Select;
51 52 53 54

const startFormat = 'YYYY-MM-DD 00:00:00';
const endFormat = 'YYYY-MM-DD 23:59:59';
const timeFormat = 'YYYY-MM-DD HH:mm:ss';
张瑶's avatar
张瑶 committed
55
const dateFormat = 'YYYYMMDD';
56 57

const timeList = [
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
    {
        key: 'twelveHours',
        name: '近12小时',
    },
    {
        key: 'roundClock',
        name: '近24小时',
    },
    {
        key: 'yesterday',
        name: '昨日',
    },
    {
        key: 'oneWeek',
        name: '近1周',
    },
    {
        key: 'oneMonth',
        name: '近1月',
    },
78
];
79 80 81 82 83 84
const predicateMap = {
    twelveHours: 12,
    roundClock: 24,
    oneWeek: 24,
    oneMonth: 24
}
85

86 87
// 同期对比 日 快捷按钮
const shortcutsForDay = [
88 89 90 91 92 93 94 95 96 97 98 99
    {
        label: '近3天',
        value: '近3天',
    },
    {
        label: '近7天',
        value: '近7天',
    },
    /*    {
                label: '去年同期',
                value: '去年同期',
            }*/
100 101 102
];
// 同期对比 月 快捷按钮
const shortcutsForMonth = [
103 104 105 106 107 108 109 110 111 112 113 114
    {
        label: '近3月',
        value: '近3月',
    },
    {
        label: '近6月',
        value: '近6月',
    },
    /*    {
                label: '去年同期',
                value: '去年同期',
            }*/
115
];
116

117
const CheckboxData = [
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
    {
        key: 'curveCenter',
        label: '曲线居中',
        checked: false,
        showInCurve: true,
        showInTable: false,
    },
    {
        key: 'chartGrid',
        label: '图表网格',
        checked: true,
        showInCurve: true,
        showInTable: false,
    },
    {
        key: 'ignoreOutliers',
        label: '去除异常值',
        type: 'updateIgnoreOutliers',
        checked: false,
        showInCurve: true,
        showInTable: true,
        tooltip: '采用递推平均滤波法(滑动平均滤波法)对采样数据中的异常离群值进行识别与去除。',
        hasSub: true,
    },
    {
        key: 'dataThin',
        label: '数据抽稀',
        type: 'updateDataThin',
        checked: true,
        showInCurve: false,
        showInTable: true,
149
    }
150 151 152
];

const timeIntervalList = [
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
    {
        key: '1min',
        zoom: '1',
        unit: 'min',
        name: '1分钟',
    },
    {
        key: '5',
        zoom: '5',
        unit: 'min',
        name: '5分钟',
    },
    {
        key: '10',
        zoom: '10',
        unit: 'min',
        name: '10分钟',
    },
    {
        key: '30',
        zoom: '30',
        unit: 'min',
        name: '30分钟',
    },
    {
        key: '1',
        zoom: '1',
        unit: 'h',
        name: '1小时',
    },
    {
        key: '2',
        zoom: '2',
        unit: 'h',
        name: '2小时',
    },
    {
        key: '4',
        zoom: '4',
        unit: 'h',
        name: '4小时',
    },
    {
        key: '6',
        zoom: '6',
        unit: 'h',
        name: '6小时',
    },
    {
        key: '12',
        zoom: '12',
        unit: 'h',
        name: '12小时',
    },
207 208 209 210 211 212
    {
        key: '24',
        zoom: '24',
        unit: 'h',
        name: '24小时',
    },
213 214
];

215 216 217 218 219
const handleTimeForPredicate = (key, start, end) => {
    let t = predicateMap[key] || 0;
    return moment(end).add(t, 'hours').format(timeFormat);
};
const updateTime = (key, predicate) => {
220 221
    let start = '';
    let end = '';
陈龙's avatar
陈龙 committed
222

223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
    if (Array.isArray(key)) {
        start = moment(key[0]).format(timeFormat);
        end = moment(key[1]).format(timeFormat);
    } else {
        switch (key) {
            case 'twelveHours':
                start = moment().subtract(12, 'hour').format(timeFormat);
                end = moment().format(timeFormat);
                break;
            case 'roundClock':
                start = moment().subtract(24, 'hour').format(timeFormat);
                end = moment().format(timeFormat);
                break;
            case 'yesterday':
                start = moment().subtract(1, 'days').format('YYYY-MM-DD 00:00:00');
                end = moment().subtract(1, 'days').format('YYYY-MM-DD 23:59:59');
                break;
            case 'oneWeek':
                start = moment().subtract(7, 'day').format(timeFormat);
                end = moment().format(timeFormat);
                break;
            case 'oneMonth':
                start = moment().subtract(30, 'day').format(timeFormat);
                end = moment().format(timeFormat);
                break;
        }
249
    }
250 251 252 253

    if (predicate) {
        end = handleTimeForPredicate(key, end)
    }
254 255 256 257 258 259
    return [
        {
            dateFrom: start,
            dateTo: end,
        },
    ];
260 261 262
};

const DefaultDatePicker = (value) => [
263 264 265 266 267 268 269 270
    {
        key: 1,
        value: moment(),
    },
    {
        key: 2,
        value: moment().subtract(1, value),
    },
271 272 273
];

const handleBatchTime = (arr, cOption) => {
274 275 276 277 278 279 280 281 282 283 284
    let newArr = [];
    arr.forEach((child) => {
        if (child.value) {
            newArr.push({
                dateFrom: moment(child.value).startOf(cOption).format(startFormat),
                dateTo: moment(child.value).endOf(cOption).format(endFormat),
            });
        }
    });
    newArr = _.uniqWith(newArr, _.isEqual); // 去掉重复日期时间
    return newArr;
285
};
陈龙's avatar
陈龙 committed
286 287 288 289 290 291 292 293
const handleFakeData = (dateRange, deviceParams) => {
    let dateFrom = dateRange[0].dateFrom;
    let dateTo = dateRange[0].dateTo;
    return deviceParams.reduce((final, cur) => {
        let _arr = cur.sensors.split(',');
        _arr.forEach(sensor => {
            final.push({
                dataModel: [
294 295
                    {pt: dateFrom, pv: null},
                    {pt: dateTo, pv: null}
陈龙's avatar
陈龙 committed
296 297 298 299 300 301 302 303 304 305 306 307 308
                ],
                dateFrom,
                dateTo,
                deviceCode: cur.deviceCode,
                deviceType: cur.deviceType,
                sensorName: sensor,
                equipmentName: '',
                stationCode: cur.deviceCode
            })
        })
        return final;
    }, [])
}
309
const timeColumn = {
310 311 312 313 314 315 316 317
    title: '采集时间',
    dataIndex: 'time',
    key: 'time',
    width: 170,
    ellipsis: true,
    align: 'center',
    sorter: true,
    // sortOrder:['descend','ascend']
318
};
陈龙's avatar
陈龙 committed
319 320
const OriginMaxDays = 31; // 原始曲线请求数据的最大天数
const CharacteristicMaxDays = null; // 特征曲线或者其他曲线的最大天数
李纪文's avatar
李纪文 committed
321
const HistoryView = (props) => {
322
    const [completeInit, setCompleteInit] = useState(false);
323
    const {getPrefixCls} = useContext(ConfigProvider.ConfigContext);
324
    const prefixCls = getPrefixCls('history-view');
325 326 327 328 329
    const {
        title,
        grid,
        defaultChecked,
        tableProps,
330
        deviceParams,
331 332 333 334
        defaultModel,
        showModels,
        needMarkLine,
        defaultDate,
335
        theme = "Normal"
336
    } = props;
337 338
    if (theme === 'Normal') import('./index.less');
    if (theme === 'BI') import('./indexForBI.less');
339 340 341 342
    const isBoxPlots =
        deviceParams?.length === 1 && deviceParams?.[0]?.sensors?.split(',').length === 1;
    const [loading, setLoading] = useState(null);
    const [activeTabKey, setActiveTabKey] = useState(defaultModel);
陈龙's avatar
陈龙 committed
343

344 345
    // 时间模式: 自定义模式/同期对比模式
    const [timeValue, setTimeValue] = useState('customer');
陈龙's avatar
陈龙 committed
346

347 348 349
    // 自定义模式
    const [customerChecked, setCustomerChecked] = useState(defaultChecked); // 时间快速选择类型值
    const [customerTime, setCustomerTime] = useState(); // 自定义时间选择值
陈龙's avatar
陈龙 committed
350

351 352 353 354 355 356 357 358
    // 同期对比模式
    const [contrastOption, setContrastOption] = useState('day'); // 对比时间类型: 日/月
    const [datePickerArr, setDatePickerArr] = useState(DefaultDatePicker(defaultDate)); // 对比时间段配置值
    const [checkboxData, setCheckboxData] = useState(() => [...CheckboxData]); // 曲线设置项
    const [dataThinKey, setDataThinKey] = useState(
        timeIntervalList[0].key === '1min' ? timeIntervalList[1].key : timeIntervalList[0].key,
    ); // 曲线抽稀时间设置
    const [algorithmValue, setAlgorithmValue] = useState(1);
陈龙's avatar
陈龙 committed
359

360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
    const [columns, setColumns] = useState([]);
    const [tableData, setTableData] = useState([]);
    const [timeOrder, setTimeOrder] = useState('descend');
    const [chartType, setChartType] = useState('lineChart');
    const [showBoxOption, setShowBoxOption] = useState(true);
    const [lineDataType, setLineDataType] = useState('特征曲线');
    // 同期对比快捷键
    // shortcutsValue
    // onShortcutsChange
    const [shortcutsValue, setShortcutsValue] = useState('');
    const [shortcutsDatePickerArr, setShortcutsDatePickerArr] = useState([]);
    const [percent, setPercent] = useState(0);
    // 频率指标特殊业务
    const [special1, setSpecial1] = useState(null);
    const [allPointAddress, setAllPointAddress] = useState([]);
    //查询所有sensorType
    const [allSensorType, setAllSensorType] = useState([]);
    const [isSingleStatusSensor, setIsSingleStatusSensor] = useState(false);
378
    const [predicateDevice, setPredicateDevice] = useState(null);
379
    const [predicateData, setPredicateData] = useState([]);
380
    const [predicateTime, setPredicateTime] = useState(null);
381 382 383 384 385
    // 需要处理默认数据,确保图表能够一直显示坐标轴。用来存储当前的请求状态。
    const emptyOrError = useRef({
        empty: true,
        error: true
    })
陈龙's avatar
陈龙 committed
386
    // 这部分功能有问题,等待解决后上线 2024年3月13日
陈龙's avatar
陈龙 committed
387
    const [discreteDeviceType, setDiscreteDeviceType] = useState(['水厂'])
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
    // 历史数据相关的特征描述
    const deviceConfig = useRef({
        oneDevice: deviceParams.length === 1, //单设备
        oneSensor:
            [
                ...new Set(
                    deviceParams.reduce((final, cur) => {
                        let _sensors = cur.sensors.split(',');
                        return final.concat(_sensors);
                    }, []),
                ),
            ].length === 1, // 单指标
    });
    // 表格虚拟列表
    const tableRef = useRef();
    // 选择的时间范围值
    const dateRange = useMemo(() => {
        if (timeValue === 'customer') {
406
            return updateTime(customerChecked || customerTime, predicateDevice);
407 408 409 410 411 412 413 414 415 416 417 418
        } else {
            let _dateArr = shortcutsValue ? shortcutsDatePickerArr : datePickerArr;
            return handleBatchTime(_dateArr, contrastOption);
        }
    }, [contrastOption, customerChecked, customerTime, datePickerArr, timeValue, shortcutsValue]);
    useEffect(() => {
        let _diffDays = moment(dateRange[0].dateTo).diff(dateRange[0].dateFrom, 'days');
        if (_diffDays > 7 && dataThinKey === '1min') {
            setDataThinKey(timeIntervalList[1].key);
        }
    }, [dateRange]);
    const [dates, setDates] = useState(null);
陈龙's avatar
陈龙 committed
419
    const [chartDataSource, setChartDataSource] = useState(handleFakeData(dateRange, deviceParams) ?? []);
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
    const configDependence = checkboxData
        .filter((item) => ['curveCenter', 'chartGrid'].indexOf(item.key) === -1)
        .map((item) => item.checked)
        .join(',');
    // 数据配置
    const dataConfig = useMemo(() => {
        const initial = {
            ignoreOutliers: false,
            dataThin: false,
            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; // 曲线强制抽稀
李纪文's avatar
李纪文 committed
442

443 444
        return config;
    }, [configDependence, dataThinKey, activeTabKey]);
陈龙's avatar
陈龙 committed
445

446 447 448 449 450 451
    // 图表居中
    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]);
452 453
    // 导出图表canvas
    const [exportFlag, setExportFlag] = useState(null);
454 455 456
    // 自定义模式: 快速选择
    const onCustomerTimeChange = (key) => {
        setCustomerChecked(key);
457
        setPredicateTime(predicateMap[key]);
458 459
        !!customerTime && setCustomerTime(null);
    };
460

461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
    // 自定义模式: 自定义时间选择
    const onCustomerRangeChange = (value) => {
        if (!value) {
            // 时间清空,回到默认时间选择
            setCustomerChecked(defaultChecked);
            setCustomerTime(value);
        } else {
            setCustomerChecked(null);
            let diffDays = moment(value[1]).diff(moment(value[0]), 'days');
            if (diffDays > OriginMaxDays && lineDataType === '原始曲线') {
                setLineDataType('特征曲线');
                message.info('时间区间超过7天,已切换为特征曲线');
            }
            setCustomerTime(value);
        }
    };
477

478 479 480 481 482 483 484 485 486 487 488 489
    // 同期对比模式: 选择(日/月)
    const onContrastChange = (value) => {
        if (value === 'month') {
            if (lineDataType === '原始曲线')
                message.info('月模式数据量较大,不支持原始曲线模式,已切换为特征曲线');
            setLineDataType('特征曲线');
        }
        setShortcutsValue('');
        setContrastOption(value);
        // 模式为日时,默认对比时间根据defaultDate判断 是昨天、上月、还是去年
        setDatePickerArr([...DefaultDatePicker(value === 'day' && defaultDate ? defaultDate : value)]);
    };
程恺文's avatar
程恺文 committed
490

491 492 493 494 495 496 497 498 499 500 501 502
    // 同期对比模式: 时间段选择
    const onContrastPickerChange = (date, dateString, item) => {
        // 操作时间就清除掉快捷键选用状态
        setShortcutsValue('');
        const arr = [...datePickerArr];
        arr.forEach((child) => {
            if (child.key === item.key) {
                child.value = date;
            }
        });
        setDatePickerArr(arr);
    };
陈龙's avatar
陈龙 committed
503

504 505 506 507 508 509 510 511 512 513 514 515
    // 同期对比模式: 新增日期选择组件
    const handleAddDatePicker = () => {
        // 操作时间就清除掉快捷键选用状态
        setShortcutsValue('');
        setDatePickerArr([
            ...datePickerArr,
            {
                key: datePickerArr[datePickerArr.length - 1].key + 1,
                value: '',
            },
        ]);
    };
516

517 518 519 520 521 522 523 524
    // 同期对比模式: 删除日期选择组件
    const handleDeleteDatePicker = (index) => {
        // 操作时间就清除掉快捷键选用状态
        setShortcutsValue('');
        const arr = [...datePickerArr];
        arr.splice(index, 1);
        setDatePickerArr(arr);
    };
525

526 527 528 529 530 531 532 533 534 535 536 537 538 539
    // 时间设置切换(自定义/同期对比)
    const onTimeSetChange = (e) => {
        // 操作时间就清除掉快捷键选用状态
        setShortcutsValue('');
        if (e.target.value === 'customer') {
            setLineDataType('特征曲线');
            setShortcutsValue('');
        }
        setTimeValue(e.target.value);
        if (e.target.value === 'contrast') {
            // 同期对比
            onContrastChange(contrastOption);
            setShowBoxOption(false);
            setChartType('lineChart');
540 541
            onCheckboxChange({target: {value: false}}, 'chartType');
            onCheckboxChange({target: {value: false}}, 'ignoreOutliers');
542 543 544 545
        } else {
            // 自定义
            // 不需要处理
            setShowBoxOption(true);
546
            onCheckboxChange({target: {value: true}}, 'chartType');
547 548 549 550 551 552 553 554 555
        }
    };
    const onShortcutsChange = (e) => {
        let _val = e.target.value;
        setShortcutsValue(_val);
        let _arr = [];
        switch (_val) {
            case '近3天':
                _arr = [
556 557 558
                    {key: 1, value: moment()},
                    {key: 2, value: moment().subtract(1, 'days')},
                    {key: 3, value: moment().subtract(2, 'days')},
559 560 561 562
                ];
                break;
            case '近7天':
                _arr = [
563 564 565 566 567 568 569
                    {key: 1, value: moment()},
                    {key: 2, value: moment().subtract(1, 'days')},
                    {key: 3, value: moment().subtract(2, 'days')},
                    {key: 4, value: moment().subtract(3, 'days')},
                    {key: 5, value: moment().subtract(4, 'days')},
                    {key: 6, value: moment().subtract(5, 'days')},
                    {key: 7, value: moment().subtract(6, 'days')},
570 571 572 573
                ];
                break;
            case '近3月':
                _arr = [
574 575 576
                    {key: 1, value: moment()},
                    {key: 2, value: moment().subtract(1, 'months')},
                    {key: 3, value: moment().subtract(2, 'months')},
577 578 579 580
                ];
                break;
            case '近6月':
                _arr = [
581 582 583 584 585 586
                    {key: 1, value: moment()},
                    {key: 2, value: moment().subtract(1, 'months')},
                    {key: 3, value: moment().subtract(2, 'months')},
                    {key: 4, value: moment().subtract(3, 'months')},
                    {key: 5, value: moment().subtract(4, 'months')},
                    {key: 6, value: moment().subtract(5, 'months')},
587 588 589 590 591 592 593 594 595 596 597 598
                ];
                break;
        }
        setShortcutsDatePickerArr(_arr);
    };
    const renderTimeOption = useMemo(() => {
        return (
            <div className={classNames(`${prefixCls}-date`)}>
                <div className={classNames(`${prefixCls}-label`)}>时间选择</div>
                <Radio.Group value={timeValue} onChange={onTimeSetChange}>
                    <Radio.Button value="customer">自定义</Radio.Button>
                    {!grid ? <Radio.Button value="contrast">同期对比</Radio.Button> : ''}
599
                </Radio.Group>
600 601 602 603 604 605 606 607 608
                {timeValue === 'customer' && ( // 自定义
                    <>
                        <TimeRangePicker
                            format={'YYYY-MM-DD HH:mm'}
                            onChange={onCustomerTimeChange}
                            value={customerChecked}
                            dataSource={timeList}
                        />
                        <RangePicker
609
                            getPopupContainer={trigger => trigger.parentElement}
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
                            format={'YYYY-MM-DD HH:mm'}
                            className={classNames(`${prefixCls}-custime-customer`)}
                            onChange={onCustomerRangeChange}
                            value={dates || customerTime}
                            onCalendarChange={(val) => {
                                setDates(val);
                            }}
                            onOpenChange={(open) => {
                                if (open) {
                                    setDates([null, null]);
                                } else {
                                    setDates(null);
                                }
                            }}
                            disabledDate={(current) => {
                                if (timeValue !== 'customer') return false;
                                let _days = lineDataType === '原始曲线' ? OriginMaxDays : CharacteristicMaxDays;
                                if (!dates) {
                                    return false;
                                }
                                if (!_days) return false;
                                const tooLate = dates[0] && current.diff(dates[0], 'days') > _days;
                                const tooEarly = dates[1] && dates[1].diff(current, 'days') > _days;
                                return !!tooEarly || !!tooLate;
                            }}
                            showTime={{
                                format: 'YYYY-MM-DD HH:mm',
                                minuteStep: 10,
                            }}
                        />
                    </>
                )}
                {timeValue === 'contrast' && ( // 同期对比
                    <>
644
                        <Select value={contrastOption} getPopupContainer={trigger => trigger.parentElement}
645
                                style={{width: 60}} onChange={onContrastChange}>
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
                            <Option value="day"></Option>
                            <Option value="month" disabled={lineDataType === '原始曲线'}>
                                
                            </Option>
                        </Select>
                        {/*增加快捷日期*/}
                        {deviceParams?.length === 1 && deviceParams?.[0]?.sensors?.split(',').length === 1 ? (
                            <Radio.Group value={shortcutsValue} onChange={onShortcutsChange}>
                                {(contrastOption === 'day' ? shortcutsForDay : shortcutsForMonth).map((item) => {
                                    return <Radio.Button value={item.value}>{item.label}</Radio.Button>;
                                })}
                            </Radio.Group>
                        ) : (
                            ''
                        )}
                        {datePickerArr.map((child, index) => (
                            <div key={child.key} className={classNames(`${prefixCls}-contrast-list`)}>
                                <div className={classNames(`${prefixCls}-contrast-wrap`)}>
                                    <DatePicker
665
                                        getPopupContainer={trigger => trigger.parentElement}
666 667 668 669
                                        key={child.key}
                                        picker={contrastOption === 'day' ? undefined : contrastOption}
                                        value={child.value}
                                        onChange={(date, dateString) => onContrastPickerChange(date, dateString, child)}
670
                                        style={{width: 130, border: !shortcutsValue ? '1px solid #1890ff' : ''}}
671 672 673 674 675 676
                                    />
                                    {datePickerArr.length > 2 && (
                                        <div
                                            className={classNames(`${prefixCls}-contrast-delete`)}
                                            onClick={() => handleDeleteDatePicker(index)}
                                        >
677
                                            <CloseCircleFilled/>
678 679 680 681 682 683 684 685
                                        </div>
                                    )}
                                </div>
                                {index < datePickerArr.length - 1 && (
                                    <div className={classNames(`${prefixCls}-contrast-connect`)}></div>
                                )}
                            </div>
                        ))}
686
                        {datePickerArr.length < 4 && <PlusCircleOutlined onClick={handleAddDatePicker}/>}
687 688
                    </>
                )}
689
            </div>
690 691 692 693 694 695 696 697 698 699 700
        );
    }, [
        timeValue,
        customerChecked,
        lineDataType,
        datePickerArr,
        deviceParams,
        dates,
        customerTime,
        chartDataSource,
    ]);
701

702 703 704 705 706 707 708 709 710 711 712
    // 曲线设置项选择/取消
    const onCheckboxChange = (e, key, showJustLine) => {
        let data = [...checkboxData];
        let _index1 = data.findIndex((item) => item.key === 'ignoreOutliers'); // 仅查看曲线会在勾选了数据滤波后展示
        data.forEach((item) => {
            if (item.key === key) {
                item.checked = e.target.checked;
            }
        });
        if (key === 'ignoreOutliers') {
            data[_index1].showInCurve = true;
713
        }
714 715 716 717 718 719

        if (key === 'chartType') {
            data[_index1].showInCurve = e.target.value;
            data[_index1].checked = false;
            // data[_index].showInCurve = false;
            // data[_index].checked = false;
陈龙's avatar
陈龙 committed
720
        }
721 722
        setCheckboxData(data);
    };
723

724 725 726 727 728 729 730 731 732 733 734 735 736
    // 数据抽稀时间间隔
    const onTimeIntervalChange = (value) => {
        setDataThinKey(value);
    };
    // 切换数据类型
    const switchLineDataType = (e) => {
        let _val = e.target.value;
        let _startDate = dateRange[0]?.dateFrom;
        let _endDate = dateRange[0]?.dateTo;
        let diffDays = moment(_endDate).diff(moment(_startDate), 'days');
        if (_val === '原始曲线' && diffDays > OriginMaxDays) {
            message.info('查阅原始曲线时,需选择小于或等于31天的时间间隔,已自动切换为近一月');
            setCustomerChecked('oneMonth');
737
        }
738 739
        if (_val === '原始曲线') {
            setContrastOption('day');
陈龙's avatar
陈龙 committed
740
        }
741 742 743 744 745 746
        setLineDataType(_val);
    };
    const renderCheckbox = (child, showJustLine) => {
        const curveAccess = activeTabKey === 'curve' && child.showInCurve;
        const tableAccess = activeTabKey === 'table' && child.showInTable;
        const gridOptions = ['curveCenter'];
747

748 749 750 751 752 753 754 755 756
        if (grid && curveAccess && gridOptions.indexOf(child.key) === -1) return null;
        return (
            (curveAccess || tableAccess) && (
                <>
                    <Checkbox checked={child.checked} onChange={(e) => onCheckboxChange(e, child.key)}>
                        {child.label}
                    </Checkbox>
                    {child.tooltip && (
                        <Tooltip title={child.tooltip}>
757
                            <QuestionCircleFilled className={`${prefixCls}-question`}/>
758 759 760 761
                        </Tooltip>
                    )}
                    {child.hasSub && child.checked && false ? (
                        <Select
762
                            style={{width: 80, marginLeft: 10}}
763 764 765 766 767 768 769 770 771 772 773 774 775 776
                            value={algorithmValue}
                            onChange={(e) => setAlgorithmValue(e)}
                        >
                            <Option value={1}></Option>
                            <Option value={5}></Option>
                            <Option value={10}></Option>
                        </Select>
                    ) : (
                        ''
                    )}
                </>
            )
        );
    };
777

778 779 780 781
    const renderCurveOption = (isChart, isSingle, isStatus) => {
        return (
            <div
                className={classNames(`${prefixCls}-cover`)}
782
                style={isChart && isSingle ? {width: '100%'} : {}}
783 784 785 786 787 788 789 790 791 792 793
            >
                {isChart && !isStatus ? (
                    <>
                        <div className={classNames(`${prefixCls}-label`)}>曲线选择</div>
                        <div className={`${prefixCls}-cover-item`}>
                            <Radio.Group value={lineDataType} onChange={switchLineDataType}>
                                <Radio.Button value={'特征曲线'}>特征曲线</Radio.Button>
                                <Radio.Button value={'原始曲线'}>原始曲线</Radio.Button>
                            </Radio.Group>
                            <Tooltip title={'原始曲线数据量较大,单次查询最多展示1万条数据'}>
                                <QuestionCircleFilled
794
                                    style={{marginLeft: 6}}
795 796 797 798 799 800 801 802 803 804 805 806
                                    className={`${prefixCls}-question`}
                                />
                            </Tooltip>
                        </div>
                    </>
                ) : (
                    ''
                )}
                {isChart && isSingle && showBoxOption && !isStatus && !grid ? (
                    <>
                        {lineDataType !== '原始曲线' ? (
                            <>
807
                                <div style={{marginLeft: 7}} className={classNames(`${prefixCls}-label`)}>
808 809 810 811
                                    曲线形态
                                </div>
                                <Radio.Group
                                    value={chartType}
812
                                    style={{marginRight: 16}}
813 814 815
                                    onChange={(e) => {
                                        let _value = e.target.value;
                                        setChartType(_value);
816
                                        onCheckboxChange({target: {value: _value !== 'boxChart'}}, 'chartType');
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
                                    }}
                                >
                                    <Radio.Button value={'lineChart'}>线形图</Radio.Button>
                                    <Radio.Button value={'boxChart'}>箱线图</Radio.Button>
                                </Radio.Group>
                            </>
                        ) : (
                            ''
                        )}
                    </>
                ) : (
                    ''
                )}
                {!isStatus ? (
                    <>
                        <div className={classNames(`${prefixCls}-label`)}>
                            {activeTabKey !== 'table' ? '曲线设置' : '表格设置'}
                        </div>
                        {checkboxData.map((child) => {
                            const box = renderCheckbox(child, isChart && isSingle);
                            if (!box) return null;
                            return (
                                <div key={child.key} className={`${prefixCls}-cover-item`}>
                                    {box}
                                </div>
                            );
                        })}
                        {activeTabKey === 'table' && (
                            <Select
                                value={dataThinKey}
847
                                style={{width: 90}}
848 849
                                onChange={onTimeIntervalChange}
                                disabled={!dataConfig.dataThin}
850
                                getPopupContainer={trigger => trigger.parentElement}
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
                            >
                                {timeIntervalList
                                    .filter((item) => {
                                        let _diffDays = moment(dateRange[0].dateTo).diff(dateRange[0].dateFrom, 'days');
                                        return !(_diffDays > 7 && item.key === '1min');
                                    })
                                    .map((child) => {
                                        return (
                                            <Option key={child.key} unit={child.unit} value={child.key}>
                                                {child.name}
                                            </Option>
                                        );
                                    })}
                            </Select>
                        )}
                    </>
                ) : (
                    ''
                )}
            </div>
        );
    };

    const exportExcelBtn = () => {
        message.info('报表生成中,请稍后~');
        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)}`;
            let _quotas = i.sensors
                .split(',')
884
                .filter((item) => item !== '是否在线')
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
                .join(',');
            getExportDeviceHistoryUrl({
                deviceType: i.deviceType,
                deviceCode: i.deviceCode,
                quotas: _quotas,
                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 exportFeatureBtn = () => {
        message.info('报表生成中,请稍后~');
        let _dataSource = tableData.sort((a, b) => {
            let _a = a.time;
            let _b = b.time;
911
            if (timeValue === 'contrast') {
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
                if (contrastOption === 'day') {
                    _a = `2000-01-01 ${a.time}:00`;
                    _b = `2000-01-01 ${b.time}:00`;
                }
                if (contrastOption === 'month') {
                    _a = `2000-01-${a.time}:00`;
                    _b = `2000-01-${b.time}:00`;
                }
            }
            return timeOrder === 'ascend' ? moment(_a) - moment(_b) : moment(_b) - moment(_a);
        });
        let _columns = [...columns];
        let timeFrom = dateRange?.[0]?.dateFrom || moment().format(startFormat);
        let timeTo = dateRange?.[0]?.dateTo || moment().format(timeFormat);
        let fileName = `特征数据-${moment(timeFrom).format(dateFormat)}${moment(timeTo).format(
            dateFormat,
        )}`;
        let _dataIndex = [];
        let _titleWidth = [];
        let _title = _columns.map((item) => {
            _dataIndex.push(item.dataIndex);
            let _titleArr = [item.name, item.title];
            if (item.title.includes(item.name)) {
                _titleArr = [item.title];
936
            }
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
            let _titleStr = _titleArr.filter((item) => item).join('-');
            _titleWidth.push(_titleStr.length * 1);
            return _titleStr;
        });
        ExportExcel({
            name: fileName,
            content: [
                {
                    sheetData: _dataSource,
                    sheetFilter: _dataIndex,
                    sheetHeader: _title,
                    columnWidths: _titleWidth,
                },
            ],
        });
    };
953 954 955
    const exportCanvas = () => {
        setExportFlag(Math.random());
    };
956 957
    const handleTableData = useCallback(
        (data) => {
958 959
            // eslint-disable-next-line no-param-reassign
            // data = data.filter(item => item.sensorName !== '是否在线');
960 961
            const ignoreOutliers = checkboxData.find((item) => item.key === 'ignoreOutliers').checked;
            const dataIndexAccess = (dataItem, index) => {
962
                const {stationCode, sensorName} = dataItem;
963 964
                return `${stationCode}-${sensorName}-${index}`;
            };
965

966 967 968
            let format = timeFormat;
            if (timeValue === 'contrast') {
                format = contrastOption === 'day' ? '2020-01-01 HH:mm:00' : '2020-01-DD HH:mm:00';
969
            }
970 971 972
            // 判断是否是单设备,单设备则不显示设备名称
            // 处理表头数据
            const columnsData = data.map((item, index) => {
973
                const {stationCode, equipmentName, sensorName, unit, dataModel} = item;
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991
                const dataIndex = dataIndexAccess(item, index);
                let _title = '';
                if (deviceConfig.current.oneDevice) {
                    _title = `${sensorName}${unit ? `(${unit})` : ''}`;
                } else {
                    _title = `${equipmentName}-${sensorName}${unit ? `(${unit})` : ''}`;
                }
                let col = {
                    title: _title,
                    dataIndex: dataIndex,
                    key: dataIndex,
                    ellipsis: true,
                    align: 'center',
                    width: 200,
                    name: equipmentName,
                };
                // 同期对比
                if (timeValue === 'contrast' && dataModel[0]) {
992 993 994
                    const time = item.dataModel[0]?.pt
                        ?.slice(0, contrastOption === 'day' ? 10 : 7)
                        ?.replace(/-/g, '');
995 996 997 998
                    col.title = `${equipmentName}-${sensorName}-${time}`;
                }
                return col;
            });
999

1000 1001 1002
            // 格式化时间对齐数据, 生成行数
            const timeData = {};
            const buildDefaultData = (time) => {
1003
                const obj = {key: time, time: time};
1004 1005 1006 1007 1008 1009 1010 1011
                data.forEach((item, index) => {
                    const dataIndex = dataIndexAccess(item, index);
                    obj[dataIndex] = '';
                    obj.name = item.equipmentName;
                });
                return obj;
            };
            data.forEach((item, index) => {
1012
                const {stationCode, sensorName, dataModel} = item;
1013
                dataModel &&
1014 1015
                dataModel.forEach((data) => {
                    const formatTime = moment(data.pt).format(format);
1016

1017 1018 1019 1020
                    let time = formatTime;
                    if (timeValue === 'contrast') {
                        time = time.slice(contrastOption === 'day' ? 11 : 8, 16);
                    }
1021

1022 1023
                    timeData[formatTime] = timeData[formatTime] || buildDefaultData(time);
                });
1024 1025 1026
            });
            // 处理表格数据
            data.forEach((child, index) => {
1027
                const {dataModel} = child;
1028 1029
                const dataIndex = dataIndexAccess(child, index);
                dataModel &&
1030 1031 1032 1033 1034 1035 1036
                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;
                    }
                });
1037 1038 1039 1040
            });
            const timeSort = (a, b) => {
                let aa = a,
                    bb = b;
1041
                if (timeValue === 'contrast') {
1042 1043
                    aa = a.slice(contrastOption === 'day' ? 11 : 8, 16);
                    bb = b.slice(contrastOption === 'day' ? 11 : 8, 16);
1044
                }
1045 1046 1047 1048 1049 1050 1051 1052
                return timeOrder === 'descend' ? -aa.localeCompare(bb) : aa.localeCompare(bb);
            };
            const times = Object.keys(timeData).sort(timeSort);
            const tableData = times.map((time) => timeData[time]);
            setColumns([timeColumn, ...columnsData]);
            setTableData(tableData);
        },
        [timeOrder, timeValue, contrastOption],
1053
    );
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082

    const [deviceAlarmSchemes, setDeviceAlarmSchemes] = useState([]);
    const beforChangeParams = (value = {}) => {
        // 不需要报警标线 或者 多曲线、多设备时不显示报警标线
        let _lengthEqual0 = deviceParams?.length === 0;
        let _lengthEqual1 = deviceParams?.length === 1;
        let _lengthMoreThan1 = deviceParams?.length > 1;
        let returnNothing = !needMarkLine || _lengthEqual0 || _lengthMoreThan1 || (_lengthEqual1 && deviceParams[0].sensors.split(',').length > 1)
        if (returnNothing) return Promise.resolve();
        return getDeviceAlarmScheme({
            data: deviceParams.map((item) => ({
                deviceType: item.deviceType,
                deviceCode: item.deviceCode,
                pointAddressID: item.pointAddressID,
                sensorName: item.sensors,
            })),
        })
            .then((res) => {
                if (res.code === 0) setDeviceAlarmSchemes(res.data || []);
                else setDeviceAlarmSchemes([]);
                return Promise.resolve();
            })
            .catch((err) => {
                setDeviceAlarmSchemes([]);
                return Promise.resolve();
            });
    };
    const handleDataThinKey = (diffYears, diffDays, diffHours, lineDataType) => {
        if (lineDataType === '原始曲线') {
1083
            return {unit: '', zoom: ''};
1084 1085 1086
        }
        // edit by zy 根据选择的时长控制抽稀频度
        if (diffYears > 0) {
1087 1088
            if (diffYears === 1) return {unit: 'h', zoom: '24'};
            return {unit: 'h', zoom: '48'};
1089
        } else if (diffYears === 0 && diffDays > 0) {
1090 1091 1092 1093 1094 1095 1096
            if (diffDays > 90) return {unit: 'h', zoom: '24'};
            if (diffDays > 30) return {unit: 'h', zoom: '4'};
            if (diffDays > 15) return {unit: 'h', zoom: '2'};
            if (diffDays > 7) return {unit: 'h', zoom: '1'};
            if (diffDays > 3) return {unit: 'min', zoom: '20'};
            if (diffDays > 1) return {unit: 'min', zoom: '15'};
            if (diffDays === 1) return {unit: 'min', zoom: '5'};
1097
        } else if (diffYears === 0 && diffDays === 0 && diffHours > 0) {
1098 1099 1100 1101 1102
            if (diffHours > 12) return {unit: 'min', zoom: '5'};
            if (diffHours > 4) return {unit: 'min', zoom: '1'};
            if (diffHours > 1) return {unit: 's', zoom: '30'};
            if (diffHours > 0) return {unit: 's', zoom: '5'};
            return {unit: 's', zoom: '5'};
1103
        } else {
1104
            return {unit: '', zoom: ''};
1105
        }
1106 1107 1108 1109
    };

    // 处理接口服务参数的变化
    const onChangeParams = (value = {}) => {
1110
        const {dateRange, isDilute, ignoreOutliers, zoom, unit} = value;
1111 1112 1113 1114 1115 1116 1117 1118
        let _diffDays = moment(dateRange[0].dateTo).diff(dateRange[0].dateFrom, 'days');
        // 查询时段大于7天时,不提供1分钟的抽稀选项。
        if (_diffDays > 7 && zoom === '1' && unit === 'min') {
            return false;
        }
        const requestArr = [];
        const acrossTables = [];
        const zoomArray = [];
陈龙's avatar
陈龙 committed
1119
        // 这部分功能有问题,等待解决后上线 2024年3月13日
陈龙's avatar
陈龙 committed
1120
        let hasDiscreteDeviceType = false;
1121 1122
        deviceParams
            .map((item) => {
1123
                let _item = {...item};
1124 1125 1126 1127 1128 1129 1130 1131
                _item.sensors = item.sensors;
                // special 业务
                if (special1) {
                    _item.sensors += `,${special1.name}`;
                }
                return _item;
            })
            .forEach((i) => {
1132
                if (i.sensors && i.deviceCode)
1133
                    acrossTables.push(_.omit(i, ['pointAddressID']));
陈龙's avatar
陈龙 committed
1134
                // 这部分功能有问题,等待解决后上线 2024年3月13日
陈龙's avatar
陈龙 committed
1135 1136 1137
                if (discreteDeviceType.includes(i.deviceType)) {
                    hasDiscreteDeviceType = true;
                }
1138
            });
1139 1140 1141 1142
        if (!acrossTables?.length || !dateRange.length) {
            handleTableData([]);
            setChartDataSource([]);
            return;
1143
        }
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
        dateRange.forEach((item) => {
            const param = {
                isDilute,
                zoom,
                unit,
                ignoreOutliers,
                dateFrom: item.dateFrom,
                dateTo: item.dateTo,
                acrossTables,
                isBoxPlots: isBoxPlots,
            };
            let diffYears = moment(item.dateTo).diff(moment(item.dateFrom), 'years');
            let diffDays = moment(item.dateTo).diff(moment(item.dateFrom), 'days');
            let diffHours = moment(item.dateTo).diff(moment(item.dateFrom), 'hours');
            let zoomParam =
                activeTabKey === 'curve'
                    ? handleDataThinKey(diffYears, diffDays, diffHours, lineDataType)
                    : !isDilute
1162
                        ? {zoom: '', unit: ''}
1163
                        : {}; // 表格也支持全数据模式;
1164
            let _finalParams = {...param, ...zoomParam};
1165 1166 1167 1168 1169 1170
            // 2024年1月8日 抽稀间隔大于等于12小时时,会存在线性插值导致抽稀间隔内数据条数大于预期的问题。需要增加一个额外参数处理该情况。
            if (_finalParams.zoom) {
                let _num = Number(_finalParams.zoom);
                let _isNaN = isNaN(_num);
                if (!_isNaN && _num >= 12) _finalParams.isInterpolation = false;
            }
1171
            // 2024年1月23日 增加预测曲线,单设备单曲线
1172
            // 同期对比不允许、多设备的不允许预测
1173 1174 1175
            if (dateRange.length === 1 && predicateDevice) {
                _finalParams.acrossTables.push(predicateDevice);
            }
陈龙's avatar
陈龙 committed
1176 1177
            // 2024年3月11日 如果设备是某些特殊设备,则采用离散型算法
            // 这部分功能有问题,等待解决后上线 2024年3月13日
陈龙's avatar
陈龙 committed
1178 1179 1180
            if (hasDiscreteDeviceType && ignoreOutliers) {
                _finalParams.algorithmName = "derivative";
            }
1181
            requestArr.push(getHistoryInfo(_finalParams));
1182 1183 1184 1185 1186
        });
        setLoading(true);
        Promise.all(requestArr)
            .then((results) => {
                setLoading(false);
1187
                emptyOrError.current.error = false;
1188 1189 1190
                if (results.length) {
                    let data = [];
                    results.forEach((res, index) => {
1191
                        const {dateFrom, dateTo} = dateRange?.[index] ?? {};
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
                        if (res.code === 0 && res.data.length) {
                            res.data.forEach((d) => {
                                d.dateFrom = dateFrom || '';
                                d.dateTo = dateTo || '';
                                /**
                                 * @date: 2023年10月25日
                                 * @description: 数据连续补点之后,首值、尾值、最大值、最小值不会补,都为null。
                                 *     为保证显示,将补点之后的数据的首值、尾值、最大值、最小值同时为null的情况变更为点的值。
                                 *
                                 *     请注意,此项为重要变更,此变更会影响原始数据。
                                 */
陈龙's avatar
陈龙 committed
1203
                                // d.dataModel=[];
1204
                                d.dataModel = d.dataModel.map((item) => {
1205
                                    let {firstPV, lastPV, maxPV, minPV, pv} = item;
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
                                    if (pv !== null && firstPV === null && lastPV === null && maxPV === null && minPV === null) {
                                        firstPV = pv;
                                        lastPV = pv;
                                        maxPV = pv;
                                        minPV = pv;
                                    }
                                    return {
                                        ...item,
                                        firstPV,
                                        lastPV,
                                        maxPV,
                                        minPV,
                                    };
                                });
                            });
1221 1222
                            // 加入预测
                            (predicateDevice ? deviceParams.concat(predicateDevice) : deviceParams).forEach((p) => {
1223 1224 1225
                                // 返回数据按查询指标顺序排序
                                const sensors = p.sensors?.split(',') ?? [];
                                if (sensors?.length) {
1226
                                    sensors.push('是否在线');
1227 1228 1229 1230
                                    if (special1) {
                                        sensors.push(special1.name);
                                    }
                                }
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
                                const list = sensors.map((s) => {
                                    const dataItem = res.data.find(
                                        (d) => d.stationCode === p.deviceCode && d.sensorName === s,
                                    );
                                    if (dataItem) {
                                        dataItem.dateFrom = dateFrom || '';
                                        dataItem.dateTo = dateTo || '';
                                        dataItem.deviceType = p.deviceType;
                                        return dataItem;
                                    } else {
                                        return {};
                                    }
                                }).filter((item) => item.sensorName);
                                // 预测的
1245
                                data = data.concat(list);
1246
                                // _predicateData = _predicateData.concat(list.filter(item => item.deviceType === '预测'));
1247 1248 1249 1250
                            });
                        }
                    });
                    setLoading(false);
1251 1252
                    if (data.length !== 0) {
                        emptyOrError.current.empty = false;
1253 1254
                    } else {
                        data = handleFakeData(dateRange, deviceParams) ?? []
1255
                    }
1256
                    handleTableData(data)
1257
                    setChartDataSource(data);
1258
                    // setPredicateData(_predicateData);
1259 1260 1261
                }
            })
            .catch((err) => {
1262 1263 1264
                let data = handleFakeData(dateRange, deviceParams) ?? [];
                handleTableData(data);
                setChartDataSource(data);
1265 1266 1267 1268 1269 1270 1271
                message.info('未查询到数据,请重试~');
                setLoading(false);
            });
    };

    useEffect(() => {
        if (!completeInit) return;
1272
        const {dataThin, ignoreOutliers, zoom, unit} = dataConfig;
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
        beforChangeParams().finally(() => {
            onChangeParams({
                isDilute: dataThin,
                ignoreOutliers,
                zoom,
                unit,
                dateRange,
                isBoxPlots: isBoxPlots,
            });
        });
    }, [dateRange, dataConfig, deviceParams, chartType, lineDataType, completeInit, algorithmValue]);
    const handleChange = (pagination, filter, sort) => {
        if (sort.field === 'time') {
            setTimeOrder(sort.order);
1287
        }
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
    };
    const tableMemo = useMemo(() => {
        return (
            <>
                <div className={`${prefixCls}-options`}>
                    {renderTimeOption}
                    {renderCurveOption()}
                </div>
                <div className={`${prefixCls}-content`} ref={tableRef}>
                    {chartDataSource.length > 0 ? (
                        // <BasicTable
                        <VirtualTable
1300 1301
                            className={`${prefixCls}-virtual-table`}
                            theme={theme}
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
                            dataSource={tableData.sort((a, b) => {
                                let _a = a.time;
                                let _b = b.time;
                                if (timeValue === 'contrast') {
                                    if (contrastOption === 'day') {
                                        _a = `2000-01-01 ${a.time}:00`;
                                        _b = `2000-01-01 ${b.time}:00`;
                                    }
                                    if (contrastOption === 'month') {
                                        _a = `2000-01-${a.time}:00`;
                                        _b = `2000-01-${b.time}:00`;
                                    }
                                }
                                return timeOrder === 'ascend' ? moment(_a) - moment(_b) : moment(_b) - moment(_a);
                            })}
                            columns={columns}
                            tableProps={tableProps}
                            pagination={false}
                            onChange={handleChange}
                            // scroll={{ x: 'max-content', y: 'calc(100% - 40px)' }}
                            scroll={{
                                x: 'max-content',
                                y: tableRef.current ? tableRef.current.getBoundingClientRect().height - 40 : 0,
                            }}
                        />
                    ) : (
1328
                        <PandaEmpty/>
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
                    )}
                </div>
            </>
        );
    }, [
        timeOrder,
        chartDataSource,
        columns,
        tableProps,
        tableData,
        isSingleStatusSensor,
        dateRange,
        tableRef.current,
    ]);
    const returnLongestPeriod = (data) => {
        let _earliest = '';
        let _latest = '';
        data.forEach((item) => {
            let _length = item.dataModel.length;
            let _tempFirst = item.dataModel[0].pt;
            let _tempLast = item.dataModel[_length - 1].pt;
            if (_earliest) {
                _earliest = moment(_earliest) > moment(_tempFirst) ? _tempFirst : _earliest;
            } else {
                _earliest = _tempFirst;
            }
            if (_latest) {
                _latest = moment(_latest) < moment(_tempLast) ? _tempLast : _latest;
            } else {
                _latest = _tempLast;
            }
        });
        return `${_earliest} - ${_latest}`;
    };
    const renderPanel = (model) => {
        if (model === 'curve') {
            return (
1366
                <>
1367 1368 1369 1370 1371 1372 1373 1374 1375
                    <div className={`${prefixCls}-options`}>
                        {renderTimeOption}
                        {renderCurveOption(
                            true,
                            deviceParams?.length === 1 && deviceParams?.[0]?.sensors?.split(',').length === 1,
                            isSingleStatusSensor,
                        )}
                    </div>
                    {lineDataType === '原始曲线' && false ? (
1376
                        <div style={{marginTop: 10}}>展示区间:{returnLongestPeriod(chartDataSource)}</div>
1377 1378 1379 1380
                    ) : (
                        ''
                    )}
                    <div className={`${prefixCls}-content`}>
陈龙's avatar
陈龙 committed
1381
                        {grid === true ? (
1382
                            <GridChart
1383
                                emptyOrError={emptyOrError.current}
1384 1385 1386 1387 1388 1389
                                curveCenter={curveCenter}
                                prefixCls={prefixCls}
                                dataSource={chartDataSource}
                                contrast={timeValue === 'contrast'}
                                contrastOption={contrastOption}
                                deviceAlarmSchemes={deviceAlarmSchemes}
1390 1391 1392 1393 1394
                                dateRange={dateRange}
                                allPointAddress={allPointAddress}
                                allSensorType={allSensorType}
                                loading={loading}
                                setLoading={setLoading}
1395 1396 1397
                            />
                        ) : (
                            <SingleChart
1398
                                exportCanvas={{exportFlag, setExportFlag}}
1399
                                emptyOrError={emptyOrError.current}
陈龙's avatar
陈龙 committed
1400
                                dateRange={dateRange}
1401 1402 1403 1404 1405 1406
                                showBoxOption={showBoxOption}
                                lineDataType={lineDataType}
                                curveCenter={curveCenter}
                                showGridLine={chartGrid}
                                prefixCls={prefixCls}
                                dataSource={chartDataSource}
1407
                                predicateData={predicateData}
1408 1409 1410 1411
                                chartType={isBoxPlots ? chartType : null}
                                contrast={timeValue === 'contrast'}
                                contrastOption={contrastOption}
                                deviceAlarmSchemes={deviceAlarmSchemes}
陈龙's avatar
陈龙 committed
1412
                                theme={theme}
1413 1414 1415 1416 1417 1418 1419 1420
                                special={{
                                    special1, // 频率业务
                                    allPointAddress,
                                    allSensorType, // 后续新增的开关量的特殊业务,用来处理开关量业务
                                }}
                            />
                        )}
                    </div>
1421
                </>
1422 1423 1424 1425 1426 1427 1428 1429
            );
        }
        if (model === 'table') {
            return tableMemo;
        }
    };
    // 获取字段配置
    const getDefaultOptions = async () => {
陈龙's avatar
陈龙 committed
1430 1431
        // 特定设备
        // 这部分功能有问题,等待解决后上线 2024年3月13日
陈龙's avatar
陈龙 committed
1432 1433 1434 1435 1436 1437 1438 1439 1440
        getDictionaryInfoAll({
            level: '离散算法设备类型',
        }).then(res => {
            if (res.code === 0 && res.data.length) {
                let deviceType = res.data.find(item => item.fieldName === '设备类型')?.fieldValue;
                setDiscreteDeviceType(deviceType.split(',').filter(item => item))
            }
        })

1441 1442 1443 1444
        // 非单曲线、单指标不执行
        if (
            deviceParams?.length !== 1 ||
            (deviceParams?.length === 1 && deviceParams?.[0]?.sensors?.split(',')?.length > 1)
1445 1446
        )
            return setCompleteInit(true);
1447
        setLoading(true);
1448
        const {deviceCode, deviceType, sensors} = deviceParams[0];
1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
        let _id = (
            await getPointAddress({
                code: deviceCode,
            })
        )?.data?.[0]?.id;
        let _params = {};
        if (_id) _params.versionId = _id;
        // 多曲线的居中,容易导致曲线被截断,故多曲线时,不请求
        let _request0 = getDictionaryInfoAll({
            level: '组件_ec_historyview',
        });
        // 以下请求为处理状态值、开关值的图表,只允许单曲线单指标情况下展示
        let _request1 = getPointAddressEntry(_params);
        let _request2 = getSensorType();
1463
        // let _request3 = getPredicateSensor({deviceCode, sensors});
1464
        await Promise.all([_request0, _request1, _request2]).then((result) => {
1465 1466 1467 1468
            if (result) {
                let _res0 = result[0];
                let _res1 = result[1];
                let _res2 = result[2];
1469
                // let _res3 = result[3];
1470 1471
                let _checkboxData = [...checkboxData];
                // 单设备单曲线时,查询是否配置为预测点
1472
                /*                if (_res3.code === 0 && _res3.data) {
1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
                                    // 1. 如果是单曲线,并且配置了预测,那么默认开启预测;
                //                    2024年3月11日 物联预测功能支撑后,再开发这部分
                                                        _checkboxData.push({
                                                            key: 'predicate',
                                                            label: '数据预测',
                                                            checked: true,
                                                            showInCurve: true,
                                                            showInTable: true,
                                                        })
                                    setPredicateDevice({..._res3.data, deviceType: '预测'});
                                } else {
                                    setPredicateDevice(null);
                                }*/
1486 1487 1488 1489 1490 1491
                // 查字典配置
                if (_res0.code === 0) {
                    let _opt = _res0.data.reduce((final, cur) => {
                        final[cur.fieldName] = cur.fieldValue;
                        return final;
                    }, {});
1492
                    _checkboxData = _checkboxData.map((item) => {
1493
                        let _item = {...item};
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532
                        if (_opt[item.label] !== undefined) {
                            _item.checked = _opt[item.label] === 'true';
                        }
                        return _item;
                    });
                    setCheckboxData(_checkboxData);
                }
                // 查点表配置
                if (_res1.code === 0) {
                    let _sensorConfig = _res1.data.find((item) => item?.name.trim() === sensors.trim());
                    let _statusName = _sensorConfig?.statusName;
                    setAllPointAddress(_res1.data);
                    if (_statusName) {
                        let _statusConfig = _res1.data.find((item) => item?.name.trim() === _statusName.trim());
                        let _valDesc = _statusConfig?.valDesc || '';
                        setSpecial1({
                            name: _statusName,
                            valDesc: _valDesc.split(';').reduce((final, cur) => {
                                let _arr = cur.split(':');
                                final[_arr[0]] = _arr[1];
                                return final;
                            }, {}),
                        });
                    }
                }
                // 标记sensor是什么类型的
                if (_res2.code === 0) {
                    setAllSensorType(_res2.data);
                    let _sensorID = _res1.data?.find((item) => item.name === sensors)?.sensorTypeID;
                    let _sensor = _res2.data?.find((item) => item.id === _sensorID)?.type;
                    let _isStatusSensor = ['状态值', '开关值'].includes(_sensor);
                    setIsSingleStatusSensor(_isStatusSensor);
                }
            }
        });
        setCompleteInit(true);
    };
    useEffect(() => {
        getDefaultOptions();
1533
    }, [deviceParams]);
1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
    let percentTimer = useRef({
        timer: null,
    });
    //  加载动画
    useEffect(() => {
        if (loading === null) return;
        if (loading) {
            let _percent = percent;
            percentTimer.current.timer = setInterval(() => {
                _percent += 5;
                if (_percent > 95) return clearInterval(percentTimer.current.timer);
                setPercent(_percent);
            }, 100);
        } else {
            clearInterval(percentTimer.current.timer);
            setPercent(100);
            setTimeout(
                () => {
                    setPercent(0);
                },
                lineDataType === '原始曲线' ? 500 : 0,
            );
        }
    }, [loading]);
    return (
1559
        <div
1560
            className={classNames(prefixCls, theme === 'BI' ? BIStyles[`${prefixCls}-historyViewComponents`] : '', 'wkt-scroll-light')}
1561 1562
            style={{background: theme === 'BI' ? '#282b34' : '#ffffff'}}>
            <div className={classNames(`${prefixCls}-spin`)} style={{position: 'relative'}}>
1563 1564 1565
                {loading || percent !== 0 ? (
                    <div className={classNames(`${prefixCls}-progressWrapper`)}>
                        {lineDataType === '原始曲线' ||
1566 1567 1568
                        (lineDataType === '特征曲线' &&
                            moment(dateRange?.[0]?.dateTo).diff(moment(dateRange?.[0]?.dateFrom), 'days') >=
                            30) ?
1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
                            <div className={classNames(`${prefixCls}-contentWrapper`)}>
                                <Progress
                                    percent={percent}
                                    steps={20}
                                    className={classNames(`${prefixCls}-progress`, `${prefixCls}-blink-2`)}
                                    showInfo={false}
                                />
                                <div className={classNames(`${prefixCls}-tip`)}>加载中...</div>
                            </div> :
                            <Spin spinning={loading || false} tip={'数据加载中...'} delay={1000}
1579
                                  style={{background: 'transparent'}}/>
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599
                        }
                    </div>
                ) : (
                    ''
                )}
                {showModels.length === 1 && (
                    <div className={`${prefixCls}-single-panel`}>{renderPanel(showModels[0])}</div>
                )}
                {showModels.length > 1 && (
                    <Tabs
                        activeKey={activeTabKey}
                        onChange={(key) => setActiveTabKey(key)}
                        centered
                        tabBarExtraContent={{
                            left: <h3>{title}</h3>,
                            right: (
                                <div className={`${prefixCls}-extra-right`}>
                                    {activeTabKey === 'table' && (
                                        <>
                                            <Button type="link" onClick={exportFeatureBtn}>
1600
                                                <DownloadOutlined/>
1601 1602 1603 1604
                                                下载
                                            </Button>
                                        </>
                                    )}
1605 1606 1607
                                    {activeTabKey === 'curve' && (
                                        <>
                                            <Button type="link" onClick={exportCanvas}>
1608
                                                <DownloadOutlined/>
1609 1610 1611 1612
                                                下载
                                            </Button>
                                        </>
                                    )}
1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624
                                </div>
                            ),
                        }}
                    >
                        <Tabs.TabPane key="curve" tab="曲线" forceRender={true}>
                            {activeTabKey === 'curve' ? renderPanel('curve') : ''}
                        </Tabs.TabPane>
                        <Tabs.TabPane key="table" tab="表格">
                            {renderPanel('table')}
                        </Tabs.TabPane>
                    </Tabs>
                )}
1625
            </div>
1626
        </div>
陈龙's avatar
陈龙 committed
1627
    )
1628 1629 1630
};

HistoryView.propTypes = {
1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645
    grid: PropTypes.bool,
    title: PropTypes.string,
    defaultChecked: PropTypes.oneOf(['twelveHours', 'roundClock', 'oneWeek', 'oneMonth']),
    tableProps: PropTypes.object,
    deviceParams: PropTypes.arrayOf(
        PropTypes.objectOf({
            deviceCode: PropTypes.string,
            sensors: PropTypes.string,
            deviceType: PropTypes.string,
            pointAddressID: PropTypes.number, // 可选,配置了将会查询相关报警方案配置
        }),
    ),
    defaultModel: PropTypes.oneOf(['curve', 'table']),
    showModels: PropTypes.arrayOf(PropTypes.oneOf(['curve', 'table'])),
    defaultDate: PropTypes.string,
陈龙's avatar
陈龙 committed
1646
    BIMode: PropTypes.bool
1647 1648 1649
};

HistoryView.defaultProps = {
1650 1651 1652 1653 1654 1655 1656 1657
    grid: false,
    title: '指标曲线',
    defaultChecked: 'roundClock',
    tableProps: {},
    defaultModel: 'curve',
    showModels: ['curve', 'table'],
    needMarkLine: true,
    defaultDate: 'day',
陈龙's avatar
陈龙 committed
1658
    BIMode: false
1659 1660
};

1661
export default HistoryView;