index.js 27.5 KB
Newer Older
涂茜's avatar
涂茜 committed
1 2 3 4 5
import React, { useContext, useState, useReducer, useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import Highcharts from 'highcharts/highstock';
import HighchartsReact from 'highcharts-react-official';
涂茜's avatar
涂茜 committed
6
import HighchartsBoost from 'highcharts/modules/boost';
涂茜's avatar
涂茜 committed
7 8
import { Button, Tabs, Select, Radio, Checkbox, ConfigProvider, DatePicker, Spin } from 'antd';
import { PlusCircleOutlined, CloseCircleFilled, DownloadOutlined } from '@ant-design/icons';
涂茜's avatar
涂茜 committed
9 10 11
import TimeRangePicker from '@wisdom-components/timerangepicker';
import BasicTable from '@wisdom-components/basictable';
import Empty from '@wisdom-components/empty';
涂茜's avatar
涂茜 committed
12
import { ExportExcel } from '@wisdom-components/exportexcel';
涂茜's avatar
涂茜 committed
13 14 15
import moment from 'moment';
import './index.less';

涂茜's avatar
涂茜 committed
16 17
HighchartsBoost(Highcharts);

涂茜's avatar
涂茜 committed
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 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 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
const { TabPane } = Tabs;
const { RangePicker } = DatePicker;
const { Option } = Select;

const UPDATE_TIME = {
  UPDATE_TIME: 'updateTime',
  UPDATE_BATCH_TIME: 'updateBatchTime',
  UPDATE_DATA_THIN: 'updateDataThin',
};

const reducer = (state, action) => {
  switch (action.type) {
    case UPDATE_TIME.UPDATE_TIME:
      return {
        ...state,
        dateRange: updateTime(action.payload),
      };
    case UPDATE_TIME.UPDATE_BATCH_TIME:
      return {
        ...state,
        dateRange: action.payload,
      };
    case 'updateIgnoreOutliers':
      return {
        ...state,
        ignoreOutliers: action.payload,
      };
    case UPDATE_TIME.UPDATE_DATA_THIN:
      const { zoom, unit } = action.payload;
      return {
        ...state,
        zoom,
        unit,
      };
    default:
      throw new Error();
  }
};

const updateTime = (key) => {
  let start = '',
    end = '';
  if (Array.isArray(key)) {
    start = moment(key[0]).format(timeFormat);
    end = moment(key[1]).format(timeFormat);
  } else {
    switch (key) {
      case 'oneHour':
        start = moment().subtract(1, 'hour').format(timeFormat);
        end = moment().format(timeFormat);
        break;
      case 'fourHour':
        start = moment().subtract(4, 'hour').format(timeFormat);
        end = moment().format(timeFormat);
        break;
      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(startFormat);
        end = moment().subtract(1, 'days').format(endFormat);
        break;
    }
  }
  return [
    {
      dateFrom: start,
      dateTo: end,
    },
  ];
};

const unique = (arr) => {
  let unique = {};
  arr.forEach((item) => {
    unique[JSON.stringify(item)] = item;
  });
  arr = Object.keys(unique).map((v) => {
    return JSON.parse(v);
  });
  return arr;
};

const DefaultDatePicker = (value) => [
  {
    key: 1,
    value: moment(),
  },
  {
    key: 2,
    value: moment().subtract(1, value),
  },
];

117 118 119 120 121
const DefaultOptions = (color, contrastOption) => ({
  chart: {
    zoomType: 'x',
    backgroundColor: 'rgba(255, 255, 255, 0.5)',
  },
涂茜's avatar
涂茜 committed
122 123 124
  boost: {
    useGPUTranslations: true,
  },
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 151 152 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
  colors: color,
  title: null,
  credits: false,
  rangeSelector: {
    enabled: false,
  },
  xAxis: [
    {
      lineWidth: 0,
      crosshair: true,
      type: 'datetime',
      gridLineDashStyle: 'dash',
      gridLineWidth: 1,
      dateTimeLabelFormats: {
        second: '%H:%M:%S',
        minute: '%H:%M',
        hour: '%H:%M',
        day: '%d',
        week: '%d',
        month: '%d',
        year: '%Y',
      },
    },
  ],
  yAxis: [],
  tooltip: {
    shared: true,
    split: false,
    valueDecimals: 3,
    formatter: function () {
      let html = `<b>${Highcharts.dateFormat(
        contrastOption === 'day' ? '%H:%M' : '%d %H:%M',
        this.x,
      )}</b><br/>`;
      this.points.forEach((item) => {
        html += `<span style={{color: ${item.series.color}}}>${item.series.name}</span>:
                <b>${
                  item.point.y.toFixed(
                    item.series.userOptions.decimalPoint ? item.series.userOptions.decimalPoint : 2,
                  ) * 1
                }${item.series.userOptions.tooltip.valueSuffix}</b>
                <br/>`;
      });
      return html;
    },
  },
  plotOptions: {
    series: {
      showInNavigator: true,
      connectNulls: false,
      zoneAxis: 'x',
    },
  },
  legend: {
    enabled: true,
    verticalAlign: 'top',
  },
  series: [],
  responsive: {
    rules: [
      {
        condition: {
          maxWidth: 800,
          minHeight: 500,
        },
      },
    ],
  },
});

涂茜's avatar
涂茜 committed
195 196 197 198 199 200 201
let chartWidth = 0; // chart width
let chartHeight = 0; // chart height

const HistoryInfo = (props) => {
  const { getPrefixCls } = useContext(ConfigProvider.ConfigContext);
  const prefixCls = getPrefixCls('history-info');

202 203 204 205 206 207 208 209 210
  const {
    title,
    tableProps,
    historyInfoService,
    historyInfoParams,
    dictionaryService,
    dictionaryParams,
    defaultChecked,
  } = props;
涂茜's avatar
涂茜 committed
211

涂茜's avatar
涂茜 committed
212
  const [loading, setLoading] = useState(false);
涂茜's avatar
涂茜 committed
213 214 215 216 217 218 219 220 221
  const [activeTabKey, setActiveTabKey] = useState('curve');
  const [timeValue, setTimeValue] = useState('customer');
  const [contrastOption, setContrastOption] = useState('day');
  const [customerChecked, setCustomerChecked] = useState(defaultChecked || 'oneHour');
  const [customerTime, setCustomerTime] = useState(null);
  const [datePickerArr, setDatePickerArr] = useState(DefaultDatePicker('day'));
  const [checkboxData, setCheckboxData] = useState(CheckboxData);
  const [dataThinKey, setDataThinKey] = useState(timeIntervalList[0].key);
  const [options, setOptions] = useState({});
222
  const [colors, setColors] = useState(defaultColors);
涂茜's avatar
涂茜 committed
223
  const [tableData, setTableData] = useState([]);
涂茜's avatar
涂茜 committed
224
  const [pageSize, setPageSize] = useState(20);
涂茜's avatar
涂茜 committed
225 226 227 228 229 230 231 232 233
  const [series, setSeries] = useState([]);
  const [columns, setColumns] = useState([
    {
      title: '采集时间',
      dataIndex: 'time',
      key: 'time',
      width: 160,
      fixed: 'left',
      ellipsis: true,
涂茜's avatar
涂茜 committed
234
      align: 'center',
涂茜's avatar
涂茜 committed
235 236 237 238 239 240 241 242 243 244 245
    },
  ]);

  const [state, dispatch] = useReducer(reducer, initialState);

  const container = useRef(null);

  // 处理图表 series
  const handleSeries = (v) => {
    const resData = v;
    const seriesData = [];
涂茜's avatar
涂茜 committed
246
    const ignoreOutliers = checkboxData.find((item) => item.key === 'ignoreOutliers').checked;
涂茜's avatar
涂茜 committed
247 248
    resData.forEach((item) => {
      const data = [];
涂茜's avatar
涂茜 committed
249 250
      const dataModel = ignoreOutliers ? item.dataModelAbnormal : item.dataModel;
      if (dataModel.length) {
涂茜's avatar
涂茜 committed
251 252
        if (timeValue === 'contrast') {
          // 同期对比
涂茜's avatar
涂茜 committed
253
          dataModel.forEach((child) => {
涂茜's avatar
涂茜 committed
254 255 256 257 258 259
            const formatTime = moment(child.pt).format(
              contrastOption === 'day' ? '2020-01-01 HH:mm:00' : '2020-01-DD HH:mm:00',
            );
            data.push([moment(formatTime).valueOf(), child.pv]);
          });
        } else {
涂茜's avatar
涂茜 committed
260
          dataModel.forEach((child) => {
涂茜's avatar
涂茜 committed
261 262 263 264
            data.push([moment(child.pt).valueOf(), child.pv]);
          });
        }
      }
涂茜's avatar
涂茜 committed
265 266 267 268 269 270 271
      const obj = {
        name: item.equipmentName + '-' + item.sensorName,
        sensorName: item.sensorName,
        decimalPoint: item.decimalPoint,
        unit: item.unit,
        data: data,
      };
涂茜's avatar
涂茜 committed
272
      if (timeValue === 'contrast' && dataModel[0]) {
涂茜's avatar
涂茜 committed
273
        const time = dataModel[0].pt.slice(0, contrastOption === 'day' ? 10 : 7).replace(/-/g, '');
涂茜's avatar
涂茜 committed
274 275 276 277 278 279 280 281 282 283
        obj.name = obj.name + '-' + time;
      }
      seriesData.push(obj);
    });
    setSeries(seriesData);
  };

  // 处理表格的数据
  const handleTableData = (resData) => {
    let timeData = [];
涂茜's avatar
涂茜 committed
284
    const ignoreOutliers = checkboxData.find((item) => item.key === 'ignoreOutliers').checked;
涂茜's avatar
涂茜 committed
285 286 287 288 289 290 291 292 293 294 295 296
    const timeSort = (dataArray) => {
      // 处理时间排序
      return dataArray.sort((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);
      });
    };
297 298 299 300
    let format = timeFormat;
    if (timeValue === 'contrast') {
      format = contrastOption === 'day' ? '2020-01-01 HH:mm:00' : '2020-01-DD HH:mm:00';
    }
涂茜's avatar
涂茜 committed
301 302
    // 处理采集时间
    resData.forEach((item) => {
涂茜's avatar
涂茜 committed
303 304
      const dataModel = ignoreOutliers ? item.dataModelAbnormal : item.dataModel;
      dataModel.forEach((data) => {
305
        const formatTime = moment(data.pt).format(format);
涂茜's avatar
涂茜 committed
306 307
        if (!timeData.includes(formatTime)) {
          timeData.push(formatTime);
涂茜's avatar
涂茜 committed
308 309 310 311 312 313
        }
      });
    });
    timeData = timeSort(timeData);
    // 处理表头数据
    const columnsData = resData.map((item, index) => {
涂茜's avatar
涂茜 committed
314
      let obj = {
涂茜's avatar
涂茜 committed
315 316 317 318
        title: `${item.equipmentName}-${item.sensorName}${item.unit ? `(${item.unit})` : ''}`,
        dataIndex: `value${index + 1}`,
        key: `value${index + 1}`,
        ellipsis: true,
涂茜's avatar
涂茜 committed
319
        align: 'center',
涂茜's avatar
涂茜 committed
320
      };
涂茜's avatar
涂茜 committed
321 322 323 324 325 326 327
      if (timeValue === 'contrast' && item.dataModel[0]) {
        const time = item.dataModel[0].pt
          .slice(0, contrastOption === 'day' ? 10 : 7)
          .replace(/-/g, '');
        obj.title = `${item.equipmentName}-${item.sensorName}-${time}`;
      }
      return obj;
涂茜's avatar
涂茜 committed
328 329 330 331 332 333 334 335 336 337 338 339
    });
    // 处理表格数据
    const tableData = timeData.map((item, index) => {
      let time = item;
      if (timeValue === 'contrast') {
        time = time.slice(contrastOption === 'day' ? 11 : 8, 16);
      }
      return { key: index, time: time };
    });
    // 处理表格数据
    tableData.forEach((item, i) => {
      resData.forEach((child, index) => {
涂茜's avatar
涂茜 committed
340 341 342
        item[`value${index + 1}`] = '--';
        const dataModel = ignoreOutliers ? child.dataModelAbnormal : child.dataModel;
        dataModel.forEach((value, j) => {
343
          const formatTime = moment(value.pt).format(format);
涂茜's avatar
涂茜 committed
344 345 346
          if (timeData[i] === formatTime) {
            item[`value${index + 1}`] = value.pv === null ? '--' : value.pv;
          }
涂茜's avatar
涂茜 committed
347 348 349 350 351 352 353 354 355 356 357 358 359
        });
      });
    });
    setTableData(tableData);
    setColumns([columns[0], ...columnsData]);
  };

  // 处理接口服务参数的变化
  const onChangeParams = (value = []) => {
    const { dateRange, ignoreOutliers, zoom, unit } = value;
    const requestArr = [];
    dateRange.forEach((item) => {
      const param = {
涂茜's avatar
涂茜 committed
360 361
        ...historyInfoParams,
        stream: historyInfoParams.stream.map((child) => ({
涂茜's avatar
涂茜 committed
362 363 364 365 366 367 368 369 370 371
          ...child,
          dateFrom: item.dateFrom,
          dateTo: item.dateTo,
        })),
        ignoreOutliers,
        zoom,
        unit,
      };
      requestArr.push(historyInfoService(param));
    });
涂茜's avatar
涂茜 committed
372
    setLoading(true);
涂茜's avatar
涂茜 committed
373 374 375 376 377 378 379 380
    Promise.all(requestArr).then((values) => {
      if (values.length) {
        let data = [];
        values.forEach((res) => {
          if (res.code === 0 && res.data.length) {
            data = data.concat(res.data);
          }
        });
涂茜's avatar
涂茜 committed
381
        setLoading(false);
涂茜's avatar
涂茜 committed
382 383 384 385 386 387
        handleTableData(data);
        handleSeries(data);
      }
    });
  };

388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
  // 获取数据字典配置的曲线颜色
  const getDictionaryList = () => {
    dictionaryService(dictionaryParams).then((res) => {
      if (res.code === 0 && res.data.length) {
        const colorsData = res.data;
        colorsData.sort((a, b) => a.nodeName.localeCompare(b.nodeName));
        const color = colorsData.map((item) => item.nodeValue);
        setColors(color);
      }
    });
  };

  useEffect(() => {
    dictionaryService && getDictionaryList();
  }, []);

涂茜's avatar
涂茜 committed
404 405
  useEffect(() => {
    onChangeParams(state);
涂茜's avatar
涂茜 committed
406
  }, [state, historyInfoParams]);
涂茜's avatar
涂茜 committed
407 408

  useEffect(() => {
涂茜's avatar
涂茜 committed
409
    customerChecked && dispatch({ type: UPDATE_TIME.UPDATE_TIME, payload: customerChecked });
涂茜's avatar
涂茜 committed
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
  }, [customerChecked]);

  useEffect(() => {
    setOptions({ ...handleChartOptions() });
  }, [series]);

  // 时间设置切换(自定义/同期对比)
  const onTimeSetChange = (e) => {
    setTimeValue(e.target.value);
    if (e.target.value === 'contrast') {
      // 同期对比
      onContrastChange(contrastOption);
    } else {
      // 自定义
      dispatch({ type: UPDATE_TIME.UPDATE_TIME, payload: customerChecked });
    }
  };

  const handleBatchTime = (arr, cOption) => {
    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 = unique(newArr);
    setDatePickerArr(arr);
    dispatch({ type: UPDATE_TIME.UPDATE_BATCH_TIME, payload: newArr });
  };

  // 选择(日/月)
  const onContrastChange = (value) => {
    setContrastOption(value);
    handleBatchTime([...DefaultDatePicker(value)], value);
  };

  const onCustomerRangeChange = (value) => {
涂茜's avatar
涂茜 committed
450
    setCustomerChecked(null);
涂茜's avatar
涂茜 committed
451 452 453 454 455 456
    setCustomerTime(value);
    dispatch({ type: UPDATE_TIME.UPDATE_TIME, payload: value });
  };

  const onCustomerTimeChange = (key) => {
    setCustomerChecked(key);
涂茜's avatar
涂茜 committed
457
    !!customerTime && setCustomerTime(null);
涂茜's avatar
涂茜 committed
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 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 522 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 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
  };

  const onContrastPickerChange = (date, dateString, item) => {
    let arr = [...datePickerArr];
    arr.forEach((child) => {
      if (child.key === item.key) {
        child.value = date;
      }
    });
    handleBatchTime(arr, contrastOption);
  };

  // 新增日期选择组件
  const handleAddDatePicker = () => {
    setDatePickerArr([
      ...datePickerArr,
      {
        key: datePickerArr[datePickerArr.length - 1].key + 1,
        value: '',
      },
    ]);
  };

  // 删除日期选择组件
  const handleDeleteDatePicker = (index) => {
    const arr = [...datePickerArr];
    arr.splice(index, 1);
    setDatePickerArr(arr);
    handleBatchTime(arr, contrastOption);
  };

  // 曲线设置 checkbox
  const onCheckboxChange = (e, key) => {
    let data = [...checkboxData];
    data.forEach((item) => {
      if (item.key === key) {
        item.checked = e.target.checked;
        if (key === 'dataThin') {
          if (e.target.checked) {
            timeIntervalList.forEach((child) => {
              if (child.key === dataThinKey) {
                dispatch({ type: item.type, payload: { zoom: dataThinKey, unit: child.unit } });
              }
            });
          } else {
            dispatch({ type: item.type, payload: { zoom: '', unit: '' } });
          }
        }
        if (key === 'ignoreOutliers') {
          dispatch({ type: item.type, payload: e.target.checked });
        }
        if (key === 'curveCenter') {
          setOptions({ ...handleChartOptions() });
        }
      }
    });
    setCheckboxData(data);
  };

  // 数据抽稀时间间隔
  const onTimeIntervalChange = (value, { unit }) => {
    let data = checkboxData.filter((item) => item.key === 'dataThin');
    if (data[0].checked) {
      dispatch({ type: UPDATE_TIME.UPDATE_DATA_THIN, payload: { zoom: value, unit: unit } });
    }
    setDataThinKey(value);
  };

  const renderCheckbox = (child) => (
    <Checkbox
      value={child.key}
      checked={child.checked}
      onChange={(e) => onCheckboxChange(e, child.key)}
    >
      {child.label}
    </Checkbox>
  );

  const renderOptions = (item) => {
    return (
      <>
        <div className={classNames(`${prefixCls}-time`)}>
          <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}-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}-date-wrap`)}>
                    <DatePicker
                      picker={contrastOption}
                      value={child.value}
                      onChange={(date, dateString) =>
                        onContrastPickerChange(date, dateString, child)
                      }
                    />
                    {datePickerArr.length > 2 && (
                      <div
                        className={classNames(`${prefixCls}-date-delete`)}
                        onClick={() => handleDeleteDatePicker(index)}
                      >
                        <CloseCircleFilled />
                      </div>
                    )}
                  </div>
                  {index < datePickerArr.length - 1 && (
                    <div className={classNames(`${prefixCls}-connect`)}></div>
                  )}
                </div>
              ))}
              {datePickerArr.length < 5 && <PlusCircleOutlined onClick={handleAddDatePicker} />}
            </>
          )}
        </div>
        <div className={classNames(`${prefixCls}-cover`)}>
          <div className={classNames(`${prefixCls}-label`)}>曲线设置</div>
          {checkboxData.map((child) => (
            <div key={child.key}>
              {item.key === 'curve' && renderCheckbox(child)}
              {item.key === 'table' && child.key !== 'curveCenter' && renderCheckbox(child)}
            </div>
          ))}
          <Select value={dataThinKey} style={{ width: 90 }} onChange={onTimeIntervalChange}>
            {timeIntervalList.map((child) => (
              <Option key={child.key} unit={child.unit} value={child.key}>
                {child.name}
              </Option>
            ))}
          </Select>
        </div>
      </>
    );
  };

  const getSeriesType = (sensorName) => {
    return sensorName ? (sensorName.indexOf('流量') > -1 ? 'area' : 'spline') : 'spline';
  };

  // 处理图表options
  const handleChartOptions = () => {
620
    const _series = [];
涂茜's avatar
涂茜 committed
621
    let _yAxis = [];
622
    const uniqueUnit = [];
涂茜's avatar
涂茜 committed
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 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
    series.forEach((item, index) => {
      // 处理series
      let _s = {
        name: item.name,
        type: getSeriesType(item.sensorName),
        data: item.data,
        zIndex: 1,
        tooltip: { valueSuffix: item.unit ? item.unit : '' },
        color: colors[index],
        decimalPoint: item.decimalPoint,
        navigatorOptions: {
          enabled: true,
        },
      };
      if (_s.type === 'area' || _s.type === 'areaspline') {
        _s.fillColor = {
          linearGradient: {
            x1: 0,
            y1: 0,
            x2: 0,
            y2: 1,
          },
          stops: [
            [0, Highcharts.Color(_s.color).setOpacity(0.1).get('rgba')],
            [1, '#fff'],
          ],
        };
        _s.threshold = 0;
      }

      // 处理yAxis
      if (!uniqueUnit.includes(item.unit)) {
        uniqueUnit.push(item.unit);
        let _length = uniqueUnit.length - 1;
        let _y = {
          title: {
            text: item.unit,
            align: 'high',
            offset: 0,
            rotation: 0,
            y: -25,
            x: 0,
          },
          gridLineWidth: 1,
          gridLineDashStyle: 'dash',
          lineWidth: 1,
          tickAmount: 10,
          crosshair: true,
          floor: 0,
          num: _length,
          opposite: _length % 2 === 0,
          offset: Math.floor(_length / 2) * 40,
          style: {
            color: '',
          },
          labels: {
            style: {
              color: '',
            },
            x: -2,
          },
        };
        _yAxis.push(_y);
      }

      // 处理series
      _s.yAxis = uniqueUnit.findIndex((child) => child === item.unit);

      _series.push(_s);
    });

    Highcharts.setOptions({
      global: { timezoneOffset: -8 * 60 },
    });

698
    let options = { ...DefaultOptions(colors, contrastOption) };
涂茜's avatar
涂茜 committed
699 700 701 702 703 704 705 706 707

    if (CheckboxData[0].checked) {
      _yAxis = setYaxisMin(_yAxis, _series);
    } else {
      _yAxis = _yAxis.map((item) => ({ ...item, max: null, min: null }));
    }

    if (_yAxis.length > 0) {
      options = {
708
        ...DefaultOptions(colors, contrastOption),
涂茜's avatar
涂茜 committed
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 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
        yAxis: _yAxis,
        series: _series,
      };
    }

    if (container.current) {
      if (container.current.offsetWidth !== 0) {
        chartWidth = container.current.offsetWidth;
        chartHeight = container.current.offsetHeight;
      }
      Highcharts.setOptions({
        // 处理 chart 高度坍塌
        chart: {
          width: container.current.offsetWidth === 0 ? chartWidth : container.current.offsetWidth,
          height:
            container.current.offsetHeight === 0 ? chartHeight : container.current.offsetHeight,
        },
      });
    }

    return options;
  };

  const setYaxisMin = (y, data) => {
    let result = y.concat();

    data.forEach((val) => {
      let min = 999999999;
      let showMin = 999999999;
      let max = -999999999;
      let showMax = -999999999;
      val.data.forEach((item) => {
        if (item[1]) {
          min = Math.min(min, item[1]);
          showMin = Math.min(min, item[1]);
          max = Math.max(max, item[1]);
          showMax = Math.max(max, item[1]);
        }
      });
      let k = 0;
      let same = false;
      for (let i = 0; i < val.data.length; i++) {
        // 判断是否全为0
        if (val.data[i][1] !== 0) {
          k = 1;
        }
        // 判断是否全相等
        if (i >= 1 && val.data[i][1] !== val.data[i - 1][1]) {
          same = true;
        }
      }

      if (k === 0) {
        result[val.yAxis].min = result[val.yAxis].min
          ? Math.min(result[val.yAxis].min, -0.2)
          : -0.2;
        result[val.yAxis].max = result[val.yAxis].max ? Math.max(result[val.yAxis].max, 0.2) : 0.2;
      } else if (!same) {
        min = val.data[0][1] > 0 ? val.data[0][1] * 0.5 : val.data[0][1] * 1.5;
        max = val.data[0][1] > 0 ? val.data[0][1] * 1.5 : val.data[0][1] * 0.5;
        result[val.yAxis].min = result[val.yAxis].min
          ? Math.min(result[val.yAxis].min, showMin)
          : min;
        result[val.yAxis].max = result[val.yAxis].max ? Math.max(result[val.yAxis].max, max) : max;
      } else {
        result[val.yAxis].min = result[val.yAxis].min
          ? Math.min(result[val.yAxis].min, min)
          : showMin;
        result[val.yAxis].max = result[val.yAxis].max
          ? Math.max(result[val.yAxis].max, max)
          : showMax;
      }
    });

    return result;
  };

涂茜's avatar
涂茜 committed
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
  const exportExcelBtn = () => {
    let data = JSON.parse(JSON.stringify(tableData));
    const keys = Object.keys(data[0]).filter((item) => item !== 'key');
    const sheetData = data.map((item) => {
      delete item.key;
      return item;
    });
    ExportExcel({
      name: '历史曲线表格',
      content: [
        {
          sheetData: sheetData,
          sheetName: '历史曲线表格',
          sheetFilter: keys,
          sheetHeader: columns.map((item) => item.title),
          columnWidths: columns.map((item) => 20),
        },
      ],
    });
  };

涂茜's avatar
涂茜 committed
807 808 809 810 811 812 813
  return (
    <div className={classNames(prefixCls)}>
      <Tabs
        activeKey={activeTabKey}
        centered
        tabBarExtraContent={{
          left: <h3 className="tabs-extra-demo-button">{title}</h3>,
涂茜's avatar
涂茜 committed
814 815 816 817 818 819 820
          right:
            activeTabKey === 'table' ? (
              <Button onClick={exportExcelBtn}>
                <DownloadOutlined />
                下载
              </Button>
            ) : null,
涂茜's avatar
涂茜 committed
821 822 823 824 825 826 827
        }}
        onChange={(key) => setActiveTabKey(key)}
      >
        {TabPaneData.map((item) => (
          <TabPane tab={item.tab} key={item.key}>
            <div className={classNames(`${prefixCls}-content`)}>
              {renderOptions(item)}
涂茜's avatar
涂茜 committed
828
              <Spin spinning={loading} wrapperClassName={classNames(`${prefixCls}-spin`)}>
涂茜's avatar
涂茜 committed
829 830 831 832 833
                {!tableData.length && (
                  <div className={classNames(`${prefixCls}-empty`)}>
                    <Empty />
                  </div>
                )}
涂茜's avatar
涂茜 committed
834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
                {!!tableData.length && (
                  <div className={classNames(`${prefixCls}-wrap`)}>
                    <div className={classNames(`${prefixCls}-main`)}>
                      {item.key === 'curve' && (
                        <div className={classNames(`${prefixCls}-chart`)} ref={container}>
                          <HighchartsReact
                            immutable={true}
                            highcharts={Highcharts}
                            constructorType={'stockChart'}
                            options={options}
                            allowChartUpdate={true}
                          />
                        </div>
                      )}
                      {item.key === 'table' && (
                        <BasicTable
                          dataSource={tableData}
                          columns={columns}
                          {...tableProps}
                          pagination={{ pageSize, showQuickJumper: true, showSizeChanger: true }}
                          onChange={(value) => {
                            setPageSize(value.pageSize);
                          }}
涂茜's avatar
涂茜 committed
857
                        />
涂茜's avatar
涂茜 committed
858 859
                      )}
                    </div>
涂茜's avatar
涂茜 committed
860
                  </div>
涂茜's avatar
涂茜 committed
861 862
                )}
              </Spin>
涂茜's avatar
涂茜 committed
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 888 889 890 891 892 893
            </div>
          </TabPane>
        ))}
      </Tabs>
    </div>
  );
};

HistoryInfo.defaultProps = {
  title: '指标曲线',
  defaultChecked: 'oneHour',
  tableProps: {},
  historyInfoParams: {},
  historyInfoService: () => {},
};

HistoryInfo.propTypes = {
  title: PropTypes.string,
  defaultChecked: PropTypes.string,
  tableProps: PropTypes.object,
  historyInfoParams: PropTypes.object,
  historyInfoService: PropTypes.func,
};

export default HistoryInfo;

const startFormat = 'YYYY-MM-DD 00:00:00';
const endFormat = 'YYYY-MM-DD 23:59:59';

const timeFormat = 'YYYY-MM-DD HH:mm:ss';

894
const defaultColors = [
涂茜's avatar
涂茜 committed
895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
  '#1884EC',
  '#90CE53',
  '#86E0C7',
  '#68cbd1',
  '#bb98d1',
  '#588c66',
  '#b0859e',
  '#647fac',
  '#7c6894',
  '#9c8273',
  '#838b61',
  '#437db0',
  '#9b97c4',
  '#bda589',
  '#89bd8e',
  '#cbcc75',
];

const initialState = {
  dateRange: [],
  ignoreOutliers: false,
  isVertical: false,
  zoom: '',
  unit: '',
};

const TabPaneData = [
  {
    key: 'curve',
    tab: '曲线',
  },
  {
    key: 'table',
    tab: '表格',
  },
];

const CheckboxData = [
  {
    key: 'curveCenter',
    label: '曲线居中',
    checked: false,
  },
  {
    key: 'ignoreOutliers',
    label: '过滤异常值',
    type: 'updateIgnoreOutliers',
    checked: false,
  },
  {
    key: 'dataThin',
    label: '数据抽稀',
    type: 'updateDataThin',
    checked: false,
  },
];

const timeList = [
  {
    key: 'oneHour',
    name: '近1小时',
  },
  {
    key: 'fourHour',
    name: '近4小时',
  },
  {
    key: 'twelveHours',
    name: '近12小时',
  },
  {
    key: 'roundClock',
    name: '近24小时',
  },
  {
    key: 'yesterday',
    name: '昨天',
  },
];

const timeIntervalList = [
  {
    key: '5',
    unit: 'min',
    name: '5分钟',
  },
  {
    key: '10',
    unit: 'min',
    name: '10分钟',
  },
  {
    key: '30',
    unit: 'min',
    name: '30分钟',
  },
  {
    key: '1',
    unit: 'h',
    name: '1小时',
  },
  {
    key: '2',
    unit: 'h',
    name: '2小时',
  },
  {
    key: '6',
    unit: 'h',
    name: '6小时',
  },
  {
    key: '12',
    unit: 'h',
    name: '12小时',
  },
];