index.js 27.2 KB
Newer Older
程恺文's avatar
程恺文 committed
1
import React, { useContext, useEffect, useMemo, useState } from 'react';
2 3
import PropTypes from 'prop-types';
import classNames from 'classnames';
张瑶's avatar
张瑶 committed
4
import {
程恺文's avatar
程恺文 committed
5 6 7 8 9 10 11 12 13
  Checkbox,
  ConfigProvider,
  DatePicker,
  Radio,
  Select,
  Spin,
  Tabs,
  Tooltip,
  Button,
张瑶's avatar
张瑶 committed
14 15
} from 'antd';
import {
程恺文's avatar
程恺文 committed
16 17 18 19
  CloseCircleFilled,
  PlusCircleOutlined,
  QuestionCircleFilled,
  DownloadOutlined,
张瑶's avatar
张瑶 committed
20
} from '@ant-design/icons';
21 22 23
import moment from 'moment';
import _ from 'lodash';
import TimeRangePicker from '@wisdom-components/timerangepicker';
24
import PandaEmpty from '@wisdom-components/empty';
25
import BasicTable from '@wisdom-components/basictable';
程恺文's avatar
程恺文 committed
26
import { getHistoryInfo, getDeviceAlarmScheme, getExportDeviceHistoryUrl } from './apis';
27 28 29
import SimgleChart from './SingleChart';
import GridChart from './GridChart';
import './index.less';
程恺文's avatar
程恺文 committed
30
import { globalConfig } from 'antd/lib/config-provider';
31

程恺文's avatar
程恺文 committed
32 33
const { RangePicker } = DatePicker;
const { Option } = Select;
34 35 36 37

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
38
const dateFormat = 'YYYYMMDD';
39 40

const timeList = [
程恺文's avatar
程恺文 committed
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
  {
    key: 'twelveHours',
    name: '近12小时',
  },
  {
    key: 'roundClock',
    name: '近24小时',
  },
  {
    key: 'oneWeek',
    name: '近1周',
  },
  {
    key: 'oneMonth',
    name: '近1月',
  },
57 58 59
];

const CheckboxData = [
程恺文's avatar
程恺文 committed
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
  {
    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: '本算法采用递推平均滤波法(滑动平均滤波法)对采样数据进行均值化平滑处理。',
  },
  //    需求变更,剔除
  /*    {
85 86 87 88 89 90
        key: 'justLine',
        label: '仅查看曲线',
        type: '',
        checked: false,
        showInCurve: false,
        showInTable: false,
陈龙's avatar
陈龙 committed
91
    },*/
程恺文's avatar
程恺文 committed
92 93 94 95 96 97 98 99
  {
    key: 'dataThin',
    label: '数据抽稀',
    type: 'updateDataThin',
    checked: true,
    showInCurve: false,
    showInTable: true,
  },
100 101 102
];

const timeIntervalList = [
程恺文's avatar
程恺文 committed
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 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 149 150
  {
    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小时',
  },
151 152 153
];

const updateTime = (key) => {
程恺文's avatar
程恺文 committed
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
  let start = '';
  let end = '';

  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 '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;
178
    }
程恺文's avatar
程恺文 committed
179 180 181 182 183 184 185
  }
  return [
    {
      dateFrom: start,
      dateTo: end,
    },
  ];
186 187 188
};

const DefaultDatePicker = (value) => [
程恺文's avatar
程恺文 committed
189 190 191 192 193 194 195 196
  {
    key: 1,
    value: moment(),
  },
  {
    key: 2,
    value: moment().subtract(1, value),
  },
197 198 199
];

const handleBatchTime = (arr, cOption) => {
程恺文's avatar
程恺文 committed
200 201 202 203 204 205 206 207 208 209 210
  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;
211 212 213
};

const timeColumn = {
程恺文's avatar
程恺文 committed
214 215 216 217 218 219 220
  title: '采集时间',
  dataIndex: 'time',
  key: 'time',
  width: 170,
  fixed: 'left',
  ellipsis: true,
  align: 'center',
221 222
};

