index.js 14.7 KB
Newer Older
1
import React, { useContext, useEffect, useRef, useState } from 'react';
2
import { ConfigProvider, Modal, Radio, Slider, InputNumber, Input, Button, Checkbox } from 'antd';
3 4 5 6 7 8
import classNames from 'classnames';
import moment from 'moment';
import { BasicChart } from '@wisdom-components/basicchart';
import { getHistoryInfo } from '../../apis';
import { std } from 'mathjs';
import skmeans from 'skmeans';
9
import { outlierArr, timeArr, chartArr, average, markArr, median } from '../utils';
10 11 12 13 14 15 16 17 18 19 20 21 22
import './index.less';

const IntellectDraw = (props) => {
  const { getPrefixCls } = useContext(ConfigProvider.ConfigContext);
  const prefixCls = getPrefixCls('intellect-draw');
  const { deviceCode, sensors, deviceType, changeSpin } = props;
  const [open, setOpen] = useState(false);
  const [outlier, setOutlier] = useState(3); // 过滤异常

  const [sensorData, setSensorData] = useState([]); // 所有数据
  const [chartData, setChartData] = useState([]); // 图表数据
  const [timeCycle, setTimeCycle] = useState(60);
  const [timeDan, setTimeDan] = useState(1);
23
  const [foldData, setFoldData] = useState([]);
24
  const [options, setOptions] = useState({});
25
  const [selectCheck, setSelectCheck] = useState([]);
26 27 28 29 30 31 32 33

  const chartRef = useRef(null);

  // 获取历史数据
  const getSensorsData = async () => {
    changeSpin(true);
    const params = {
      isDilute: true,
34 35
      zoom: '5',
      unit: 'min',
36 37 38 39
      dateFrom: moment().subtract(8, 'day').format('YYYY-MM-DD 00:00:00'),
      dateTo: moment().subtract(1, 'day').format('YYYY-MM-DD 23:59:59'),
      acrossTables: [{ deviceCode: deviceCode, sensors: sensors, deviceType: deviceType }],
      isBoxPlots: true,
40
      ignoreOutliers: true,
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
    };
    const results = await getHistoryInfo(params);
    changeSpin(false);
    const historyData = results?.data?.[0] || {};

    setSensorData(() => {
      return historyData;
    });
  };

  // 图表数据处理
  const chartDataHandle = (data) => {
    const times = moment().subtract(1, 'day').format('YYYY-MM-DD');
    const chart = data.map((item) => {
      return {
        ...item,
        time: moment(item.pt).format(times + ' HH:mm:ss'),
      };
    });
    return chart;
  };

  // 聚集方法
64
  const clusteredMothod = (clustered, num) => {
65
    // console.log(clustered);
66 67 68 69 70 71 72
    let foldLine = [];
    const arr = [];
    const times = moment().subtract(1, 'day').format('YYYY-MM-DD');
    const data = clustered.map((item) => {
      return item[1];
    });
    const medianVal = median([...data]);
73
    // console.log(data, medianVal);
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
    if (timeDan === 1) {
      return [
        [new Date(moment(times + ' 00:00:00')).getTime(), medianVal],
        [new Date(moment(times + ' 23:59:59')).getTime(), medianVal],
      ];
    }
    data.forEach((item, index) => {
      if (
        index === 0 ||
        (medianVal < item && medianVal > data[index - 1] && index > 0) ||
        (medianVal > item && medianVal < data[index - 1] && index > 0)
      ) {
        arr.push([
          {
            x: clustered[index][0],
            y: clustered[index][1],
            l: item,
          },
        ]);
      } else {
        arr[arr.length - 1].push({
          x: clustered[index][0],
          y: clustered[index][1],
          l: item,
        });
      }
    });
101
    // console.log(arr);
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
    arr.forEach((list, index) => {
      const _list = list.map((item) => {
        return item['y'];
      });
      const _medianVal = median([..._list]);
      if (index === 0) {
        foldLine = foldLine.concat([
          [new Date(moment(times + ' 00:00:00')).getTime(), _medianVal],
          [list[list.length - 1].x, _medianVal],
        ]);
      } else if (index === arr.length - 1) {
        foldLine = foldLine.concat([
          [arr[index - 1].at(-1).x, _medianVal],
          [new Date(moment(times + ' 23:59:59')).getTime(), _medianVal],
        ]);
      } else {
        foldLine = foldLine.concat([
          [arr[index - 1].at(-1).x, _medianVal],
          [list[list.length - 1].x, _medianVal],
        ]);
      }
    });
124
    // console.log(foldLine, 'foldLine');
125 126 127 128 129 130
    if (arr.length === timeDan || arr.length === num) {
      return foldLine;
    } else {
      return clusteredMothod(foldLine, arr.length);
    }
  };
131 132

  // 渲染图表
133
  const renderChart = (_chartData, _clustered) => {
134 135 136 137 138 139 140 141
    const chartDatas = _chartData.map((item) => {
      return [new Date(item.time).getTime(), item.pv];
    });
    const clustered = skmeans(chartDatas, 24);
    const { centroids = [] } = clustered;
    const _centroids = centroids.sort((a, b) => {
      return a[0] - b[0];
    });
142
    // console.log(_centroids);
143
    const foldLine = clusteredMothod(_centroids, 0);
144
    // console.log(foldLine);
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
    const option = {
      xAxis: {
        type: 'time',
        axisTick: {
          alignWithLabel: true,
        },
        boundaryGap: false,
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dashed',
          },
        },
      },
      yAxis: {
        type: 'value',
161
        name: sensorData?.unit || '',
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
        position: 'left',
        alignTicks: true,
        axisLine: {
          show: true,
        },
        axisLabel: {
          formatter: '{value}',
        },
      },
      series: [
        {
          type: 'scatter',
          name: sensors,
          sampling: 'average',
          large: true,
          symbolSize: 5,
          data: _chartData.map((item) => {
            return [new Date(item.time).getTime(), item.pv];
          }),
        },
        {
          type: 'line',
184
          name: '趋势',
185 186 187 188 189 190
          sampling: 'average',
          large: true,
          data: _centroids.map((item) => {
            return [Math.floor(item[0]), item[1]];
          }),
        },
191 192 193 194 195 196 197
        {
          type: 'line',
          name: '限值',
          data: foldLine.map((item) => {
            return [Math.floor(item[0]), item[1]];
          }),
        },
198 199 200
      ],
    };
    setOptions(option);
