index.js 17.1 KB
Newer Older
李纪文's avatar
李纪文 committed
1 2 3 4 5 6
import React, { useState, useEffect, useRef, useContext } from 'react';
import classNames from 'classnames';
import moment from 'moment';
import Empty from '@wisdom-components/empty';
import LoadBox from '@wisdom-components/loadbox';
import BasicTable from '@wisdom-components/basictable';
李纪文's avatar
李纪文 committed
7 8 9
import { ExportExcel } from '@wisdom-components/exportexcel';
import { ConfigProvider, Select, DatePicker, Radio, Table, Button } from 'antd';
import { VerticalAlignBottomOutlined } from '@ant-design/icons';
李纪文's avatar
李纪文 committed
10 11 12 13 14 15 16
import { BasicChart } from '@wisdom-components/basicchart';
import { getStatisticsInfo } from './apis';
import './index.less';

const StatisticalHistoryView = (props) => {
  const { getPrefixCls } = useContext(ConfigProvider.ConfigContext);
  const prefixCls = getPrefixCls('ec-statistical-history-view');
李纪文's avatar
李纪文 committed
17
  const chartRef = useRef(null);
李纪文'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

  const [loading, setLoading] = useState(false);
  const [historyRender, setHistoryRender] = useState(true);
  const [historyParams, setHistoryParams] = useState({});
  const [columns, setColumns] = useState([
    {
      title: '时间',
      dataIndex: 'pt',
      align: 'center',
      width: 100,
      fixed: 'left',
    },
  ]);
  const [dataSource, setDataSource] = useState([]);
  const [options, setOptions] = useState({});
  const [dateValue, setDateValue] = useState('today');
  const [picker, setPicker] = useState('day');
  const [time, setTime] = useState({ startTime: '', endTime: '' });
  const [dateTime, setDateTime] = useState(moment().format('YYYY-MM-DD HH:mm:ss'));

  // 时间切换筛选
  const onTimeChange = (e) => {
    setDateValue(e.target.value);
  };

  // 自定义时间类型
  const onPickerChange = (value) => {
    setPicker(value);
李纪文's avatar
李纪文 committed
46 47
    let start = moment(dateTime).subtract(2, value).startOf(value).format('YYYY-MM-DD 00:00:00');
    let end = moment(dateTime).endOf(value).format('YYYY-MM-DD 23:59:59');
李纪文's avatar
李纪文 committed
48 49 50 51 52 53 54 55 56 57 58
    setTime({ startDate: start, endDate: end });
  };

  // 自定义时间选择
  const onDateChange = (value, dateString) => {
    setDateTime(dateString);
    const start = moment(value).subtract(2, picker).format('YYYY-MM-DD 00:00:00');
    const end = moment(value).format('YYYY-MM-DD 23:59:59');
    setTime({ startDate: start, endDate: end });
  };

李纪文's avatar
李纪文 committed
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
  const exportExcelBtn = (e) => {
    if (!dataSource.length) return false;
    const sheetFilter = columns.map((item) => {
      return item.dataIndex;
    });
    const sheetHeader = columns.map((item) => {
      return item.title;
    });
    const sheetData = dataSource.map((item) => {
      return {
        pt: item.pt,
        value0: String(item.value0),
        value1: String(item.value1),
        value2: String(item.value2),
      };
    });
    ExportExcel({
      name: `${props?.deviceParams?.sensors || ''}指标数据`,
      content: [
        {
          sheetData: sheetData,
          sheetName: 'sheet1',
          sheetFilter: sheetFilter,
          sheetHeader: sheetHeader,
          columnWidths: [10, 10, 10, 10],
        },
      ],
    });
  };

李纪文's avatar
李纪文 committed
89 90 91 92
  // 获取历史统计数据
  const getHistoryData = async () => {
    const { deviceCode = '', sensors = '', deviceType = '', statisticType = '' } = historyParams;
    const nameTypeList = [];
李纪文's avatar
李纪文 committed
93
    if (!deviceCode || !sensors) return setOptions(null);
李纪文's avatar
李纪文 committed
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
    nameTypeList.push({
      name: sensors,
      type: statisticType || 'Sub',
    });
    const params = {
      pageIndex: 1,
      pageSize: 999,
      nameTypeList: nameTypeList,
      accountName: deviceType,
      dateFrom: time.startDate,
      dateTo: time.endDate,
      deviceCode: deviceCode,
      dateType: picker,
    };
    setLoading(true);
李纪文's avatar
李纪文 committed
109 110 111 112 113 114
    let results = null;
    try {
      results = await getStatisticsInfo(params);
    } catch (err) {
      return setLoading(false);
    }
李纪文's avatar
李纪文 committed
115 116 117 118 119
    setLoading(false);
    const list = results?.data?.list || [];
    const dataList = list.length ? list[0] : {};
    const dNameDataList = dataList.dNameDataList ? dataList.dNameDataList : [];
    const data = dNameDataList.length ? dNameDataList[0] : null;
李纪文's avatar
李纪文 committed
120
    if (!data) return setOptions(null);
李纪文's avatar
李纪文 committed
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
    dataMenthod(data);
  };

  const dataMenthod = (data) => {
    const { nameDate } = data;
    let time0 = '',
      time1 = '',
      time2 = '';
    let data0 = [],
      data1 = [],
      data2 = [];
    let timeName = [];
    switch (dateValue) {
      case 'today':
        time0 = moment(time.endDate).subtract(0, 'day').format('YYYY-MM-DD');
        time1 = moment(time.endDate).subtract(1, 'day').format('YYYY-MM-DD');
        time2 = moment(time.endDate).subtract(2, 'day').format('YYYY-MM-DD');
        timeName = [].concat(dayName);
        nameDate.forEach((item) => {
          const times = moment(item.time).format('YYYY-MM-DD');
          const pt = moment(item.time).format('HH时');
          if (times === time0) data0.push({ ...item, pt: pt });
          if (times === time1) data1.push({ ...item, pt: pt });
          if (times === time2) data2.push({ ...item, pt: pt });
        });
        break;
      case 'thisWeek':
        time0 = moment(time.endDate).subtract(0, 'week').format('WW');
        time1 = moment(time.endDate).subtract(1, 'week').format('WW');
        time2 = moment(time.endDate).subtract(2, 'week').format('WW');
        timeName = [].concat(weekName);
        nameDate.forEach((item) => {
          const times = moment(item.time).format('WW');
          const pt = getWeek(item.time);
          if (times === time0) data0.push({ ...item, pt: pt });
          if (times === time1) data1.push({ ...item, pt: pt });
          if (times === time2) data2.push({ ...item, pt: pt });
        });
        break;
      case 'thisMonth':
        time0 = moment(time.endDate).subtract(0, 'month').format('YYYY-MM');
        time1 = moment(time.endDate).subtract(1, 'month').format('YYYY-MM');
        time2 = moment(time.endDate).subtract(2, 'month').format('YYYY-MM');
        timeName = [].concat(monthName);
        nameDate.forEach((item) => {
          const times = moment(item.time).format('YYYY-MM');
          const pt = moment(item.time).format('DD日');
          if (times === time0) data0.push({ ...item, pt: pt });
          if (times === time1) data1.push({ ...item, pt: pt });
          if (times === time2) data2.push({ ...item, pt: pt });
        });
        break;
李纪文's avatar
李纪文 committed
173 174 175 176 177 178 179 180 181 182 183 184 185
      case 'thisYear':
        time0 = moment(time.endDate).subtract(0, 'year').format('YYYY');
        time1 = moment(time.endDate).subtract(1, 'year').format('YYYY');
        time2 = moment(time.endDate).subtract(2, 'year').format('YYYY');
        timeName = [].concat(yearName);
        nameDate.forEach((item) => {
          const times = moment(item.time).format('YYYY');
          const pt = moment(item.time).format('MM月');
          if (times === time0) data0.push({ ...item, pt: pt });
          if (times === time1) data1.push({ ...item, pt: pt });
          if (times === time2) data2.push({ ...item, pt: pt });
        });
        break;
李纪文's avatar
李纪文 committed
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
      case 'customer':
        const style = picker === 'day' ? 'HH时' : picker === 'month' ? 'DD日' : 'MM月';
        const format = picker === 'day' ? 'YYYY-MM-DD' : picker === 'month' ? 'YYYY-MM' : 'YYYY';
        time0 = moment(time.endDate).subtract(0, picker).format(format);
        time1 = moment(time.endDate).subtract(1, picker).format(format);
        time2 = moment(time.endDate).subtract(2, picker).format(format);
        timeName = [].concat([time0, time1, time2]);
        nameDate.forEach((item) => {
          const times = moment(item.time).format(format);
          const pt = moment(item.time).format(style);
          if (times === time0) data0.push({ ...item, pt: pt });
          if (times === time1) data1.push({ ...item, pt: pt });
          if (times === time2) data2.push({ ...item, pt: pt });
        });
        break;
    }
    const dataChart = {
      data: [data0, data1, data2],
      name: timeName,
    };
    const dataTable = data0.map((item, index) => {
      return {
        ...item,
李纪文's avatar
李纪文 committed
209 210 211
        value0: item?.value === 0 || item?.value ? item?.value : '-',
        value1: data1[index]?.value === 0 || data1[index]?.value ? data1[index]?.value : '-',
        value2: data2[index]?.value === 0 || data2[index]?.value ? data2[index]?.value : '-',
李纪文's avatar
李纪文 committed
212 213 214 215 216 217 218 219 220 221 222
      };
    });
    renderChart(dataChart, data);
    renderTable(dataTable, timeName);
  };

  const renderChart = (dataInfo, data) => {
    if (!dataInfo) return setOptions(null);
    const { unit, dName } = data;
    const series = [];
    dataInfo.data.forEach((item, index) => {
李纪文's avatar
李纪文 committed
223
      const config = !index && dName.indexOf('流量') > -1 ? { areaStyle: {} } : {};
李纪文's avatar
李纪文 committed
224
      const style = index ? { lineStyle: { normal: { type: 'dashed' } } } : {};
李纪文's avatar
李纪文 committed
225 226 227
      const list = {
        name: dataInfo.name[index],
        type: 'line',
李纪文's avatar
李纪文 committed
228
        smooth: true,
李纪文's avatar
李纪文 committed
229
        ...config,
李纪文's avatar
李纪文 committed
230
        ...style,
李纪文's avatar
李纪文 committed
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
        data: item.map((arr) => {
          return {
            name: arr.pt,
            value: arr.value,
          };
        }),
      };
      series.push(list);
    });
    const option = {
      title: {
        show: false,
        text: '',
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
        },
      },
      grid: {
        containLabel: true,
李纪文's avatar
李纪文 committed
253
        left: 20,
李纪文's avatar
李纪文 committed
254
        right: 20,
李纪文's avatar
李纪文 committed
255 256
        // top: 20,
        bottom: 10,
李纪文's avatar
李纪文 committed
257 258 259 260 261 262 263 264 265 266 267 268 269
      },
      toolbox: {
        show: false,
      },
      legend: {
        left: 'center',
      },
      xAxis: [
        {
          type: 'category',
          axisTick: {
            alignWithLabel: true,
          },
李纪文's avatar
李纪文 committed
270 271 272 273 274 275 276
          boundaryGap: false,
          splitLine: {
            show: true,
            lineStyle: {
              type: 'dashed',
            },
          },
李纪文's avatar
李纪文 committed
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
        },
      ],
      yAxis: [
        {
          type: 'value',
          name: unit,
          position: 'left',
          alignTicks: true,
          axisLine: {
            show: true,
          },
          axisLabel: {
            formatter: '{value}',
          },
        },
      ],
      series: series,
    };
    setOptions(option);
  };

  const renderTable = (dataInfo, timeName) => {
李纪文's avatar
李纪文 committed
299
    const dataIndex = ['value0', 'value1', 'value2'];
李纪文's avatar
李纪文 committed
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 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
    const column1 = [
      {
        title: '时间',
        dataIndex: 'pt',
        align: 'center',
        width: 100,
        fixed: 'left',
      },
    ];
    const column2 = timeName.map((item, index) => {
      return {
        title: item,
        dataIndex: dataIndex[index],
        align: 'center',
      };
    });
    const column = column1.concat(column2);
    setColumns(column);
    setDataSource(dataInfo);
  };

  const getWeek = (date) => {
    const weekTime = moment(date).day();
    switch (weekTime) {
      case 1:
        return '周一';
        break;
      case 2:
        return '周二';
        break;
      case 3:
        return '周三';
        break;
      case 4:
        return '周四';
        break;
      case 5:
        return '周五';
        break;
      case 6:
        return '周六';
        break;
      case 0:
        return '周日';
        break;
    }
  };

