import * as echarts from 'echarts/lib/echarts';
import type { ECharts } from 'echarts';
import { getInstanceByDom } from 'echarts';
import React, { useEffect, useRef, useState } from 'react';

const FinishRate: React.FC<{ data: any }> = ({ data }) => {
  const chartRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    // Initialize chart
    let chart: ECharts | undefined;
    if (chartRef.current !== null) {
      chart = echarts.init(chartRef.current);
    }

    // Add chart resize listener
    // ResizeObserver is leading to a bit janky UX
    function resizeChart() {
      chart?.resize();
    }
    window.addEventListener('resize', resizeChart);

    // Return cleanup function
    return () => {
      chart?.dispose();
      window.removeEventListener('resize', resizeChart);
    };
  }, []);

  useEffect(() => {
    const rate = (
      data.planNum == 0 ? 0 : ((data.actualFinishNum || 0) / (data.planNum || 0)) * 100
    ).toFixed(2);
    if (chartRef.current !== null) {
      const chart = getInstanceByDom(chartRef.current);
      const option = {
        title: {
          text: '完成率',
          top: 10,
          left: 10,
          textStyle: {
            fontSize: 20,
            color: '#ffffff',
          },
        },
        color: ['#249ab5', '#7f7f7f'],
        series: [
          {
            name: 'Access From',
            type: 'pie',
            radius: ['50%', '90%'],
            top: 20,
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: 'center',
              formatter: rate + '%',
              color: '#fff',
              fontSize: '16px',
              fontWeight: 600,
            },
            silent: false,
            data: [
              { value: rate, name: '物料配送完成率' },
              { value: 100 - rate, name: '物料配送未完成率' },
            ],
          },
        ],
      };
      chart?.setOption(option);
    }
  }, [data]);
  return <div ref={chartRef} style={{ width: '100%', height: '100%' }}></div>;
};

export default FinishRate;
