index.js 9.22 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
import React, { useContext, useEffect, useRef, useState } from 'react';
import { ConfigProvider, Radio, Slider, InputNumber, Input } from 'antd';
import classNames from 'classnames';
import moment from 'moment';
import { BasicChart } from '@wisdom-components/basicchart';
import { getHistoryInfo, getDateList } from '../../apis';
import { timeArr } from '../utils';
import './index.less';

const HistoryTrend = (props) => {
  const { getPrefixCls } = useContext(ConfigProvider.ConfigContext);
  const prefixCls = getPrefixCls('history-trend');
  const { deviceCode, sensors, deviceType, changeSpin } = props;
  const chartRef = useRef(null);
15 16 17 18
  const infoRef = useRef({
    decimalPoint: 2,
    unit: '',
  })
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

  const [sensitive, setSensitive] = useState(10); // 敏感度
  const [timeType, setTimeType] = useState('近7日'); // 时间
  const [timeData, setTimeData] = useState([]); // 时间
  const [sensorData, setSensorData] = useState([]); // 所有数据
  const [ruleData, setRuleData] = useState([]); // 预测数据
  const [options, setOptions] = useState({});

  // 日期处理
  const dateMethod = async () => {
    const arr = new Array(7).fill('list');
    let data = arr.map((item, index) => {
      return moment()
        .subtract(index + 1, 'day')
        .format('YYYY-MM-DD');
    });
    switch (timeType) {
      case '7工作日':
        const dateList1 = await getDateList({
          n: 7,
          isHoliday: false,
          date: moment().subtract(1, 'day').format('YYYY-MM-DD'),
        });
        setTimeData(dateList1?.data || []);
        break;
      case '7节假日':
        const dateList2 = await getDateList({
          n: 7,
          isHoliday: false,
          date: moment().subtract(1, 'day').format('YYYY-MM-DD'),
        });
        setTimeData(dateList2?.data || []);
        break;
      default:
        setTimeData([data.join(',')]);
        break;
    }
  };

  // 获取历史数据
59
  const getSensorsData = () => {
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
    changeSpin(true);
    if (!timeData.length) return setOptions({});
    const reqs = [];
    timeData.forEach((item) => {
      const list = item.split(',');
      const params = {
        isDilute: true,
        zoom: '5',
        unit: 'min',
        dateFrom: moment(list[list.length - 1]).format('YYYY-MM-DD 00:00:00'),
        dateTo: moment(list[0]).format('YYYY-MM-DD 23:59:59'),
        acrossTables: [{ deviceCode: deviceCode, sensors: sensors, deviceType: deviceType }],
        isBoxPlots: true,
        ignoreOutliers: true,
      };
      const req = getHistoryInfo(params);
      reqs.push(req);
    });
    Promise.all(reqs).then((results) => {
      changeSpin(false);
      let historyData = [];
      results.forEach((result) => {
        const _historyData = result?.data?.[0]?.dataModel || [];
83 84 85 86 87
        const info = result?.data?.[0] || {};
        infoRef.current = {
          decimalPoint: info?.decimalPoint || 2,
          unit: info?.unit || ''
        }
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 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 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
        historyData = historyData.concat([..._historyData]);
      });
      console.log(historyData);
      setSensorData(() => {
        dataMonthod(historyData);
        return historyData;
      });
    });
  };

  // 数据处理
  const dataMonthod = (data) => {
    let timeDatas = [];
    const chartData = [];
    const strTime = moment().format('YYYY-MM-DD');
    timeData.forEach((item) => {
      const list = item.split(',');
      timeDatas = timeDatas.concat([...list]);
    });
    timeDatas.forEach((item) => {
      const seriesData = data.filter((list) => {
        return list.pt.indexOf(item) > -1;
      });
      const series = {
        type: 'line',
        name: item,
        smooth: true,
        areaStyle: {},
        data: seriesData.map((list) => {
          const pv = new Date(moment(list['pt']).format(strTime + ' HH:mm:ss')).getTime();
          return [pv, list['pv']];
        }),
      };
      chartData.push(series);
    });
    renderChart(chartData);
  };

  // 渲染图表
  const renderChart = (chartData) => {
    const option = {
      xAxis: {
        type: 'time',
        axisTick: {
          alignWithLabel: true,
        },
        axisLabel: {
          formatter: (value) => {
            return moment(value).format('HH:mm:ss');
          },
        },
        boundaryGap: false,
      },
      yAxis: {
        type: 'value',
        name: 'm',
        position: 'left',
        alignTicks: true,
        axisLabel: {
          formatter: '{value}',
        },
      },
      tooltip: {
        formatter: function (params) {
          const title = moment(params[0].axisValue).format('HH:mm:ss');
          let html = `<div style="border-bottom: 1px solid #F0F0F0;color: #808080;margin-bottom: 5px;padding-bottom: 5px;">${title}</div><div>`;
          params.forEach((item) => {
            html += `<span style="display: inline-block;margin: 0 7px 2px 0;border-radius: 5px;width: 5px;height: 5px;background: ${item.color};"></span>${item.seriesName}:<span style="color: ${item.color}">${item.data[1]}</span><br />`;
          });
          return html;
        },
      },
      series: chartData,
    };
    setOptions(option);
  };

  // 限值处理
  const limitMethod = () => {
    const pvArr = sensorData.map((item) => {
      return item.pv;
    });
    let max = Math.max(...pvArr);
    let min = Math.min(...pvArr);
    console.log(max, min);
173
    const decimalPoint = infoRef.current.decimalPoint || 2;
174
    const data = [
175 176 177 178
      (min * (1 - sensitive / 100)).toFixed(decimalPoint) * 1,
      (min * (1 + sensitive / 100)).toFixed(decimalPoint) * 1,
      (max * (1 - sensitive / 100)).toFixed(decimalPoint) * 1,
      (max * (1 + sensitive / 100)).toFixed(decimalPoint) * 1,
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 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 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 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 282 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
    ];
    const color = ['#CB2D2D', '#0087F7'];
    const name = ['低低限', '低限', '高限', '高高限'];
    const mark = name.map((item, index) => {
      return {
        name: item,
        yAxis: data[index],
        lineStyle: {
          color: color[index % 2],
          type: 'dashed',
        },
        label: {
          color: color[index % 2],
        },
      };
    });
    let option = { ...options };
    option.series[0].markLine = {
      data: mark,
    };
    setOptions(option);
    setRuleData(data);
    props.backData(data);
  };

  useEffect(() => {
    getSensorsData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [timeData]);

  useEffect(() => {
    dateMethod();
  }, [timeType]);

  useEffect(() => {
    if (options?.series?.length && sensorData.length) limitMethod();
  }, [sensitive, sensorData]);

  return (
    <div className={classNames(`${prefixCls}`)}>
      <div className={classNames(`${prefixCls}-header`)}>
        <div className={classNames(`${prefixCls}-list`)}>
          <span>参考依据:</span>
          <Radio.Group
            options={timeArr}
            optionType={'button'}
            value={timeType}
            onChange={(e) => {
              setTimeType(e.target.value);
            }}
          />
        </div>
        <div className={classNames(`${prefixCls}-list`)}>
          <span>建议取值:</span>
          <div className={classNames(`${prefixCls}-read`)}>
            <div className={classNames(`${prefixCls}-value`)}>
              <Input
                style={{
                  width: '150px',
                }}
                value={ruleData[0]}
                addonBefore="低低限"
                disabled
              />
            </div>
            <div className={classNames(`${prefixCls}-value`)}>
              <Input
                style={{
                  width: '150px',
                }}
                value={ruleData[1]}
                addonBefore="低限"
                disabled
              />
            </div>
            <div className={classNames(`${prefixCls}-value`)}>
              <Input
                style={{
                  width: '150px',
                }}
                value={ruleData[2]}
                addonBefore="高限"
                disabled
              />
            </div>
            <div className={classNames(`${prefixCls}-value`)}>
              <Input
                style={{
                  width: '150px',
                }}
                value={ruleData[3]}
                addonBefore="高高限"
                disabled
              />
            </div>
          </div>
          <div className={classNames(`${prefixCls}-range`)}>
            允许浮动范围:
            <Slider
              min={0}
              max={100}
              style={{ width: '100px' }}
              onChange={(value) => {
                setSensitive(value);
              }}
              value={typeof sensitive === 'number' ? sensitive : 0}
            />
            <InputNumber
              min={1}
              max={100}
              style={{
                margin: '0 16px',
                width: '100px',
              }}
              formatter={(value) => `${value}%`}
              value={sensitive}
              onChange={(value) => {
                setSensitive(value);
              }}
            />
          </div>
        </div>
      </div>
      <div className={classNames(`${prefixCls}-chart`)}>
        <BasicChart
          ref={chartRef}
          option={options}
          notMerge
          style={{ width: '100%', height: '100%' }}
        />
      </div>
    </div>
  );
};

export default HistoryTrend;