import React, { useEffect, useRef, useState } from 'react';
import * as echarts from 'echarts';


const BarChart = props => {
  const { data } = props;
  const domRef = useRef(null);
  const chartRef = useRef(null);

  useEffect(() => {
    chartRef.current = echarts.init(domRef.current);

    // 在组件卸载时销毁图表实例
    return () => {
      chartRef.current.dispose();
    };
  }, []);

  useEffect(() => {
    let options = getOption(data);

    // chartRef.current.clear();
    chartRef.current.setOption(options);
  }, [data]);

  return <div ref={domRef} style={{ height: '100%' }} />;
};
const getOption = chartData => {
  let option = {
    title: [
      {
        text: chartData[0].name,
        left: '25%',
        bottom: 20,
        textAlign: 'center',
        textStyle: { // color: '#fff' },
      },
      {
        text: chartData[1].name,
        left: '75%',
        bottom: 20,
        textAlign: 'center',
        textStyle: { // color: '#fff' },
      },
    ],
    color: [
      '#5470c6',
      '#91cc75',
      '#fac858',
      '#ee6666',
      '#73c0de',
      '#3ba272',
      '#fc8452',
      '#9a60b4',
      '#ea7ccc',
    ],
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c}',
    },
    series: [
      {
        name: chartData[0].name,
        type: 'pie',
        radius: [20, "55%"],
        center: ['25%', '45%'],
        itemStyle: {
          borderRadius: 5,
        },
        label: {
          // color: '#fff',
          fontSize: 16,
        },
        data: chartData[0].value,
      },
      {
        name: chartData[1].name,
        type: 'pie',
        radius: [20, "55%"],
        center: ['75%', '45%'],
        itemStyle: {
          borderRadius: 5,
        },
        label: {
          // color: '#fff',
          fontSize: 16,
        },
        data: chartData[1].value,
      },
    ],
  };

  return option;
};

export default BarChart;
