import React, { memo, useMemo } from 'react';
import _ from 'lodash';
import { BasicChart } from '@wisdom-components/basicchart';
import PandaEmpty from '@wisdom-components/empty';
import optionGenerator from './utils';

const ChartTitle = ({ prefixCls, title, unit }) => {
  const cls = `${prefixCls}-grid-item-title`;
  return (
    <div className={cls}>
      <span className={`${cls}_text`}>{title}</span>
      {unit && <span className={`${cls}_unit`}>（单位：{unit}）</span>}
    </div>
  );
};

const GridChart = memo((props) => {
  const {
    dataSource,
    contrast = false,
    contrastOption = 'day',
    smooth = true,
    curveCenter,
  } = props;
  const { prefixCls } = props;

  const gridData = useMemo(() => {
    const grids = dataSource.reduce((pre, item, index) => {
      const { sensorName, deviceType } = item;
      const key = `${deviceType}_${sensorName}`; // 同设备类型同指标才在同一组
      let grid = pre.find((g) => g.key === key);
      if (!grid) {
        const restProp = _.pick(item, ['equipmentName', 'sensorName', 'stationCode', 'unit']);
        grid = {
          key: key,
          list: [],
          ...restProp,
        };
        pre.push(grid);
      }
      grid.list.push(item);
      return pre;
    }, []);
    return grids;
  }, [dataSource]);

  const options = useMemo(() => {
    let _options = gridData.map((item) => {
      const { key, list, equipmentName, sensorName, stationCode, unit } = item;
      const cusOption = {
        title: {
          show: true,
          // text: `{prefix|}{t|${sensorName}}${unit ? '{suffix|（单位：' + unit + '）}' : ''}`,
          text: ' ',
          textStyle: {
            width: 200,
            overflow: 'truncate',
          },
        },
        legend: {
          // orient: 'vertical',
          itemGap: 10,
          padding: [0, 0, 0, 200],
          textStyle: {
            width: 120,
            overflow: 'truncate',
          },
        },
      };
      const option = optionGenerator(list, cusOption, contrast, contrastOption, smooth, {
        curveCenter,
        nameWithSensor: false,
        showGridLine: true,
      });
      return {
        key,
        option: option,
      };
    });
    return _options
  }, [gridData, smooth, curveCenter]);

  return (
    <div className={`${prefixCls}-grid`}>
      {options.map((item, index) => {
        const { sensorName, unit } = gridData[index];
        const isEmpty =
          !item.option.series.length ||
          !item.option.series.find((e) => e.data && e.data.length > 0);
        return (
          <div key={item.key} className={`${prefixCls}-grid-item`}>
            <div className={`${prefixCls}-grid-item-wrap`}>
              <ChartTitle prefixCls={prefixCls} title={sensorName} unit={unit} />
              {isEmpty ? (
                <PandaEmpty />
              ) : (
                <BasicChart
                  style={{ width: '100%', height: '100%' }}
                  option={item.option}
                  notMerge
                />
              )}
            </div>
          </div>
        );
      })}
    </div>
  );
});

export default GridChart;
