/*
data: [
        { value: 1048, name: 'Search Engine' },
        { value: 735, name: 'Direct' },
        { value: 580, name: 'Email' },
        { value: 484, name: 'Union Ads' },
        { value: 300, name: 'Video Ads' },
      ],
*/

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

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

  useEffect(() => {
    if (!chartRef.current || !data) return;
    const option = { ...defaultOption };
    option.series[0].data = data;
    chartRef.current.clear();
    chartRef.current.setOption(option);
    chartRef.current.resize();
  }, [data]);

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

  const getStyle = () => {
    if (data && data.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} />
      {(!data || data.length == 0) && <Empty />}
    </div>
  );
};
export default PieChartModule;
const colors = [
  '#5470c6',
  '#91cc75',
  '#fac858',
  '#ee6666',
  '#73c0de',
  '#3ba272',
  '#fc8452',
  '#9a60b4',
  '#ea7ccc',
];
const defaultOption = {
  color: colors,
  tooltip: {
    trigger: 'item',
    formatter: '{b} : {d}% ({c})',
  },

  series: [
    {
      type: 'pie',
      radius: '70%',
      data: [
        { value: 1048, name: 'Search Engine' },
        { value: 735, name: 'Direct' },
        { value: 580, name: 'Email' },
        { value: 484, name: 'Union Ads' },
        { value: 300, name: 'Video Ads' },
      ],
      label: {
        fontSize: 18,
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)',
        },
        label: {
          fontSize: 24,
        },
      },
    },
  ],
};