201 202 203 204 205 206 207 208 209 210 211 212 213
    setFoldData(foldDataMethod(foldLine));
  };

  // 限值数据处理
  const foldDataMethod = (data) => {
    let _data = [];
    data.forEach((item, index) => {
      if (index % 2 === 0) {
        _data = _data.concat([[item]]);
      } else {
        _data[Math.floor(index / 2)].push([...item]);
      }
    });
214
    // console.log(_data);
215 216 217 218 219 220 221 222 223 224 225 226

    return _data.map((list) => {
      return {
        start: moment(list[0][0]).format('HH:mm'),
        end: moment(list[1][0]).format('HH:mm'),
        value: list[0][1],
        wave: 10,
      };
    });
  };

  const onCheckChange = (checkedValues) => {
227
    setSelectCheck(checkedValues);
228 229 230 231
  };

  const proposeRender = () => {
    return (
232 233 234
      <div className={classNames(`${prefixCls}-propose-box`)}>
        <Checkbox.Group onChange={onCheckChange}>
          {foldData.map((list, index) => {
235 236 237 238 239
            const decimalPoint = sensorData?.decimalPoint || 2;
            const lower1 = (list.value * (1 - list.wave / 100) * (1 - list.wave / 100)).toFixed(decimalPoint) * 1;
            const lower2 = (list.value * (1 - list.wave / 100)).toFixed(decimalPoint) * 1;
            const high1 = (list.value * (1 + list.wave / 100)).toFixed(decimalPoint) * 1;
            const high2 = (list.value * (1 + list.wave / 100) * (1 + list.wave / 100)).toFixed(decimalPoint) * 1;
240 241 242 243 244 245 246 247 248 249 250 251 252 253
            return (
              <div className={classNames(`${prefixCls}-propose-list`)} key={index}>
                <div className={classNames(`${prefixCls}-propose-select`)}>
                  <Checkbox value={index}>
                    {list.start}-{list.end}
                  </Checkbox>
                </div>
                <div className={classNames(`${prefixCls}-propose-value`)}>
                  <div className={classNames(`${prefixCls}-value-list`)}>
                    <Input
                      style={{
                        width: '150px',
                      }}
                      addonBefore="低低限"
254
                      value={lower1}
255 256 257 258 259 260 261 262 263
                      disabled
                    />
                  </div>
                  <div className={classNames(`${prefixCls}-value-list`)}>
                    <Input
                      style={{
                        width: '150px',
                      }}
                      addonBefore="低限"
264
                      value={lower2}
265 266 267 268 269 270 271 272 273
                      disabled
                    />
                  </div>
                  <div className={classNames(`${prefixCls}-value-list`)}>
                    <Input
                      style={{
                        width: '150px',
                      }}
                      addonBefore="高限"
274
                      value={high1}
275 276 277 278 279 280 281 282 283
                      disabled
                    />
                  </div>
                  <div className={classNames(`${prefixCls}-value-list`)}>
                    <Input
                      style={{
                        width: '150px',
                      }}
                      addonBefore="高高限"
284
                      value={high2}
285 286 287 288 289 290 291 292 293 294 295
                      disabled
                    />
                  </div>
                </div>
                <div className={classNames(`${prefixCls}-propose-range`)}>
                  <span className={classNames(`${prefixCls}-label`)}>允许浮动范围:</span>
                  <Slider
                    min={0}
                    max={100}
                    style={{ width: '100px' }}
                    onChange={(value) => {
296 297 298
                      const _foldData = structuredClone(foldData);
                      _foldData[index].wave = value;
                      setFoldData(_foldData);
299
                    }}
300
                    value={typeof list.wave === 'number' ? list.wave : 0}
301 302 303 304 305 306 307 308 309
                  />
                  <InputNumber
                    min={1}
                    max={100}
                    style={{
                      margin: '0 16px',
                      width: '100px',
                    }}
                    formatter={(value) => `${value}%`}
310
                    value={list.wave}
311
                    onChange={(value) => {
312 313 314
                      const _foldData = structuredClone(foldData);
                      _foldData[index].wave = value;
                      setFoldData(_foldData);
315 316 317 318 319 320 321 322
                    }}
                  />
                </div>
              </div>
            );
          })}
        </Checkbox.Group>
      </div>
323 324 325
    );
  };

