function _array_like_to_array(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
    return arr2;
}
function _array_with_holes(arr) {
    if (Array.isArray(arr)) return arr;
}
function _array_without_holes(arr) {
    if (Array.isArray(arr)) return _array_like_to_array(arr);
}
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
function _iterable_to_array(iter) {
    if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _iterable_to_array_limit(arr, i) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
        for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
            _arr.push(_s.value);
            if (i && _arr.length === i) break;
        }
    } catch (err) {
        _d = true;
        _e = err;
    } finally{
        try {
            if (!_n && _i["return"] != null) _i["return"]();
        } finally{
            if (_d) throw _e;
        }
    }
    return _arr;
}
function _non_iterable_rest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _non_iterable_spread() {
    throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _object_spread(target) {
    for(var i = 1; i < arguments.length; i++){
        var source = arguments[i] != null ? arguments[i] : {};
        var ownKeys = Object.keys(source);
        if (typeof Object.getOwnPropertySymbols === "function") {
            ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
                return Object.getOwnPropertyDescriptor(source, sym).enumerable;
            }));
        }
        ownKeys.forEach(function(key) {
            _define_property(target, key, source[key]);
        });
    }
    return target;
}
function ownKeys(object, enumerableOnly) {
    var keys = Object.keys(object);
    if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object);
        if (enumerableOnly) {
            symbols = symbols.filter(function(sym) {
                return Object.getOwnPropertyDescriptor(object, sym).enumerable;
            });
        }
        keys.push.apply(keys, symbols);
    }
    return keys;
}
function _object_spread_props(target, source) {
    source = source != null ? source : {};
    if (Object.getOwnPropertyDescriptors) {
        Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
        ownKeys(Object(source)).forEach(function(key) {
            Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
        });
    }
    return target;
}
function _object_without_properties(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys, key, i;
    if (typeof Reflect !== "undefined" && Reflect.ownKeys) {
        sourceKeys = Reflect.ownKeys(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
        return target;
    }
    target = _object_without_properties_loose(source, excluded);
    if (Object.getOwnPropertySymbols) {
        sourceKeys = Object.getOwnPropertySymbols(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
    }
    return target;
}
function _object_without_properties_loose(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys = Object.getOwnPropertyNames(source), key, i;
    for(i = 0; i < sourceKeys.length; i++){
        key = sourceKeys[i];
        if (excluded.indexOf(key) >= 0) continue;
        if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
        target[key] = source[key];
    }
    return target;
}
function _sliced_to_array(arr, i) {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _to_consumable_array(arr) {
    return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
import { ConfigProvider } from "antd";
import { ArcElement, Chart as ChartJS, Legend, Tooltip } from "chart.js";
import ChartDataLabels from "chartjs-plugin-datalabels";
import classNames from "clsx";
import React, { useContext, useMemo, useRef, useState } from "react";
import { Doughnut } from "react-chartjs-2";
import { useLocale } from "../../../I18n";
import { ChartContainer, ChartFilter, ChartStatistic, ChartToolBar, downloadChart } from "../components";
import { defaultColorList } from "../const";
import { isWindowDefined } from "../env";
import { useChartTheme } from "../hooks";
import { resolveCssVariable } from "../utils";
import { SINGLE_MODE_DESKTOP_CUTOUT, SINGLE_MODE_MOBILE_CUTOUT } from "./constants";
import { useAutoCategory, useFilterLabels, useMobile, useResponsiveDimensions } from "./hooks";
import DonutChartLegend from "./Legend";
import { createBackgroundArcPlugin, createCenterTextPlugin, createDataLabelsLeaderLinePlugin } from "./plugins";
import { useStyle } from "./style";
/**
 * @fileoverview 环形图组件文件
 *
 * 该文件提供了环形图（甜甜圈图）组件的实现，基于 Chart.js 和 react-chartjs-2。
 * 支持饼图和环形图两种样式，提供数据可视化、交互、配置、统计等功能。
 *
 * @author md-editor
 * @version 1.0.0
 * @since 2024
 */ var donutChartComponentsRegistered = false;
/**
 * 环形图组件
 *
 * 基于 Chart.js 和 react-chartjs-2 实现的环形图（甜甜圈图）组件。
 * 支持饼图和环形图两种样式，提供数据可视化、交互、配置、统计等功能。
 *
 * @component
 * @param {DonutChartProps} props - 组件属性
 * @returns {React.ReactElement} 环形图组件
 *
 * @example
 * ```tsx
 * <DonutChart
 *   title="销售占比"
 *   data={[
 *     { label: '产品A', value: 30 },
 *     { label: '产品B', value: 50 },
 *     { label: '产品C', value: 20 }
 *   ]}
 *   configs={[{ chartStyle: 'donut', showLegend: true }]}
 *   width={400}
 *   height={400}
 *   showToolbar={true}
 * />
 * ```
 *
 * @since 1.0.0
 */ var DonutChart = function DonutChart(_0) {
    var data = _0.data, configs = _0.configs, _0_width = _0.width, width = _0_width === void 0 ? 200 : _0_width, _0_height = _0.height, height = _0_height === void 0 ? 200 : _0_height, className = _0.className, classNamesProp = _0.classNames, title = _0.title, _0_showToolbar = _0.showToolbar, showToolbar = _0_showToolbar === void 0 ? true : _0_showToolbar, onDownload = _0.onDownload, _0_theme = _0.theme, theme = _0_theme === void 0 ? 'light' : _0_theme, dataTime = _0.dataTime, filterList = _0.filterList, selectedFilter = _0.selectedFilter, onFilterChange = _0.onFilterChange, _0_enableAutoCategory = _0.enableAutoCategory, enableAutoCategory = _0_enableAutoCategory === void 0 ? true : _0_enableAutoCategory, _0_singleMode = _0.singleMode, singleMode = _0_singleMode === void 0 ? false : _0_singleMode, toolbarExtra = _0.toolbarExtra, _0_renderFilterInToolbar = _0.renderFilterInToolbar, renderFilterInToolbar = _0_renderFilterInToolbar === void 0 ? false : _0_renderFilterInToolbar, statisticConfig = _0.statistic, _0_loading = _0.loading, loading = _0_loading === void 0 ? false : _0_loading, props = _object_without_properties(_0, [
        "data",
        "configs",
        "width",
        "height",
        "className",
        "classNames",
        "title",
        "showToolbar",
        "onDownload",
        "theme",
        "dataTime",
        "filterList",
        "selectedFilter",
        "onFilterChange",
        "enableAutoCategory",
        "singleMode",
        "toolbarExtra",
        "renderFilterInToolbar",
        "statistic",
        "loading"
    ]);
    var _props_styles;
    useMemo(function() {
        if (donutChartComponentsRegistered) {
            return undefined;
        }
        if (!isWindowDefined()) {
            return undefined;
        }
        ChartJS.register(ArcElement, Tooltip, Legend, ChartDataLabels);
        donutChartComponentsRegistered = true;
        return undefined;
    }, []);
    var _useMobile = useMobile(), isMobile = _useMobile.isMobile, windowWidth = _useMobile.windowWidth;
    var locale = useLocale();
    // 使用 useChartTheme hook 获取主题相关颜色
    var isLight = useChartTheme(theme).isLight;
    // 默认配置：当 configs 不传时，使用默认配置，showLegend 默认为 true
    var defaultConfigs = [
        {
            showLegend: true
        }
    ];
    var finalConfigs = configs || defaultConfigs;
    var context = useContext(ConfigProvider.ConfigContext);
    var baseClassName = context === null || context === void 0 ? void 0 : context.getPrefixCls('donut-chart');
    var hashId = useStyle(baseClassName).hashId;
    // 多图场景下独立管理每个图表实例，避免引用被覆盖
    var chartRefs = useRef([]);
    // 多图场景下按图索引隔离 Legend 隐藏状态
    var _useState = _sliced_to_array(useState({}), 2), hiddenDataIndicesByChart = _useState[0], setHiddenDataIndicesByChart = _useState[1];
    var _useFilterLabels = useFilterLabels(data), filterLabels = _useFilterLabels.filterLabels, filteredDataByFilterLabel = _useFilterLabels.filteredDataByFilterLabel, selectedFilterLabel = _useFilterLabels.selectedFilterLabel, setSelectedFilterLabel = _useFilterLabels.setSelectedFilterLabel;
    var _useAutoCategory = useAutoCategory(data, enableAutoCategory, selectedFilter), autoCategoryData = _useAutoCategory.autoCategoryData, internalSelectedCategory = _useAutoCategory.internalSelectedCategory, setInternalSelectedCategory = _useAutoCategory.setInternalSelectedCategory, selectedCategory = _useAutoCategory.selectedCategory;
    var filteredData = useMemo(function() {
        var byCategory = selectedCategory ? data.filter(function(item) {
            return item.category === selectedCategory;
        }) : data;
        if (!filterLabels || !selectedFilterLabel) {
            return byCategory;
        }
        return byCategory.filter(function(item) {
            return item.filterLabel === selectedFilterLabel;
        });
    }, [
        data,
        selectedCategory,
        filterLabels,
        selectedFilterLabel
    ]);
    var handleInternalCategoryChange = function handleInternalCategoryChange(category) {
        setInternalSelectedCategory(category);
    };
    var handleLegendItemClick = function handleLegendItemClick(chartIndex, dataIndex) {
        setHiddenDataIndicesByChart(function(prev) {
            var _next_chartIndex;
            var next = _object_spread({}, prev);
            var currentSet = new Set((_next_chartIndex = next[chartIndex]) !== null && _next_chartIndex !== void 0 ? _next_chartIndex : new Set());
            if (currentSet.has(dataIndex)) {
                currentSet.delete(dataIndex);
            } else {
                currentSet.add(dataIndex);
            }
            next[chartIndex] = currentSet;
            return next;
        });
    };
    if (filterList && filterList.length > 0) {
        var uniqueItems = new Set(filterList);
        if (uniqueItems.size !== filterList.length) {
            var seen = new Set();
            var duplicates = new Set();
            filterList.forEach(function(item) {
                if (seen.has(item)) {
                    duplicates.add(item);
                } else {
                    seen.add(item);
                }
            });
            throw new Error("DonutChart filterList 包含重复项: [".concat(Array.from(duplicates).join(', '), "]. 每个筛选项必须唯一。"));
        }
    }
    // 处理 ChartStatistic 组件配置
    var statistics = useMemo(function() {
        if (!statisticConfig) return null;
        return Array.isArray(statisticConfig) ? statisticConfig : [
            statisticConfig
        ];
    }, [
        statisticConfig
    ]);
    var handleDownload = function handleDownload() {
        if (onDownload) {
            onDownload();
            return;
        }
        var instances = (chartRefs.current || []).filter(function(c) {
            return !!c;
        });
        if (instances.length <= 1) {
            var _instances_;
            var target = (_instances_ = instances[0]) !== null && _instances_ !== void 0 ? _instances_ : null;
            downloadChart(target, 'donut-chart');
            return;
        }
        try {
            var _Math;
            // 将多个 canvas 竖直拼接为一张图片
            var canvases = instances.map(function(inst) {
                return inst === null || inst === void 0 ? void 0 : inst.canvas;
            }).filter(Boolean);
            if (canvases.length === 0) {
                return;
            }
            var GAP = 16; // 竖向间距
            var widths = canvases.map(function(c) {
                return c.width;
            });
            var heights = canvases.map(function(c) {
                return c.height;
            });
            var maxWidth = (_Math = Math).max.apply(_Math, _to_consumable_array(widths));
            var totalHeight = heights.reduce(function(sum, h) {
                return sum + h;
            }, 0) + GAP * (canvases.length - 1);
            var composite = document.createElement('canvas');
            composite.width = maxWidth;
            composite.height = totalHeight;
            var ctx = composite.getContext('2d');
            if (!ctx) return;
            // 背景填充为白色，避免透明背景在 jpeg 下变黑
            ctx.fillStyle = '#ffffff';
            ctx.fillRect(0, 0, composite.width, composite.height);
            var offsetY = 0;
            canvases.forEach(function(c, i) {
                var x = Math.floor((maxWidth - c.width) / 2);
                ctx.drawImage(c, x, offsetY);
                offsetY += c.height + (i < canvases.length - 1 ? GAP : 0);
            });
            var link = document.createElement('a');
            link.download = "donut-charts-".concat(Date.now(), ".png");
            link.href = composite.toDataURL('image/png', 1);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        } catch (e) {
            var _instances_1;
            // 兜底：任意异常回退为下载第一张
            var target1 = (_instances_1 = instances[0]) !== null && _instances_1 !== void 0 ? _instances_1 : null;
            downloadChart(target1, 'donut-chart');
        }
    };
    var shouldShowFilter = filterList && filterList.length > 0 || autoCategoryData;
    var finalFilterList = filterList || (autoCategoryData ? autoCategoryData.categories : []);
    var finalSelectedFilter = selectedFilter || internalSelectedCategory;
    var finalOnFilterChange = onFilterChange || handleInternalCategoryChange;
    // 使用组件级别的 theme prop，而不是从 configs 中获取
    var chartFilterTheme = theme;
    var dimensions = useResponsiveDimensions(isMobile, windowWidth, width, height);
    var renderConfigs = singleMode && !configs ? Array.from({
        length: filteredData.length
    }, function(_, i) {
        return {
            showLegend: false,
            showTooltip: false,
            backgroundColor: [
                defaultColorList[i % defaultColorList.length],
                '#F7F8F9'
            ]
        };
    }) : finalConfigs;
    return /*#__PURE__*/ React.createElement(ChartContainer, {
        baseClassName: baseClassName,
        className: classNames(classNamesProp === null || classNamesProp === void 0 ? void 0 : classNamesProp.root, className),
        variant: props.variant,
        theme: theme,
        isMobile: isMobile,
        style: _object_spread(_define_property({}, '--donut-item-min-width', "".concat(dimensions.width, "px")), props.style, (_props_styles = props.styles) === null || _props_styles === void 0 ? void 0 : _props_styles.root)
    }, showToolbar && /*#__PURE__*/ React.createElement(ChartContainer, {
        baseClassName: "".concat(baseClassName, "-toolbar-wrapper"),
        variant: "borderless",
        theme: theme,
        isMobile: isMobile
    }, title && /*#__PURE__*/ React.createElement(ChartToolBar, {
        title: title,
        theme: chartFilterTheme,
        onDownload: handleDownload,
        extra: toolbarExtra,
        dataTime: dataTime,
        loading: loading,
        filter: renderFilterInToolbar && shouldShowFilter ? /*#__PURE__*/ React.createElement(ChartFilter, _object_spread_props(_object_spread({
            filterOptions: finalFilterList.map(function(item) {
                return {
                    label: item || '',
                    value: item || ''
                };
            }),
            selectedFilter: finalSelectedFilter || '',
            onFilterChange: finalOnFilterChange
        }, filterLabels && {
            customOptions: filteredDataByFilterLabel,
            selectedCustomSelection: selectedFilterLabel,
            onSelectionChange: setSelectedFilterLabel
        }), {
            theme: chartFilterTheme,
            variant: "compact"
        })) : undefined
    }), statistics && /*#__PURE__*/ React.createElement("div", {
        className: [
            "".concat(baseClassName, "-statistic-container"),
            hashId
        ].filter(Boolean).join(' ')
    }, statistics.map(function(config, index) {
        return /*#__PURE__*/ React.createElement(ChartStatistic, _object_spread_props(_object_spread({
            key: index
        }, config), {
            theme: chartFilterTheme
        }));
    })), !renderFilterInToolbar && shouldShowFilter && /*#__PURE__*/ React.createElement(ChartFilter, _object_spread_props(_object_spread({
        filterOptions: finalFilterList.map(function(item) {
            return {
                label: item || '',
                value: item || ''
            };
        }),
        selectedFilter: finalSelectedFilter || '',
        onFilterChange: finalOnFilterChange
    }, filterLabels && {
        customOptions: filteredDataByFilterLabel,
        selectedCustomSelection: selectedFilterLabel,
        onSelectionChange: setSelectedFilterLabel
    }), {
        theme: chartFilterTheme
    }))), /*#__PURE__*/ React.createElement(ChartContainer, {
        baseClassName: "".concat(baseClassName, "-content"),
        variant: "borderless",
        theme: theme,
        isMobile: isMobile
    }, renderConfigs.map(function(cfg, idx) {
        var _ref;
        var _cfg_backgroundColor;
        var currentDataItem = filteredData[idx];
        var isSingleValueMode = Boolean(singleMode && currentDataItem);
        var chartData = filteredData;
        if (isSingleValueMode && currentDataItem) {
            var mainValue = typeof currentDataItem.value === 'number' ? currentDataItem.value : Number(currentDataItem.value);
            var remainingValue = Math.max(0, 100 - (Number.isFinite(mainValue) ? mainValue : 0));
            chartData = [
                currentDataItem,
                {
                    label: locale['chart.legend.remaining'],
                    value: remainingValue,
                    category: currentDataItem.category
                }
            ];
        }
        var hiddenSetForChart = hiddenDataIndicesByChart[idx] || new Set();
        var visibleDataWithIndex = chartData.map(function(d, index) {
            return {
                d: d,
                originalIndex: index
            };
        }).filter(function(param) {
            var originalIndex = param.originalIndex;
            return !hiddenSetForChart.has(originalIndex);
        });
        var visibleData = visibleDataWithIndex.map(function(param) {
            var d = param.d;
            return d;
        });
        var visibleOriginalIndices = visibleDataWithIndex.map(function(param) {
            var originalIndex = param.originalIndex;
            return originalIndex;
        });
        var toNum = function toNum(v) {
            return typeof v === 'number' ? v : Number(v);
        };
        var rawLabels = visibleData.map(function(d) {
            return d.label;
        });
        var labels = isSingleValueMode ? rawLabels.map(function(labelText, i) {
            return i === 1 ? '' : labelText;
        }) : rawLabels;
        var values = visibleData.map(function(d) {
            return toNum(d.value);
        });
        var safeValues = values.map(function(v) {
            return Number.isFinite(v) ? v : 0;
        });
        var total = values.reduce(function(sum, v) {
            return sum + (Number.isFinite(v) ? v : 0);
        }, 0);
        var backgroundColors = cfg.backgroundColor || defaultColorList;
        // 解析 CSS 变量为实际颜色值（Canvas 需要实际颜色值），按原始索引取色保证与图例颜色一致
        var resolvedVisibleBackgroundColors = visibleOriginalIndices.map(function(originalIndex) {
            return resolveCssVariable(backgroundColors[originalIndex % backgroundColors.length]);
        });
        var mainColor = (_ref = (_cfg_backgroundColor = cfg.backgroundColor) === null || _cfg_backgroundColor === void 0 ? void 0 : _cfg_backgroundColor[0]) !== null && _ref !== void 0 ? _ref : defaultColorList[idx % defaultColorList.length];
        var resolvedMainColor = resolveCssVariable(mainColor);
        var isDarkTheme = !isLight;
        /** 与 ChartContainer 暗色底一致，扇区描边融进背景，避免亮白描边突兀 */ var donutDarkSegmentBorder = '#1f1f1f';
        var donutDarkSegmentBorderHover = 'rgba(255, 255, 255, 0.14)';
        var chartBorderColor = function() {
            if (isSingleValueMode) {
                if (isDarkTheme) {
                    return [
                        cfg.borderColor || 'rgba(255, 255, 255, 0.14)',
                        'transparent'
                    ];
                }
                return [
                    cfg.borderColor || '#fff',
                    'transparent'
                ];
            }
            if (cfg.chartStyle === 'pie') {
                return cfg.borderColor || '#fff';
            }
            if (isDarkTheme) {
                return donutDarkSegmentBorder;
            }
            return cfg.borderColor || '#fff';
        }();
        var chartHoverBorderColor = function() {
            if (isSingleValueMode) {
                if (isDarkTheme) {
                    return [
                        cfg.borderColor || 'rgba(255, 255, 255, 0.22)',
                        'transparent'
                    ];
                }
                return [
                    cfg.borderColor || '#fff',
                    'transparent'
                ];
            }
            if (cfg.chartStyle === 'pie') {
                return cfg.borderColor || '#fff';
            }
            if (isDarkTheme) {
                return donutDarkSegmentBorderHover;
            }
            return cfg.borderColor || '#fff';
        }();
        var chartJsData = {
            labels: labels,
            datasets: [
                {
                    data: safeValues,
                    backgroundColor: isSingleValueMode ? [
                        resolvedMainColor,
                        'transparent'
                    ] : resolvedVisibleBackgroundColors.slice(0, values.length),
                    borderColor: chartBorderColor,
                    hoverBackgroundColor: isSingleValueMode ? [
                        resolvedMainColor,
                        'transparent'
                    ] : resolvedVisibleBackgroundColors.slice(0, values.length),
                    hoverBorderColor: chartHoverBorderColor,
                    borderWidth: cfg.chartStyle === 'pie' ? 2 : isMobile ? 1 : 1,
                    spacing: isSingleValueMode ? 0 : cfg.chartStyle === 'pie' ? 0 : isDarkTheme ? isMobile ? 4 : 8 : isMobile ? 3 : 6,
                    borderRadius: cfg.chartStyle === 'pie' ? 0 : 4,
                    hoverOffset: function hoverOffset(ctx) {
                        return isSingleValueMode && (ctx === null || ctx === void 0 ? void 0 : ctx.dataIndex) === 1 ? 0 : isMobile ? 4 : 6;
                    }
                }
            ]
        };
        var cutout = function() {
            var _cfg_cutout;
            // 如果明确指定为饼图，cutout 为 0（实心）
            if (cfg.chartStyle === 'pie') {
                return 0;
            }
            // 环形图的逻辑
            if (isMobile) {
                var _cfg_cutout1;
                if (typeof cfg.cutout === 'number') return cfg.cutout * 0.9;
                return (_cfg_cutout1 = cfg.cutout) !== null && _cfg_cutout1 !== void 0 ? _cfg_cutout1 : isSingleValueMode ? SINGLE_MODE_MOBILE_CUTOUT : '70%';
            }
            return (_cfg_cutout = cfg.cutout) !== null && _cfg_cutout !== void 0 ? _cfg_cutout : isSingleValueMode ? SINGLE_MODE_DESKTOP_CUTOUT : '75%';
        }();
        var tooltipBackgroundColor = isDarkTheme ? '#1F2937' : '#FFFFFF';
        var tooltipBorderColor = isDarkTheme ? '#374151' : '#E5E7EB';
        var tooltipTitleColor = isDarkTheme ? '#F9FAFB' : '#111827';
        var tooltipBodyColor = isDarkTheme ? '#D1D5DB' : '#374151';
        var options = {
            responsive: true,
            maintainAspectRatio: false,
            cutout: cutout,
            plugins: {
                legend: {
                    display: false
                },
                /** 默认不展示扇区上的数值与占比，仅通过 configs[].showDataLabels === true 开启 */ datalabels: {
                    display: false
                },
                tooltip: {
                    enabled: cfg.showTooltip !== false,
                    filter: function filter(tooltipItem) {
                        return !(isSingleValueMode && tooltipItem.dataIndex === 1);
                    },
                    backgroundColor: tooltipBackgroundColor,
                    borderColor: tooltipBorderColor,
                    borderWidth: 1,
                    titleColor: tooltipTitleColor,
                    bodyColor: tooltipBodyColor,
                    padding: isMobile ? 8 : 12,
                    titleFont: {
                        size: isMobile ? 12 : 14
                    },
                    bodyFont: {
                        size: isMobile ? 11 : 13
                    },
                    callbacks: {
                        label: function label(param) {
                            var label = param.label, raw = param.raw;
                            var val = typeof raw === 'number' ? raw : Number(raw);
                            var pct = total > 0 && Number.isFinite(val) ? (val / total * 100).toFixed(0) : '0';
                            if (cfg.showDataLabels) {
                                return "".concat(label, ": ").concat(Number.isFinite(val) ? val : raw, " (").concat(pct, "%)");
                            }
                            return "".concat(label, " (").concat(pct, "%)");
                        }
                    }
                }
            },
            animation: {
                duration: isMobile ? 200 : 400
            },
            interaction: {
                mode: 'point',
                intersect: false
            },
            layout: {
                padding: isMobile ? 4 : 6
            }
        };
        var dataLabelOffset = isMobile ? 22 : 36;
        var optionsWithDataLabels = _object_spread_props(_object_spread({}, options, cfg.showDataLabels === true && !isSingleValueMode && {
            layout: _object_spread_props(_object_spread({}, options.layout), {
                padding: isMobile ? 36 : 52
            })
        }), {
            plugins: _object_spread({}, options.plugins, cfg.showDataLabels === true && !isSingleValueMode && {
                datalabels: {
                    display: function display(context) {
                        var _context_dataset_data, _context_dataset;
                        var value = (_context_dataset = context.dataset) === null || _context_dataset === void 0 ? void 0 : (_context_dataset_data = _context_dataset.data) === null || _context_dataset_data === void 0 ? void 0 : _context_dataset_data[context.dataIndex];
                        var numVal = typeof value === 'number' ? value : Number(value);
                        if (!Number.isFinite(numVal) || total <= 0) return false;
                        var pct = numVal / total * 100;
                        if (pct < 2) return false;
                        return true;
                    },
                    formatter: function formatter(value, context) {
                        var _context_chart_data_labels;
                        var pct = total > 0 ? (value / total * 100).toFixed(2) : '0';
                        var label = (_context_chart_data_labels = context.chart.data.labels) === null || _context_chart_data_labels === void 0 ? void 0 : _context_chart_data_labels[context.dataIndex];
                        var labelStr = label !== undefined && label !== null ? String(label) : '';
                        return labelStr ? "".concat(labelStr, ": ").concat(pct, "%") : "".concat(value, " (").concat(pct, "%)");
                    },
                    color: isDarkTheme ? '#F9FAFB' : '#343A45',
                    font: {
                        size: isMobile ? 10 : 11,
                        weight: 'normal'
                    },
                    anchor: 'end',
                    align: 'end',
                    offset: dataLabelOffset,
                    clamp: false,
                    clip: false
                }
            })
        });
        var _obj, _obj1;
        return /*#__PURE__*/ React.createElement(ChartContainer, {
            key: idx,
            baseClassName: "".concat(baseClassName, "-chart-wrapper"),
            variant: "borderless",
            theme: theme,
            isMobile: isMobile
        }, isSingleValueMode ? /*#__PURE__*/ React.createElement(ChartContainer, {
            baseClassName: "".concat(baseClassName, "-single"),
            variant: "borderless",
            theme: theme,
            isMobile: isMobile,
            style: _object_spread((_obj = {}, _define_property(_obj, '--donut-chart-height', "".concat(dimensions.height, "px")), _define_property(_obj, '--donut-chart-width', "".concat(dimensions.width, "px")), _define_property(_obj, "width", dimensions.width), _define_property(_obj, "height", dimensions.height), _define_property(_obj, "marginTop", '20px'), _obj), isMobile ? {
                margin: '0 auto'
            } : {})
        }, /*#__PURE__*/ React.createElement(Doughnut, {
            ref: function ref(instance) {
                chartRefs.current[idx] = instance;
            },
            data: chartJsData,
            options: options,
            plugins: // 只有环形图才显示中心文本和背景
            _to_consumable_array(cfg.chartStyle !== 'pie' ? [
                createCenterTextPlugin((typeof currentDataItem.value === 'number' ? currentDataItem.value : Number(currentDataItem.value)) / (total || 1) * 100, currentDataItem.label, isMobile, isDarkTheme),
                createBackgroundArcPlugin(isDarkTheme ? 'rgba(255, 255, 255, 0.08)' : '#F7F8F9')
            ] : [])
        })) : /*#__PURE__*/ React.createElement(ChartContainer, {
            baseClassName: "".concat(baseClassName, "-row"),
            variant: "borderless",
            theme: theme,
            isMobile: isMobile,
            style: _object_spread({}, isMobile ? {
                flexDirection: 'column',
                alignItems: 'stretch'
            } : {})
        }, /*#__PURE__*/ React.createElement(ChartContainer, {
            baseClassName: "".concat(baseClassName, "-chart"),
            variant: "borderless",
            theme: theme,
            isMobile: isMobile,
            style: (_obj1 = {}, _define_property(_obj1, '--donut-chart-width', "".concat(dimensions.chartWidth, "px")), _define_property(_obj1, '--donut-chart-height', "".concat(dimensions.chartHeight, "px")), _define_property(_obj1, "width", dimensions.chartWidth), _define_property(_obj1, "height", dimensions.chartHeight), _define_property(_obj1, "marginTop", '20px'), _obj1)
        }, /*#__PURE__*/ React.createElement(Doughnut, {
            ref: function ref(instance) {
                chartRefs.current[idx] = instance;
            },
            data: chartJsData,
            options: optionsWithDataLabels,
            plugins: cfg.showDataLabels === true && !isSingleValueMode ? [
                createDataLabelsLeaderLinePlugin(dataLabelOffset, isDarkTheme),
                ChartDataLabels
            ] : []
        })), cfg.showLegend && /*#__PURE__*/ React.createElement(DonutChartLegend, {
            chartData: chartData,
            backgroundColors: chartData.map(function(_, i) {
                return backgroundColors[i % backgroundColors.length];
            }),
            hiddenDataIndicesByChart: hiddenDataIndicesByChart,
            chartIndex: idx,
            onLegendItemClick: function onLegendItemClick(dataIndex) {
                return handleLegendItemClick(idx, dataIndex);
            },
            total: total,
            baseClassName: baseClassName,
            hashId: hashId,
            isMobile: isMobile,
            theme: theme
        })));
    })));
};
export default DonutChart;