李纪文's avatar
李纪文 committed
223
const HistoryView = (props) => {
程恺文's avatar
程恺文 committed
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 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
  const { getPrefixCls } = useContext(ConfigProvider.ConfigContext);
  const prefixCls = getPrefixCls('history-view');

  const {
    title,
    grid,
    defaultChecked,
    tableProps,
    deviceParams,
    defaultModel,
    showModels,
    needMarkLine,
  } = props;
  const isBoxPlots =
    deviceParams?.length === 1 && deviceParams[0]?.sensors?.split(',').length === 1;
  const [loading, setLoading] = useState(false);
  const [activeTabKey, setActiveTabKey] = useState(defaultModel);

  // 时间模式: 自定义模式/同期对比模式
  const [timeValue, setTimeValue] = useState('customer');

  // 自定义模式
  const [customerChecked, setCustomerChecked] = useState(defaultChecked); // 时间快速选择类型值
  const [customerTime, setCustomerTime] = useState(); // 自定义时间选择值

  // 同期对比模式
  const [contrastOption, setContrastOption] = useState('day'); // 对比时间类型: 日/月
  const [datePickerArr, setDatePickerArr] = useState(DefaultDatePicker('day')); // 对比时间段配置值

  const [checkboxData, setCheckboxData] = useState(() => [...CheckboxData]); // 曲线设置项
  const [dataThinKey, setDataThinKey] = useState(timeIntervalList[0].key); // 曲线抽稀时间设置

  const [columns, setColumns] = useState([]);
  const [tableData, setTableData] = useState([]);
  const [chartDataSource, setChartDataSource] = useState([]);

  const [chartType, setChartType] = useState('lineChart');
  const [showBoxOption, setShowBoxOption] = useState(true);
  // 选择的时间范围值
  const dateRange = useMemo(() => {
    if (timeValue === 'customer') {
      return updateTime(customerChecked || customerTime);
    } else {
      return handleBatchTime(datePickerArr, contrastOption);
    }
  }, [contrastOption, customerChecked, customerTime, datePickerArr, timeValue]);

  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: '', // 数据抽稀时间单位
282
    };
程恺文's avatar
程恺文 committed
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
    // 曲线居中,过滤异常值,数据抽稀
    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);
    }
  };
321

程恺文's avatar
程恺文 committed
322 323 324 325 326
  // 同期对比模式: 选择(日/月)
  const onContrastChange = (value) => {
    setContrastOption(value);
    setDatePickerArr([...DefaultDatePicker(value)]);
  };
327

程恺文's avatar
程恺文 committed
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
  // 同期对比模式: 时间段选择
  const onContrastPickerChange = (date, dateString, item) => {
    const arr = [...datePickerArr];
    arr.forEach((child) => {
      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);
      setShowBoxOption(false);
      setChartType('lineChart');
      onCheckboxChange({ target: { value: false } }, 'chartType');
      onCheckboxChange({ target: { value: false } }, 'ignoreOutliers');
    } else {
      // 自定义
      // 不需要处理
      setShowBoxOption(true);
      onCheckboxChange({ target: { value: true } }, 'chartType');
    }
  };
374

程恺文's avatar
程恺文 committed
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
  const renderTimeOption = () => {
    return (
      <div className={classNames(`${prefixCls}-date`)}>
        <div className={classNames(`${prefixCls}-label`)}>时间选择</div>
        <Radio.Group value={timeValue} onChange={onTimeSetChange}>
          <Radio.Button value="customer">自定义</Radio.Button>
          <Radio.Button value="contrast">同期对比</Radio.Button>
        </Radio.Group>
        {timeValue === 'customer' && ( // 自定义
          <>
            <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>
423
                )}
程恺文's avatar
程恺文 committed
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
              </div>
            ))}
            {datePickerArr.length < 5 && <PlusCircleOutlined onClick={handleAddDatePicker} />}
          </>
        )}
      </div>
    );
  };

  // 曲线设置项选择/取消
  const onCheckboxChange = (e, key, showJustLine) => {
    let data = [...checkboxData];
    // let _index = data.findIndex(item => item.key === 'justLine'); // 仅查看曲线会在勾选了数据滤波后展示
    let _index1 = data.findIndex((item) => item.key === 'ignoreOutliers'); // 仅查看曲线会在勾选了数据滤波后展示
    data.forEach((item) => {
      if (item.key === key) {
        item.checked = e.target.checked;
      }
    });
    if (key === 'ignoreOutliers') {
      //            需求变更,仅查看曲线剔除
      /*            if (showJustLine) {
陈龙's avatar
陈龙 committed
446 447 448
                data[_index].showInCurve = e.target.checked;
                data[_index].checked = e.target.checked;
            } else {*/
程恺文's avatar
程恺文 committed
449 450 451 452
      data[_index1].showInCurve = true;
      // data[_index1].checked = false;
      // }
    }
陈龙's avatar
陈龙 committed
453

程恺文's avatar
程恺文 committed
454 455 456 457 458 459 460 461
    if (key === 'chartType') {
      data[_index1].showInCurve = e.target.value;
      data[_index1].checked = false;
      // data[_index].showInCurve = false;
      // data[_index].checked = false;
    }
    setCheckboxData(data);
  };
