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 _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 _type_of(obj) {
    "@swc/helpers - typeof";
    return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
}
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 { BarElement, CategoryScale, Chart as ChartJS, Legend, LinearScale, Tooltip } from "chart.js";
import ChartDataLabels from "chartjs-plugin-datalabels";
import clsx from "clsx";
import React, { useContext, useEffect, useMemo, useRef, useState } from "react";
import { Bar } from "react-chartjs-2";
import { ChartContainer, ChartFilter, ChartStatistic, ChartToolBar, downloadChart } from "../components";
import { defaultColorList } from "../const";
import { useChartTheme } from "../hooks";
import { extractAndSortXValues, findDataPointByXValue, hexToRgba, resolveCssVariable, toNumber } from "../utils";
import { useStyle } from "./style";
/**
 * @fileoverview 柱状图组件文件
 *
 * 该文件提供了柱状图组件的实现，基于 Chart.js 和 react-chartjs-2。
 * 支持数据可视化、交互、配置、统计等功能。
 *
 * @author md-editor
 * @version 1.0.0
 * @since 2024
 */ var barChartComponentsRegistered = false;
// 正负柱状图颜色（与需求给定的 rgba 保持一致）
var POSITIVE_COLOR_HEX = '#388BFF'; // rgba(56, 139, 255, 1)
var NEGATIVE_COLOR_HEX = '#F78826'; // rgba(247, 136, 38, 1)
var BarChart = function BarChart(param) {
    var title = param.title, data = param.data, _param_width = param.width, width = _param_width === void 0 ? 600 : _param_width, _param_height = param.height, height = _param_height === void 0 ? 400 : _param_height, className = param.className, classNames = param.classNames, style = param.style, styles = param.styles, dataTime = param.dataTime, _param_theme = param.theme, theme = _param_theme === void 0 ? 'light' : _param_theme, color = param.color, _param_showLegend = param.showLegend, showLegend = _param_showLegend === void 0 ? true : _param_showLegend, _param_legendPosition = param.legendPosition, legendPosition = _param_legendPosition === void 0 ? 'bottom' : _param_legendPosition, _param_legendAlign = param.legendAlign, legendAlign = _param_legendAlign === void 0 ? 'start' : _param_legendAlign, _param_showGrid = param.showGrid, showGrid = _param_showGrid === void 0 ? true : _param_showGrid, _param_xPosition = param.xPosition, xPosition = _param_xPosition === void 0 ? 'bottom' : _param_xPosition, _param_yPosition = param.yPosition, yPosition = _param_yPosition === void 0 ? 'left' : _param_yPosition, _param_hiddenX = param.hiddenX, hiddenX = _param_hiddenX === void 0 ? false : _param_hiddenX, _param_hiddenY = param.hiddenY, hiddenY = _param_hiddenY === void 0 ? false : _param_hiddenY, _param_stacked = param.stacked, stacked = _param_stacked === void 0 ? false : _param_stacked, _param_indexAxis = param.indexAxis, indexAxis = _param_indexAxis === void 0 ? 'x' : _param_indexAxis, maxBarThickness = param.maxBarThickness, toolbarExtra = param.toolbarExtra, _param_renderFilterInToolbar = param.renderFilterInToolbar, renderFilterInToolbar = _param_renderFilterInToolbar === void 0 ? false : _param_renderFilterInToolbar, statisticConfig = param.statistic, variant = param.variant, _param_showDataLabels = param.showDataLabels, showDataLabels = _param_showDataLabels === void 0 ? false : _param_showDataLabels, dataLabelFormatter = param.dataLabelFormatter, chartOptions = param.chartOptions, _param_loading = param.loading, loading = _param_loading === void 0 ? false : _param_loading;
    useMemo(function() {
        if (barChartComponentsRegistered) {
            return undefined;
        }
        if (typeof window === 'undefined') {
            return undefined;
        }
        ChartJS.register(CategoryScale, LinearScale, BarElement, Tooltip, Legend);
        barChartComponentsRegistered = true;
        return undefined;
    }, []);
    var safeData = Array.isArray(data) ? data : [];
    // 响应式尺寸计算
    var _useState = _sliced_to_array(useState(typeof window !== 'undefined' ? window.innerWidth : 768), 2), windowWidth = _useState[0], setWindowWidth = _useState[1];
    var isMobile = windowWidth <= 768;
    var responsiveWidth = isMobile ? '100%' : width;
    var responsiveHeight = isMobile ? Math.min(windowWidth * 0.8, 400) : height;
    // 监听窗口大小变化
    useEffect(function() {
        var handleResize = function handleResize() {
            setWindowWidth(window.innerWidth);
        };
        if (typeof window !== 'undefined') {
            window.addEventListener('resize', handleResize);
            return function() {
                return window.removeEventListener('resize', handleResize);
            };
        }
    }, []);
    // 样式注册
    var context = useContext(ConfigProvider.ConfigContext);
    var baseClassName = context === null || context === void 0 ? void 0 : context.getPrefixCls('bar-chart-container');
    var wrapSSR = useStyle(baseClassName).wrapSSR;
    var chartRef = useRef(null);
    // 处理 ChartStatistic 组件配置
    var statistics = useMemo(function() {
        if (!statisticConfig) return null;
        return Array.isArray(statisticConfig) ? statisticConfig : [
            statisticConfig
        ];
    }, [
        statisticConfig
    ]);
    // 从数据中提取唯一的类别作为筛选选项
    var categories = useMemo(function() {
        var uniqueCategories = _to_consumable_array(new Set(safeData.map(function(item) {
            return item === null || item === void 0 ? void 0 : item.category;
        }))).filter(Boolean);
        return uniqueCategories;
    }, [
        safeData
    ]);
    // 从数据中提取 filterLabel，过滤掉 undefined 值
    var validFilterLabels = useMemo(function() {
        return safeData.map(function(item) {
            return item === null || item === void 0 ? void 0 : item.filterLabel;
        }).filter(function(filterLabel) {
            return filterLabel !== undefined;
        });
    }, [
        safeData
    ]);
    var filterLabels = useMemo(function() {
        return validFilterLabels.length > 0 ? _to_consumable_array(new Set(validFilterLabels)) : undefined;
    }, [
        validFilterLabels
    ]);
    // 状态管理
    var _useState1 = _sliced_to_array(useState(categories.find(Boolean) || ''), 2), selectedFilter = _useState1[0], setSelectedFilter = _useState1[1];
    var _useState2 = _sliced_to_array(useState(filterLabels && filterLabels.length > 0 ? filterLabels[0] : undefined), 2), selectedFilterLabel = _useState2[0], setSelectedFilterLabel = _useState2[1];
    // 当数据变化导致当前选中分类失效时，自动回退到首个有效分类或空（显示全部）
    useEffect(function() {
        if (selectedFilter && !categories.includes(selectedFilter)) {
            setSelectedFilter(categories.find(Boolean) || '');
        }
    }, [
        categories,
        selectedFilter
    ]);
    // 筛选数据
    var filteredData = useMemo(function() {
        // 先按分类与可选的 filterLabel 进行筛选
        var base = selectedFilter ? safeData.filter(function(item) {
            return item.category === selectedFilter;
        }) : safeData;
        var withFilterLabel = !filterLabels || !selectedFilterLabel ? base : base.filter(function(item) {
            return item.filterLabel === selectedFilterLabel;
        });
        // 最终统一过滤掉 x 为空（null/undefined/空字符串）的数据，避免后续 toString 报错
        return withFilterLabel.filter(function(item) {
            return item.x !== null && item.x !== undefined && item.x !== '' && String(item.x).trim() !== '';
        });
    }, [
        safeData,
        selectedFilter,
        filterLabels,
        selectedFilterLabel
    ]);
    // 从数据中提取唯一的类型
    var types = useMemo(function() {
        return _to_consumable_array(new Set(filteredData.map(function(item) {
            return item.type;
        })));
    }, [
        filteredData
    ]);
    // 从数据中提取唯一的x值 - 水平柱状图时保持原始顺序
    var xValues = useMemo(function() {
        if (indexAxis === 'y') {
            // 水平柱状图时，x是类目轴，应保持原始顺序而不排序
            var uniqueValues = _to_consumable_array(new Set(filteredData.map(function(item) {
                return item.x;
            }).filter(function(x) {
                return x !== null && x !== undefined && x !== '' && String(x).trim() !== '';
            })));
            return uniqueValues;
        }
        return extractAndSortXValues(filteredData);
    }, [
        filteredData,
        indexAxis
    ]);
    // 从数据中获取xtitle和ytitle
    var xTitle = useMemo(function() {
        var titles = _to_consumable_array(new Set(filteredData.map(function(item) {
            return item.xtitle;
        }).filter(Boolean)));
        return titles[0] || '';
    }, [
        filteredData
    ]);
    var yTitle = useMemo(function() {
        var titles = _to_consumable_array(new Set(filteredData.map(function(item) {
            return item.ytitle;
        }).filter(Boolean)));
        return titles[0] || '';
    }, [
        filteredData
    ]);
    // 是否是正负柱图（同一批次同时存在正值与负值）
    var hasPositive = useMemo(function() {
        return filteredData.some(function(item) {
            var v = typeof item.y === 'number' ? item.y : toNumber(item.y, Number.NaN);
            return Number.isFinite(v) && v > 0;
        });
    }, [
        filteredData
    ]);
    var hasNegative = useMemo(function() {
        return filteredData.some(function(item) {
            var v = typeof item.y === 'number' ? item.y : toNumber(item.y, Number.NaN);
            return Number.isFinite(v) && v < 0;
        });
    }, [
        filteredData
    ]);
    var isDiverging = hasPositive && hasNegative;
    // 构建Chart.js数据结构
    var processedData = useMemo(function() {
        var labels = xValues.map(function(x) {
            return x.toString();
        });
        var datasets = types.map(function(type, index) {
            var provided = color;
            var pickByIndex = function pickByIndex(i) {
                return Array.isArray(provided) ? provided[i] || provided[0] || defaultColorList[i % defaultColorList.length] : provided || defaultColorList[i % defaultColorList.length];
            };
            var baseColor = pickByIndex(index);
            // 解析 CSS 变量为实际颜色值（Canvas 需要实际颜色值）
            var resolvedBaseColor = resolveCssVariable(baseColor);
            var resolvedProvidedColors = Array.isArray(provided) ? provided.map(function(c) {
                return resolveCssVariable(c);
            }) : provided ? [
                resolveCssVariable(provided)
            ] : null;
            // 为每个类型收集数据点
            var typeData = xValues.map(function(x) {
                var dataPoint = findDataPointByXValue(filteredData, x, type);
                var v = dataPoint === null || dataPoint === void 0 ? void 0 : dataPoint.y;
                var n = typeof v === 'number' ? v : toNumber(v, Number.NaN);
                return Number.isFinite(n) ? n : null;
            });
            return _object_spread_props(_object_spread({
                label: type || '默认',
                data: typeData,
                borderColor: function borderColor(ctx) {
                    var parsed = ctx.parsed;
                    var value = indexAxis === 'y' ? typeof (parsed === null || parsed === void 0 ? void 0 : parsed.x) === 'number' ? parsed.x : 0 : typeof (parsed === null || parsed === void 0 ? void 0 : parsed.y) === 'number' ? parsed.y : 0;
                    var base = resolvedBaseColor;
                    if (!color && isDiverging) {
                        base = value >= 0 ? POSITIVE_COLOR_HEX : NEGATIVE_COLOR_HEX;
                    } else if (resolvedProvidedColors && isDiverging) {
                        var pos = resolvedProvidedColors[0] || resolvedBaseColor;
                        var neg = resolvedProvidedColors[1] || resolvedProvidedColors[0] || resolvedBaseColor;
                        base = value >= 0 ? pos : neg;
                    }
                    return hexToRgba(base, 0.95);
                },
                backgroundColor: function backgroundColor(ctx) {
                    var chart = ctx.chart;
                    var chartArea = chart.chartArea;
                    var parsed = ctx.parsed;
                    if (!chartArea) return hexToRgba(resolvedBaseColor, 0.6);
                    var xScale = chart.scales['x'];
                    var yScale = chart.scales['y'];
                    var startAlpha = 0.65;
                    var endAlpha = 0.95;
                    // 安全检查：确保坐标轴已正确初始化
                    if (!xScale || !yScale || typeof xScale.getPixelForValue !== 'function' || typeof yScale.getPixelForValue !== 'function') {
                        return hexToRgba(resolvedBaseColor, 0.6);
                    }
                    if (indexAxis === 'y') {
                        var value = typeof (parsed === null || parsed === void 0 ? void 0 : parsed.x) === 'number' ? parsed.x : 0;
                        var base = resolvedBaseColor;
                        if (!color && isDiverging) {
                            base = value >= 0 ? POSITIVE_COLOR_HEX : NEGATIVE_COLOR_HEX;
                        } else if (resolvedProvidedColors && isDiverging) {
                            var pos = resolvedProvidedColors[0] || resolvedBaseColor;
                            var neg = resolvedProvidedColors[1] || resolvedProvidedColors[0] || resolvedBaseColor;
                            base = value >= 0 ? pos : neg;
                        }
                        // 当值为 0 时，直接返回纯色，避免渐变范围为 0 导致的显示问题
                        if (value === 0) {
                            return hexToRgba(base, 0.75);
                        }
                        // 安全获取像素值，添加有限性检查
                        var x0 = xScale.getPixelForValue(0);
                        var x1 = xScale.getPixelForValue(value);
                        // 检查像素值是否为有限数
                        if (!Number.isFinite(x0) || !Number.isFinite(x1)) {
                            return hexToRgba(base, endAlpha);
                        }
                        // 从靠近坐标轴的零点开始，向数据端渐深
                        var gradient = chart.ctx.createLinearGradient(x0, 0, x1, 0);
                        gradient.addColorStop(0, hexToRgba(base, startAlpha));
                        gradient.addColorStop(1, hexToRgba(base, endAlpha));
                        return gradient;
                    }
                    var value1 = typeof (parsed === null || parsed === void 0 ? void 0 : parsed.y) === 'number' ? parsed.y : 0;
                    var base1 = resolvedBaseColor;
                    if (!color && isDiverging) {
                        base1 = value1 >= 0 ? POSITIVE_COLOR_HEX : NEGATIVE_COLOR_HEX;
                    } else if (resolvedProvidedColors && isDiverging) {
                        var pos1 = resolvedProvidedColors[0] || resolvedBaseColor;
                        var neg1 = resolvedProvidedColors[1] || resolvedProvidedColors[0] || resolvedBaseColor;
                        base1 = value1 >= 0 ? pos1 : neg1;
                    }
                    // 当值为 0 时，直接返回纯色，避免渐变范围为 0 导致的显示问题
                    if (value1 === 0) {
                        return hexToRgba(base1, 0.75);
                    }
                    // 安全获取像素值，添加有限性检查
                    var y0 = yScale.getPixelForValue(0);
                    var y1 = yScale.getPixelForValue(value1);
                    // 检查像素值是否为有限数
                    if (!Number.isFinite(y0) || !Number.isFinite(y1)) {
                        return hexToRgba(base1, endAlpha);
                    }
                    var gradient1 = chart.ctx.createLinearGradient(0, y0, 0, y1);
                    gradient1.addColorStop(0, hexToRgba(base1, startAlpha));
                    gradient1.addColorStop(1, hexToRgba(base1, endAlpha));
                    return gradient1;
                },
                borderWidth: 0,
                // 当设置了 maxBarThickness 时，使用较大的百分比以允许 maxBarThickness 生效
                categoryPercentage: maxBarThickness ? 1.0 : 0.7,
                barPercentage: maxBarThickness ? 1.0 : 0.8
            }, maxBarThickness && {
                maxBarThickness: maxBarThickness
            }), {
                stack: stacked ? 'stack' : undefined,
                borderRadius: function borderRadius(ctx) {
                    var rawValue = ctx === null || ctx === void 0 ? void 0 : ctx.raw;
                    var value = typeof rawValue === 'number' ? rawValue : Number(rawValue !== null && rawValue !== void 0 ? rawValue : 0);
                    var isHorizontal = indexAxis === 'y';
                    var radius = 6;
                    var chart = ctx === null || ctx === void 0 ? void 0 : ctx.chart;
                    // When stacked, only the outermost (top) segment of the same sign gets radius
                    var isTopOfStack = true;
                    if (stacked && chart) {
                        var _Math;
                        var _chart_data_datasets_dsIndex, _chart_data_datasets;
                        var dsIndex = ctx === null || ctx === void 0 ? void 0 : ctx.datasetIndex;
                        var dIndex = ctx === null || ctx === void 0 ? void 0 : ctx.dataIndex;
                        var currentStack = (_chart_data_datasets = chart.data.datasets) === null || _chart_data_datasets === void 0 ? void 0 : (_chart_data_datasets_dsIndex = _chart_data_datasets[dsIndex]) === null || _chart_data_datasets_dsIndex === void 0 ? void 0 : _chart_data_datasets_dsIndex.stack;
                        var sameStackIndexes = chart.data.datasets.map(function(_, i) {
                            return i;
                        }).filter(function(i) {
                            var _ref;
                            var _chart_data_datasets, _ds_data;
                            var ds = (_chart_data_datasets = chart.data.datasets) === null || _chart_data_datasets === void 0 ? void 0 : _chart_data_datasets[i];
                            if (!chart.isDatasetVisible(i)) return false;
                            if (currentStack) {
                                if ((ds === null || ds === void 0 ? void 0 : ds.stack) !== currentStack) return false;
                            }
                            var v = Number((_ref = ds === null || ds === void 0 ? void 0 : (_ds_data = ds.data) === null || _ds_data === void 0 ? void 0 : _ds_data[dIndex]) !== null && _ref !== void 0 ? _ref : 0);
                            return v >= 0 && value >= 0 || v < 0 && value < 0;
                        });
                        // top means the last dataset in rendering order among same sign
                        var topIndex = sameStackIndexes.length ? (_Math = Math).max.apply(_Math, _to_consumable_array(sameStackIndexes)) : dsIndex;
                        isTopOfStack = dsIndex === topIndex;
                    }
                    if (!isTopOfStack) return 0;
                    if (isHorizontal) {
                        if (value >= 0) {
                            return {
                                topRight: radius,
                                bottomRight: radius,
                                topLeft: 0,
                                bottomLeft: 0
                            };
                        } else {
                            return {
                                topLeft: radius,
                                bottomLeft: radius,
                                topRight: 0,
                                bottomRight: 0
                            };
                        }
                    } else {
                        if (value >= 0) {
                            return {
                                topLeft: radius,
                                topRight: radius,
                                bottomLeft: 0,
                                bottomRight: 0
                            };
                        } else {
                            return {
                                bottomLeft: radius,
                                bottomRight: radius,
                                topLeft: 0,
                                topRight: 0
                            };
                        }
                    }
                },
                borderSkipped: false
            });
        });
        return {
            labels: labels,
            datasets: datasets
        };
    }, [
        filteredData,
        types,
        xValues,
        stacked,
        indexAxis,
        maxBarThickness
    ]);
    // 筛选器选项
    var filterOptions = useMemo(function() {
        return categories.map(function(category) {
            return {
                label: category || '默认',
                value: category || '默认'
            };
        });
    }, [
        categories
    ]);
    // 根据 filterLabel 筛选数据 - 只有当 filterLabels 存在时才生成
    var filteredDataByFilterLabel = useMemo(function() {
        return filterLabels === null || filterLabels === void 0 ? void 0 : filterLabels.map(function(item) {
            return {
                key: item,
                label: item
            };
        });
    }, [
        filterLabels
    ]);
    // 使用 useChartTheme hook 获取主题相关颜色
    var _useChartTheme = useChartTheme(theme), axisTextColor = _useChartTheme.axisTextColor, gridColor = _useChartTheme.gridColor, isLight = _useChartTheme.isLight;
    // 标签宽度计算函数
    var calculateLabelWidth = function calculateLabelWidth(text) {
        var fontSize = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 11;
        // 创建临时canvas来测量文本宽度
        try {
            var canvas = document.createElement('canvas');
            var context = canvas.getContext('2d');
            if (!context) return text.length * fontSize * 0.6; // 备用估算
            context.font = "".concat(fontSize, "px Arial, sans-serif");
            var metrics = context.measureText(text);
            return metrics.width;
        } catch (e) {
            // 在测试环境或无法使用 canvas 时使用备用估算
            return text.length * fontSize * 0.6;
        }
    };
    // 计算所需的最大标签宽度
    var calculateMaxLabelWidth = useMemo(function() {
        if (!showDataLabels || !filteredData.length) return 0;
        var fontSize = isMobile ? 10 : 11;
        var maxWidth = 0;
        // 遍历所有数据点，计算标签文本的最大宽度
        filteredData.forEach(function(item) {
            var value = typeof item.y === 'number' ? item.y : toNumber(item.y, Number.NaN);
            if (Number.isFinite(value)) {
                var labelText = '';
                if (dataLabelFormatter) {
                    labelText = dataLabelFormatter({
                        value: value,
                        label: String(item.x),
                        datasetLabel: String(item.type || '默认'),
                        dataIndex: 0,
                        datasetIndex: 0
                    });
                } else {
                    // 使用默认格式化
                    labelText = value.toLocaleString();
                }
                var width = calculateLabelWidth(labelText, fontSize);
                maxWidth = Math.max(maxWidth, width);
            }
        });
        return maxWidth;
    }, [
        filteredData,
        showDataLabels,
        dataLabelFormatter,
        isMobile
    ]);
    // 计算动态padding
    var calculateDynamicPadding = useMemo(function() {
        if (!showDataLabels || calculateMaxLabelWidth === 0) return {
            top: 0,
            right: 0,
            bottom: 0,
            left: 0
        };
        var basePadding = 8; // 基础padding
        var labelPadding = Math.ceil(calculateMaxLabelWidth) + 12; // 标签宽度 + 额外间距
        if (indexAxis === 'y') {
            // 水平柱状图：标签在右侧，需要增加右侧padding
            return {
                top: basePadding,
                right: Math.max(basePadding, labelPadding),
                bottom: basePadding,
                left: basePadding
            };
        } else {
            // 垂直柱状图：标签在上方，需要增加上方padding
            return {
                top: Math.max(basePadding, labelPadding),
                right: basePadding,
                bottom: basePadding,
                left: basePadding
            };
        }
    }, [
        showDataLabels,
        calculateMaxLabelWidth,
        indexAxis
    ]);
    // 深度合并函数
    var deepMerge = function deepMerge1(target, source) {
        if (!source || (typeof source === "undefined" ? "undefined" : _type_of(source)) !== 'object') return source;
        if (!target || (typeof target === "undefined" ? "undefined" : _type_of(target)) !== 'object') return source;
        var result = _object_spread({}, target);
        for(var key in source){
            if (source.hasOwnProperty(key)) {
                if (_type_of(source[key]) === 'object' && source[key] !== null && !Array.isArray(source[key])) {
                    var _target_layout;
                    // 特殊处理layout.padding，确保动态计算的padding不被覆盖
                    if (key === 'layout' && source[key].padding && ((_target_layout = target.layout) === null || _target_layout === void 0 ? void 0 : _target_layout.padding)) {
                        result[key] = _object_spread_props(_object_spread({}, target[key], source[key]), {
                            padding: _object_spread({}, target[key].padding, source[key].padding)
                        });
                    } else {
                        result[key] = deepMerge(target[key] || {}, source[key]);
                    }
                } else {
                    result[key] = source[key];
                }
            }
        }
        return result;
    };
    var defaultOptions = {
        responsive: true,
        maintainAspectRatio: false,
        indexAxis: indexAxis,
        layout: {
            padding: calculateDynamicPadding
        },
        plugins: _object_spread({
            legend: {
                display: showLegend,
                position: legendPosition,
                align: legendAlign,
                labels: {
                    color: axisTextColor,
                    font: {
                        size: isMobile ? 10 : 12,
                        weight: 'normal'
                    },
                    padding: isMobile ? 10 : 12,
                    usePointStyle: true,
                    pointStyle: 'rectRounded'
                }
            },
            tooltip: {
                backgroundColor: isLight ? 'rgba(255,255,255,0.95)' : 'rgba(0,0,0,0.85)',
                titleColor: isLight ? '#333' : '#fff',
                bodyColor: isLight ? '#333' : '#fff',
                borderColor: isLight ? 'rgba(0,0,0,0.12)' : 'rgba(255,255,255,0.2)',
                borderWidth: 1,
                cornerRadius: isMobile ? 6 : 8,
                displayColors: true
            }
        }, ChartDataLabels && {
            datalabels: {
                display: function display(context) {
                    if (!showDataLabels) return false;
                    // 堆叠图：只在可见数据集中最后一个显示标签（显示累计总和）
                    if (stacked) {
                        var _Math;
                        var _ref;
                        var _chart_data_datasets_dsIndex, _chart_data_datasets, _chart_data_datasets_dsIndex_data, _chart_data_datasets_dsIndex1, _chart_data_datasets1;
                        var chart = context.chart;
                        var dsIndex = context.datasetIndex;
                        var dIndex = context.dataIndex;
                        var currentStack = (_chart_data_datasets = chart.data.datasets) === null || _chart_data_datasets === void 0 ? void 0 : (_chart_data_datasets_dsIndex = _chart_data_datasets[dsIndex]) === null || _chart_data_datasets_dsIndex === void 0 ? void 0 : _chart_data_datasets_dsIndex.stack;
                        // 获取当前数据点的值，用于判断正负
                        var currentValue = Number((_ref = (_chart_data_datasets1 = chart.data.datasets) === null || _chart_data_datasets1 === void 0 ? void 0 : (_chart_data_datasets_dsIndex1 = _chart_data_datasets1[dsIndex]) === null || _chart_data_datasets_dsIndex1 === void 0 ? void 0 : (_chart_data_datasets_dsIndex_data = _chart_data_datasets_dsIndex1.data) === null || _chart_data_datasets_dsIndex_data === void 0 ? void 0 : _chart_data_datasets_dsIndex_data[dIndex]) !== null && _ref !== void 0 ? _ref : 0);
                        // 找出所有可见的、同一堆叠、同一符号（正/负）的数据集索引
                        var sameStackIndexes = chart.data.datasets.map(function(_, i) {
                            return i;
                        }).filter(function(i) {
                            var _ref;
                            var _chart_data_datasets, _ds_data;
                            var ds = (_chart_data_datasets = chart.data.datasets) === null || _chart_data_datasets === void 0 ? void 0 : _chart_data_datasets[i];
                            // 检查数据集是否可见
                            if (!chart.isDatasetVisible(i)) return false;
                            // 检查是否属于同一堆叠
                            if (currentStack && (ds === null || ds === void 0 ? void 0 : ds.stack) !== currentStack) return false;
                            // 检查该位置的值是否与当前值同号（正/负）
                            var v = Number((_ref = ds === null || ds === void 0 ? void 0 : (_ds_data = ds.data) === null || _ds_data === void 0 ? void 0 : _ds_data[dIndex]) !== null && _ref !== void 0 ? _ref : 0);
                            return v >= 0 && currentValue >= 0 || v < 0 && currentValue < 0;
                        });
                        // 只在可见数据集中的最后一个显示标签
                        var topIndex = sameStackIndexes.length ? (_Math = Math).max.apply(_Math, _to_consumable_array(sameStackIndexes)) : dsIndex;
                        return dsIndex === topIndex;
                    }
                    // 非堆叠图：显示所有标签
                    return true;
                },
                anchor: indexAxis === 'y' ? 'end' : 'end',
                align: indexAxis === 'y' ? 'end' : 'top',
                offset: 4,
                color: axisTextColor,
                font: {
                    size: isMobile ? 10 : 11,
                    weight: 'normal'
                },
                formatter: function formatter(value, context) {
                    var _context_chart_data_labels;
                    if (value === null || value === undefined) return '';
                    var dataIndex = context.dataIndex;
                    var datasetIndex = context.datasetIndex;
                    var labelValue = (_context_chart_data_labels = context.chart.data.labels) === null || _context_chart_data_labels === void 0 ? void 0 : _context_chart_data_labels[dataIndex];
                    var label = typeof labelValue === 'string' || typeof labelValue === 'number' ? labelValue : String(labelValue || '');
                    var datasetLabel = String(context.dataset.label || '');
                    // 堆叠图：计算并显示该位置的可见数据集累计总和
                    if (stacked) {
                        var _ref;
                        var _datasets_datasetIndex_data, _datasets_datasetIndex, _datasets_datasetIndex1;
                        var chart = context.chart;
                        var datasets = chart.data.datasets;
                        var currentValue = Number((_ref = datasets === null || datasets === void 0 ? void 0 : (_datasets_datasetIndex = datasets[datasetIndex]) === null || _datasets_datasetIndex === void 0 ? void 0 : (_datasets_datasetIndex_data = _datasets_datasetIndex.data) === null || _datasets_datasetIndex_data === void 0 ? void 0 : _datasets_datasetIndex_data[dataIndex]) !== null && _ref !== void 0 ? _ref : 0);
                        var currentStack = datasets === null || datasets === void 0 ? void 0 : (_datasets_datasetIndex1 = datasets[datasetIndex]) === null || _datasets_datasetIndex1 === void 0 ? void 0 : _datasets_datasetIndex1.stack;
                        // 只累加可见的、同一堆叠、同一符号的数据集
                        var total = 0;
                        datasets.forEach(function(dataset, i) {
                            // 检查数据集是否可见
                            if (!chart.isDatasetVisible(i)) return;
                            // 检查是否属于同一堆叠
                            if (currentStack && (dataset === null || dataset === void 0 ? void 0 : dataset.stack) !== currentStack) return;
                            var val = dataset.data[dataIndex];
                            if (val !== null && val !== undefined) {
                                var numVal = Number(val);
                                // 只累加与当前值同号的数据
                                if (numVal >= 0 && currentValue >= 0 || numVal < 0 && currentValue < 0) {
                                    total += numVal;
                                }
                            }
                        });
                        if (dataLabelFormatter) {
                            return dataLabelFormatter({
                                value: total,
                                label: label,
                                datasetLabel: datasetLabel,
                                dataIndex: dataIndex,
                                datasetIndex: datasetIndex
                            });
                        }
                        return total.toLocaleString();
                    }
                    // 非堆叠图：显示原始值
                    if (dataLabelFormatter) {
                        return dataLabelFormatter({
                            value: value,
                            label: label,
                            datasetLabel: datasetLabel,
                            dataIndex: dataIndex,
                            datasetIndex: datasetIndex
                        });
                    }
                    return value.toLocaleString();
                }
            }
        }),
        scales: {
            x: {
                display: !hiddenX,
                stacked: stacked,
                position: xPosition,
                title: {
                    display: !!xTitle,
                    text: xTitle,
                    color: axisTextColor,
                    font: {
                        size: isMobile ? 10 : 12,
                        weight: 'normal'
                    },
                    align: 'end'
                },
                grid: {
                    display: showGrid,
                    color: gridColor,
                    lineWidth: 1,
                    drawTicks: false,
                    tickLength: 0
                },
                ticks: {
                    color: axisTextColor,
                    font: {
                        size: isMobile ? 10 : 12
                    },
                    padding: isMobile ? 10 : 12
                },
                border: {
                    color: gridColor
                }
            },
            y: {
                display: !hiddenY,
                stacked: stacked,
                position: yPosition,
                beginAtZero: true,
                title: {
                    display: !!yTitle,
                    text: yTitle,
                    color: axisTextColor,
                    font: {
                        size: isMobile ? 10 : 12,
                        weight: 'normal'
                    },
                    align: 'end'
                },
                grid: {
                    display: showGrid,
                    color: gridColor,
                    lineWidth: 1,
                    drawTicks: false,
                    tickLength: 0
                },
                ticks: {
                    color: axisTextColor,
                    font: {
                        size: isMobile ? 10 : 12
                    },
                    padding: isMobile ? 10 : 12
                },
                border: {
                    color: gridColor
                }
            }
        },
        animation: {
            duration: isMobile ? 200 : 400
        }
    };
    // 合并外部传入的选项与默认选项
    var options = chartOptions ? deepMerge(defaultOptions, chartOptions) : defaultOptions;
    var handleDownload = function handleDownload() {
        downloadChart(chartRef.current, 'bar-chart');
    };
    var rootClassName = clsx(classNames === null || classNames === void 0 ? void 0 : classNames.root, className);
    var rootStyle = _object_spread({
        width: responsiveWidth,
        height: responsiveHeight
    }, style, styles === null || styles === void 0 ? void 0 : styles.root);
    var toolbarClassName = clsx(classNames === null || classNames === void 0 ? void 0 : classNames.toolbar);
    var toolbarStyle = styles === null || styles === void 0 ? void 0 : styles.toolbar;
    var statisticContainerClassName = clsx(classNames === null || classNames === void 0 ? void 0 : classNames.statisticContainer, "".concat(baseClassName, "-statistic-container"));
    var statisticContainerStyle = styles === null || styles === void 0 ? void 0 : styles.statisticContainer;
    var filterClassName = clsx(classNames === null || classNames === void 0 ? void 0 : classNames.filter);
    var filterStyle = styles === null || styles === void 0 ? void 0 : styles.filter;
    var wrapperClassName = clsx(classNames === null || classNames === void 0 ? void 0 : classNames.wrapper, "".concat(baseClassName, "-wrapper"));
    var wrapperStyle = _object_spread({
        marginTop: '20px',
        height: responsiveHeight
    }, styles === null || styles === void 0 ? void 0 : styles.wrapper);
    return wrapSSR(/*#__PURE__*/ React.createElement(ChartContainer, {
        baseClassName: baseClassName,
        className: rootClassName,
        theme: theme,
        isMobile: isMobile,
        variant: variant,
        style: rootStyle
    }, /*#__PURE__*/ React.createElement(ChartToolBar, {
        title: title,
        theme: theme,
        onDownload: handleDownload,
        extra: toolbarExtra,
        dataTime: dataTime,
        loading: loading,
        className: toolbarClassName,
        style: toolbarStyle,
        filter: renderFilterInToolbar && filterOptions && filterOptions.length > 1 ? /*#__PURE__*/ React.createElement(ChartFilter, _object_spread_props(_object_spread({
            filterOptions: filterOptions,
            selectedFilter: selectedFilter,
            onFilterChange: setSelectedFilter
        }, filterLabels && {
            customOptions: filteredDataByFilterLabel,
            selectedCustomSelection: selectedFilterLabel,
            onSelectionChange: setSelectedFilterLabel
        }), {
            theme: theme,
            variant: "compact",
            className: filterClassName,
            style: filterStyle
        })) : undefined
    }), statistics && /*#__PURE__*/ React.createElement("div", {
        className: statisticContainerClassName,
        style: statisticContainerStyle
    }, statistics.map(function(config, index) {
        return /*#__PURE__*/ React.createElement(ChartStatistic, _object_spread_props(_object_spread({
            key: index
        }, config), {
            theme: theme
        }));
    })), !renderFilterInToolbar && filterOptions && filterOptions.length > 1 && /*#__PURE__*/ React.createElement(ChartFilter, _object_spread_props(_object_spread({
        filterOptions: filterOptions,
        selectedFilter: selectedFilter,
        onFilterChange: setSelectedFilter
    }, filterLabels && {
        customOptions: filteredDataByFilterLabel,
        selectedCustomSelection: selectedFilterLabel,
        onSelectionChange: setSelectedFilterLabel
    }), {
        theme: theme,
        className: filterClassName,
        style: filterStyle
    })), /*#__PURE__*/ React.createElement("div", {
        className: wrapperClassName,
        style: wrapperStyle
    }, /*#__PURE__*/ React.createElement(Bar, {
        ref: chartRef,
        data: processedData,
        options: options,
        plugins: [
            ChartDataLabels
        ]
    }))));
};
export default BarChart;
