/*
//y轴显示数据
Data:{       
  name:string,                       
  data:string[],
}

props：{
  xData:string[],  //x轴时间数据
  dataList:Data[],  //数据列表
}
*/

import { Empty } from 'antd';
import * as echarts from 'echarts';
import { useEffect, useRef } from 'react';
import styles from './index.less';

//图表模块
const BarChartModule = (props) => {
  const chartDomRef = useRef();
  const chartRef = useRef();
  const { xData, dataList } = props;
  useEffect(() => {
    chartRef.current = echarts.init(chartDomRef.current);
    window.addEventListener('resize', resetChart);
    return () => window.removeEventListener('resize', resetChart);
  }, []);

  useEffect(() => {
    if (!chartRef.current || !dataList) return;
    const option = { ...defaultOption };
    option.xAxis.data = xData;
    option.series = dataList.map((item, idx) => {
      return {
        ...option.series[idx],
        ...item,
      };
    });
    chartRef.current.clear();
    chartRef.current.setOption(option);
    chartRef.current.resize();
  }, [xData, dataList]);

  const resetChart = () => {
    if (chartRef.current) chartRef.current.resize();
  };

  const getStyle = () => {
    if (dataList && dataList.length != 0)
      return { width: '100%', height: '100%' };
    else return { width: '100%', height: '100%', display: 'none' };
  };

  return (
    <div className={styles.content}>
      <div style={getStyle()} ref={chartDomRef} />
      {(!dataList || dataList.length == 0) && <Empty />}
    </div>
  );
};
export default BarChartModule;
const colors = [
  '#5470c6',
  '#91cc75',
  '#fac858',
  '#ee6666',
  '#73c0de',
  '#3ba272',
  '#fc8452',
  '#9a60b4',
  '#ea7ccc',
];
const defaultOption = {
  color: colors,
  grid: {
    bottom: 30,
    left: 60,
    right: 30,
  },
  xAxis: {
    type: 'category',
    axisTick: { show: false },
    axisLine: {
      lineStyle: {
        color: '#c9d2d2',
      },
    },
    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
  },
  yAxis: {
    type: 'value',
    splitLine: {
      lineStyle: {
        type: 'dashed',
      },
    },
    axisTick: { show: false },
    axisLine: {
      show: false,
    },
  },
  legend: {
    icon: 'circle',
    right: '20%',
  },
  series: [
    {
      name: '2022',
      data: [120, 200, 150, 80, 70, 110, 130],
      type: 'bar',
      label: {
        show: true,
        position: 'top',
      },
      barGap: '0',
      barMaxWidth: '10%',
    },
    {
      name: '2023',
      data: [120, 200, 150, 80, 70, 110, 130],
      type: 'bar',
      label: {
        show: true,
        position: 'top',
      },
      barGap: '0',
      barMaxWidth: '10%',
    },
  ],
};