462

程恺文's avatar
程恺文 committed
463 464 465 466
  // 数据抽稀时间间隔
  const onTimeIntervalChange = (value) => {
    setDataThinKey(value);
  };
467

程恺文's avatar
程恺文 committed
468 469 470 471
  const renderCheckbox = (child, showJustLine) => {
    const curveAccess = activeTabKey === 'curve' && child.showInCurve;
    const tableAccess = activeTabKey === 'table' && child.showInTable;
    const gridOptions = ['curveCenter'];
472

程恺文's avatar
程恺文 committed
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
    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}>
              <QuestionCircleFilled className={`${prefixCls}-question`} />
            </Tooltip>
          )}
        </>
      )
    );
  };

  const renderCurveOption = (isChart, isSingle) => {
    return (
      <div
        className={classNames(`${prefixCls}-cover`)}
        style={isChart && isSingle ? { width: '100%' } : {}}
      >
        {isChart && isSingle && showBoxOption ? (
          <>
            <div className={classNames(`${prefixCls}-label`)}>曲线形态</div>
            <Radio.Group
              value={chartType}
              style={{ marginRight: 16 }}
              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, isChart && isSingle);
          if (!box) return null;
          return (
            <div key={child.key} className={`${prefixCls}-cover-item`}>
              {box}
522
            </div>
程恺文's avatar
程恺文 committed
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
          );
        })}
        {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();
        })
566
        .catch((err) => { });
程恺文's avatar
程恺文 committed
567 568
    });
  };
569

程恺文's avatar
程恺文 committed
570 571 572 573 574
  const handleTableData = (data) => {
    const ignoreOutliers = checkboxData.find((item) => item.key === 'ignoreOutliers').checked;
    const dataIndexAccess = (dataItem, index) => {
      const { stationCode, sensorName } = dataItem;
      return `${stationCode}-${sensorName}-${index}`;
李纪文's avatar
李纪文 committed
575 576
    };

程恺文's avatar
程恺文 committed
577 578 579 580
    let format = timeFormat;
    if (timeValue === 'contrast') {
      format = contrastOption === 'day' ? '2020-01-01 HH:mm:00' : '2020-01-DD HH:mm:00';
    }
581

程恺文's avatar
程恺文 committed
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
    // 处理表头数据
    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;
    });
602

程恺文's avatar
程恺文 committed
603 604
    // 格式化时间对齐数据, 生成行数
    const timeData = {};
605

程恺文's avatar
程恺文 committed
606 607 608 609 610 611 612
    const buildDefaultData = (time) => {
      const obj = { key: time, time: time };
      data.forEach((item, index) => {
        const dataIndex = dataIndexAccess(item, index);
        obj[dataIndex] = '';
      });
      return obj;
613
    };
程恺文's avatar
程恺文 committed
614 615
    data.forEach((item, index) => {
      const { stationCode, sensorName, dataModel } = item;
徐乐's avatar
徐乐 committed
616
      dataModel && dataModel.forEach((data) => {
程恺文's avatar
程恺文 committed
617
        const formatTime = moment(data.pt).format(format);
618

程恺文's avatar
程恺文 committed
619 620 621
        let time = formatTime;
        if (timeValue === 'contrast') {
          time = time.slice(contrastOption === 'day' ? 11 : 8, 16);
622 623
        }

程恺文's avatar
程恺文 committed
624 625 626 627 628 629 630 631
        timeData[formatTime] = timeData[formatTime] || buildDefaultData(time);
      });
    });

    // 处理表格数据
    data.forEach((child, index) => {
      const { dataModel } = child;
      const dataIndex = dataIndexAccess(child, index);
徐乐's avatar
徐乐 committed
632
      dataModel && dataModel.forEach((value, j) => {
程恺文's avatar
程恺文 committed
633 634 635 636
        const formatTime = moment(value.pt).format(format);
        const dataRow = timeData[formatTime];
        if (dataRow) {
          dataRow[dataIndex] = value.pv === null || value.pv === undefined ? '' : value.pv;
637
        }
程恺文's avatar
程恺文 committed
638 639 640 641 642 643 644 645 646 647
      });
    });
    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);
648
    };
