import { ArcElement, Chart as ChartJS, Legend, Tooltip } from "chart.js";
import React, { forwardRef, useImperativeHandle, useRef } from "react";
import { Doughnut } from "react-chartjs-2";
import { defaultColorList } from "../const";
import { isWindowDefined } from "../env";
import { Container } from "./Container";
var chartMarkPieRegistered = false;
export var Pie = /*#__PURE__*/ forwardRef(function(props, ref) {
    React.useMemo(function() {
        if (chartMarkPieRegistered) {
            return undefined;
        }
        if (!isWindowDefined()) {
            return undefined;
        }
        ChartJS.register(ArcElement, Tooltip, Legend);
        chartMarkPieRegistered = true;
        return undefined;
    }, []);
    var chartRef = React.useRef(undefined);
    var htmlRef = useRef(null);
    var pieChartRef = useRef(null);
    useImperativeHandle(ref, function() {
        return chartRef.current;
    }, [
        chartRef.current
    ]);
    // 处理数据格式
    var processData = function processData() {
        if (!props.data || props.data.length === 0) {
            return {
                labels: [],
                datasets: []
            };
        }
        // 获取标签和数据
        var labels = props.data.map(function(item) {
            return item[props.xField];
        });
        var data = props.data.map(function(item) {
            return item[props.yField];
        });
        return {
            labels: labels,
            datasets: [
                {
                    data: data,
                    backgroundColor: defaultColorList.slice(0, data.length),
                    borderColor: defaultColorList.slice(0, data.length).map(function(color) {
                        return color;
                    }),
                    borderWidth: 1
                }
            ]
        };
    };
    var chartData = processData();
    var options = {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                display: true,
                position: 'bottom'
            },
            tooltip: {
                enabled: true
            }
        },
        cutout: '50%'
    };
    // 更新 chartRef 当 Doughnut 组件的 ref 改变时
    React.useEffect(function() {
        if (pieChartRef.current) {
            chartRef.current = pieChartRef.current;
        }
    }, [
        pieChartRef.current
    ]);
    return /*#__PURE__*/ React.createElement(Container, {
        index: props.index,
        chartRef: chartRef,
        htmlRef: htmlRef
    }, /*#__PURE__*/ React.createElement(Doughnut, {
        ref: pieChartRef,
        data: chartData,
        options: options
    }));
});
Pie.displayName = 'Pie';
