import { useMemo, useRef } from 'react'
import ReactEcharts from 'echarts-for-react';
const Chart = ({
  data,
  style,
  color,
}: {
  data?: any[];  // 接收数据源
  style?: React.CSSProperties;
  color?: string[]
}) => {

  const ref = useRef(null)

  const option = useMemo(() => {
    // 计算总数
    const total = data?.reduce((acc, cur) => acc + Number(cur.num), 0) || 0;
    const totalInWan = total;
    // const totalInWan = (total / 10000).toFixed(1);

    const seriesData = data?.map(item => ({
      name: item.ssqy,
      value: item.num
    }))
    return {
      tooltip: {
        trigger: 'item',
        borderWidth: '0',
        backgroundColor: 'rgba(73,81,92,.95)',
        textStyle: {
          color: '#fff',
          fontSize: 16,
        },
        formatter: (params: any) => {
          return `${params?.data?.name}: ${params?.data?.value}件`;
        },
        position: function (point: any, params: any, dom: any, rect: any, size: any) {
          const xOffset = 10;
          const yOffset = 10;
          return [point[0] + xOffset, point[1] + yOffset];
        }
      },
      color: color ?? ['#FF9B5D', '#FFE335', '#29B5FF'],
      series: [
        {
          name: '',
          type: 'pie',
          radius: ['65%', '90%'],
          avoidLabelOverlap: false,
          padAngle: 5,
          label: {
            show: true,
            position: 'center',
            formatter: () => {
              return [
                `{total|${totalInWan}}`,
                '{unit|件}'
              ].join('\n');
            },
            rich: {
              total: {
                color: '#FFFFFF',
                fontSize: 20,
                fontWeight: 700,
                lineHeight: 40,
                fontFamily: 'DingTalk JinBuTi'
              },
              unit: {
                color: '#FFFFFF',
                fontSize: 14,
                fontWeight: 400,
                lineHeight: 20
              }
            }
          },
          labelLine: {
            show: false,
          },
          data: seriesData,
        },
      ],
    }
  }, [data])

  return (
    <ReactEcharts
      ref={ref}
      option={option} // option：图表配置项
      notMerge={true}
      lazyUpdate={true}
      style={style}
    />
  );
};

export default Chart;