程恺文's avatar
程恺文 committed
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
    const times = Object.keys(timeData).sort(timeSort);
    const tableData = times.map((time) => timeData[time]);
    setColumns([timeColumn, ...columnsData]);
    setTableData(tableData);
  };

  const [deviceAlarmSchemes, setDeviceAlarmSchemes] = useState([]);
  const beforChangeParams = (value = {}) => {
    if (!needMarkLine) 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 = (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 if (diffDays < 7 && diffDays >= 2) {
      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
      .map((item) => {
        let _item = { ...item };
        _item.sensors =
          item.sensors && !item.sensors.includes('是否在线')
            ? item.sensors + ',是否在线'
            : item.sensors;
        return _item;
      })
      .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) => {
徐乐's avatar
徐乐 committed
742 743
              d.dateFrom = dateFrom || '';
              d.dateTo = dateTo || '';
744
            });
程恺文's avatar
程恺文 committed
745 746 747 748 749 750 751
            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,
                );
752 753 754 755 756 757 758
                if (dataItem) {
                  dataItem.dateFrom = dateFrom || '';
                  dataItem.dateTo = dateTo || '';
                  return dataItem;
                } else {
                  return {};
                }
徐乐's avatar
徐乐 committed
759

程恺文's avatar
程恺文 committed
760 761 762 763
              });
              data = data.concat(list);
            });
          }
764
        });
程恺文's avatar
程恺文 committed
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
        setLoading(false);
        handleTableData(data);
        setChartDataSource(data);
      }
    });
  };

  useEffect(() => {
    const { dataThin, ignoreOutliers, zoom, unit } = dataConfig;
    beforChangeParams().finally(() => {
      onChangeParams({
        isDilute: dataThin,
        ignoreOutliers,
        zoom,
        unit,
        dateRange,
        isBoxPlots: isBoxPlots,
      });
    });
  }, [dateRange, dataConfig, deviceParams, chartType]);

  const renderPanel = (model) => {
    if (model === 'curve') {
      return (
        <>
          <div className={`${prefixCls}-options`}>
            {renderTimeOption()}
            {renderCurveOption(
              true,
              deviceParams?.length === 1 && deviceParams[0]?.sensors?.split(',').length === 1,
            )}
          </div>
          <div className={`${prefixCls}-content`}>
            {!chartDataSource.length ? (
              <PandaEmpty />
            ) : grid === true ? (
              <GridChart
                curveCenter={curveCenter}
                prefixCls={prefixCls}
                dataSource={chartDataSource}
                contrast={timeValue === 'contrast'}
                contrastOption={contrastOption}
                deviceAlarmSchemes={deviceAlarmSchemes}
              />
            ) : (
              <SimgleChart
                showBoxOption={showBoxOption}
                curveCenter={curveCenter}
                showGridLine={chartGrid}
                prefixCls={prefixCls}
                dataSource={chartDataSource}
                // justLine={!!checkboxData.find(item => item.key === 'justLine' && item.checked)}
                chartType={isBoxPlots ? chartType : null}
                contrast={timeValue === 'contrast'}
                contrastOption={contrastOption}
                deviceAlarmSchemes={deviceAlarmSchemes}
              />
            )}
          </div>
        </>
      );
    }
    if (model === 'table') {
      return (
        <>
          <div className={`${prefixCls}-options`}>
            {renderTimeOption()}
            {renderCurveOption()}
          </div>
          <div className={`${prefixCls}-content`}>
            {chartDataSource.length > 0 ? (
              <BasicTable
                dataSource={tableData}
                columns={columns}
                {...tableProps}
                pagination={false}
841
                onChange={() => { }}
程恺文's avatar
程恺文 committed
842 843 844 845 846 847 848 849 850 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 884 885 886 887
              />
            ) : (
              <PandaEmpty />
            )}
          </div>
        </>
      );
    }
  };

  return (
    <div className={classNames(prefixCls)}>
      <Spin spinning={loading} wrapperClassName={classNames(`${prefixCls}-spin`)}>
        {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={exportExcelBtn}>
                      <DownloadOutlined />
                      下载
                    </Button>
                  )}
                </div>
              ),
            }}
          >
            <Tabs.TabPane key="curve" tab="曲线">
              {renderPanel('curve')}
            </Tabs.TabPane>
            <Tabs.TabPane key="table" tab="表格">
              {renderPanel('table')}
            </Tabs.TabPane>
          </Tabs>
        )}
      </Spin>
    </div>
  );
888 889 890
};

HistoryView.propTypes = {
程恺文's avatar
程恺文 committed
891 892 893 894 895 896 897 898 899 900 901 902 903 904
  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'])),
905 906 907
};

HistoryView.defaultProps = {
程恺文's avatar
程恺文 committed
908 909 910 911 912 913 914
  grid: false,
  title: '指标曲线',
  defaultChecked: 'roundClock',
  tableProps: {},
  defaultModel: 'curve',
  showModels: ['curve', 'table'],
  needMarkLine: true,
915 916 917
};

export default HistoryView;