李纪文's avatar
李纪文 committed
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
  const Summary = (currentData) => {
    return (
      <Table.Summary.Row>
        {columns.map((item, index) => {
          let sum = 0;
          currentData.reduce((prev, next) => {
            sum += next[item.dataIndex] === '-' ? 0 : next[item.dataIndex];
          }, 0);
          return (
            <Table.Summary.Cell key={item.dataIndex} index={index} align={'center'}>
              {index === 0 ? '总计' : sum.toFixed(0)}
            </Table.Summary.Cell>
          );
        })}
      </Table.Summary.Row>
    );
  };

李纪文's avatar
李纪文 committed
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
  useEffect(() => {
    setHistoryParams(props.deviceParams || {});
  }, [props.deviceParams]);

  useEffect(() => {
    let start = '',
      end = '';
    switch (dateValue) {
      case 'today':
        start = moment().subtract(2, 'day').format('YYYY-MM-DD 00:00:00');
        end = moment().format('YYYY-MM-DD 23:59:59');
        setPicker('day');
        break;
      case 'thisWeek':
        start = moment().startOf('week').subtract(2, 'week').format('YYYY-MM-DD 00:00:00');
        end = moment().endOf('week').format('YYYY-MM-DD 23:59:59');
        setPicker('month');
        break;
      case 'thisMonth':
        start = moment().startOf('month').subtract(2, 'month').format('YYYY-MM-DD 00:00:00');
        end = moment().endOf('month').format('YYYY-MM-DD 23:59:59');
        setPicker('month');
        break;
李纪文's avatar
李纪文 committed
389 390 391 392 393
      case 'thisYear':
        start = moment().startOf('year').subtract(2, 'year').format('YYYY-MM-DD 00:00:00');
        end = moment().endOf('year').format('YYYY-MM-DD 23:59:59');
        setPicker('year');
        break;
李纪文's avatar
李纪文 committed
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
      case 'customer':
        start = moment().startOf(picker).subtract(2, picker).format('YYYY-MM-DD 00:00:00');
        end = moment().endOf(picker).format('YYYY-MM-DD 23:59:59');
        break;
    }
    setTime({ startDate: start, endDate: end });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dateValue]);

  useEffect(() => {
    getHistoryData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [time, historyParams, picker]);

  return (
    <div className={classNames(prefixCls)}>
      <div className={classNames(`${prefixCls}-box`)}>
        <div className={classNames(`${prefixCls}-header`)}>
李纪文's avatar
李纪文 committed
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
          <div className={classNames(`${prefixCls}-time`)}>
            <span>时间选择:</span>
            <Radio.Group value={dateValue} defaultValue={dateList[0].key} onChange={onTimeChange}>
              {dateList.map((item) => (
                <Radio.Button key={item.key} value={item.key}>
                  {item.name}
                </Radio.Button>
              ))}
            </Radio.Group>
            {dateValue === 'customer' && (
              <>
                <Select
                  defaultValue="day"
                  value={picker}
                  options={timeList}
                  onChange={onPickerChange}
                  className={classNames(`${prefixCls}-select`)}
                />
                <DatePicker onChange={onDateChange} value={moment(dateTime)} picker={picker} />
              </>
            )}
          </div>
          <Button
            className={classNames(`${prefixCls}-down-load`)}
            type="primary"
            onClick={exportExcelBtn}
            disabled={!dataSource.length}
          >
            <VerticalAlignBottomOutlined />
            下载
          </Button>
李纪文's avatar
李纪文 committed
443 444 445 446 447
        </div>
        <div className={classNames(`${prefixCls}-content`)}>
          {
            <>
              <div className={classNames(`${prefixCls}-chart`)}>
李纪文's avatar
李纪文 committed
448 449 450 451 452 453 454 455 456 457 458 459
                {options ? (
                  <BasicChart
                    ref={chartRef}
                    option={options}
                    notMerge
                    style={{ width: '100%', height: '100%' }}
                  />
                ) : (
                  <div className={classNames(`${prefixCls}-empty`)}>
                    <Empty />
                  </div>
                )}
李纪文's avatar
李纪文 committed
460 461 462 463 464 465 466
              </div>
              <div className={classNames(`${prefixCls}-table`)}>
                <BasicTable
                  dataSource={dataSource}
                  columns={columns}
                  pagination={false}
                  bordered={true}
李纪文's avatar
李纪文 committed
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
                  onRow={(record, index) => {
                    return {
                      onMouseEnter: (event) => {
                        let seriesIndex = 0;
                        const dataIndex = ['value0', 'value1', 'value2'];
                        seriesIndex = dataIndex.findIndex((item) => {
                          return record[item] !== '-';
                        });
                        chartRef?.current?.getEchartsInstance() &&
                          chartRef?.current?.getEchartsInstance().dispatchAction({
                            type: 'showTip',
                            seriesIndex: seriesIndex,
                            dataIndex: index,
                          });
                      }, // 鼠标移入行
                      onMouseLeave: (event) => {
                        chartRef?.current?.getEchartsInstance() &&
                          chartRef?.current?.getEchartsInstance().dispatchAction({
                            type: 'hideTip',
                            dataIndex: index,
                          });
                      }, // 鼠标移出行
                    };
                  }}
李纪文's avatar
李纪文 committed
491
                  scroll={{ x: '100%', y: 'calc(100% - 40px)' }}
李纪文's avatar
李纪文 committed
492
                  summary={Summary}
李纪文's avatar
李纪文 committed
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
                />
              </div>
            </>
          }
        </div>
      </div>
      {loading && (
        <div className={classNames(`${prefixCls}-load-box`)}>
          <LoadBox spinning={loading} />
        </div>
      )}
    </div>
  );
};

export default StatisticalHistoryView;

const dateList = [
  {
    key: 'today',
    name: '今日',
  },
李纪文's avatar
李纪文 committed
515 516 517 518
  // {
  //   key: 'thisWeek',
  //   name: '本周',
  // },
李纪文's avatar
李纪文 committed
519 520 521 522
  {
    key: 'thisMonth',
    name: '本月',
  },
李纪文's avatar
李纪文 committed
523 524 525 526
  {
    key: 'thisYear',
    name: '今年',
  },
李纪文's avatar
李纪文 committed
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
  {
    key: 'customer',
    name: '自定义',
  },
];

const timeList = [
  {
    value: 'day',
    label: '日',
  },
  {
    value: 'month',
    label: '月',
  },
  {
    value: 'year',
    label: '年',
  },
];

const dayName = ['今日', '昨日', '前日'];

const weekName = ['本周', '上周', '上上周'];

const monthName = ['本月', '上月', '上上月'];
李纪文's avatar
李纪文 committed
553 554

const yearName = ['今年', '去年', '前年'];