326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
  useEffect(() => {
    const data = [];
    const decimalPoint = sensorData?.decimalPoint || 2;
    selectCheck.forEach((index) => {
      const value = foldData[index]?.value || 0;
      const wave = foldData[index]?.wave || 0;
      const lower1 = (value * (1 - wave / 100) * (1 - wave / 100)).toFixed(decimalPoint) * 1;
      const lower2 = (value * (1 - wave / 100)).toFixed(decimalPoint) * 1;
      const high1 = (value * (1 + wave / 100)).toFixed(decimalPoint) * 1;
      const high2 = (value * (1 + wave / 100) * (1 + wave / 100)).toFixed(decimalPoint) * 1;
      data.push({
        ...foldData[index],
        lower1,
        lower2,
        high1,
        high2,
      })
    })
    if (data.length) return props.backData([data[0].lower1, data[0].lower2, data[0].high1, data[0].high2]);
    return props.backData([]);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectCheck, foldData]);

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 374 375
  useEffect(() => {
    open && getSensorsData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open]);

  useEffect(() => {
    const { dataModel = [] } = sensorData;
    if (!dataModel.length) return setChartData([]);
    const count = Math.floor((24 * 60) / timeCycle);
    const times = moment().subtract(1, 'day').format('YYYY-MM-DD');
    const _dataModel = dataModel.map((item) => {
      return {
        ...item,
        time: moment(item.pt).format(times + ' HH:mm:ss'),
      };
    });
    const _chartData = [];
    const _clustered = [];
    for (let i = 0; i < count; i++) {
      const data = _dataModel.filter((item) => {
        const time = new Date(item.time).getTime();
        const min = new Date(moment(times + ' 00:00:00').add(i * timeCycle, 'minute')).getTime();
        const max = new Date(
          moment(times + ' 00:00:00').add((i + 1) * timeCycle, 'minute'),
        ).getTime();
        return time && time >= min && max >= time;
      });
376
      let dataArr = [];
377
      const pvArr = data.map((item) => {
378
        return item.pv || 0;
379 380 381 382 383 384 385 386 387 388
      });
      const stdVal = pvArr.length ? std(pvArr) : 0;
      const medianVal = pvArr.length ? average(pvArr) : 0;
      const range = {
        min: medianVal - outlier * stdVal,
        max: medianVal + outlier * stdVal,
      };
      data.forEach((item) => {
        if (item.pv >= range.min && item.pv <= range.max) dataArr.push(item);
      });
389
      if (!outlier) dataArr = [].concat([...data]);
390 391 392 393
      _chartData.push(...dataArr);
    }
    renderChart(_chartData, _clustered);
    // eslint-disable-next-line react-hooks/exhaustive-deps
394
  }, [sensorData, outlier, timeDan]);
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 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 450 451 452 453 454 455 456 457 458 459

  useEffect(() => {
    setOpen(props.open);
  }, [props.open]);

  return (
    <>
      <div className={classNames(`${prefixCls}`)}>
        <div className={classNames(`${prefixCls}-header`)}>
          <div className={classNames(`${prefixCls}-list`)}>
            <span className={classNames(`${prefixCls}-item`)}>
              <span className={classNames(`${prefixCls}-label`)}>异常值剔除:</span>
              <Slider
                marks={markArr}
                step={null}
                style={{
                  width: '200px',
                }}
                defaultValue={1}
                onChange={(value) => {
                  setOutlier(outlierArr[value]?.value || 0);
                }}
                min={0}
                max={3}
                tooltip={{
                  formatter: (value) => {
                    return markArr[value];
                  },
                }}
              />
            </span>
            <span className={classNames(`${prefixCls}-item`)}>
              <span className={classNames(`${prefixCls}-label`)}>限值时段个数:</span>
              <InputNumber
                min={1}
                max={10}
                style={{
                  width: '100px',
                }}
                value={timeDan}
                onChange={(value) => {
                  setTimeDan(value);
                }}
              />
            </span>
          </div>
          <div className={classNames(`${prefixCls}-propose`)}>
            <span className={classNames(`${prefixCls}-label`)}>建议限值:</span>
            {proposeRender()}
          </div>
        </div>
        <div className={classNames(`${prefixCls}-chart`)}>
          <BasicChart
            ref={chartRef}
            option={options}
            notMerge
            style={{ width: '100%', height: '100%' }}
          />
        </div>
      </div>
    </>
  );
};

export default IntellectDraw;