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_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 _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 _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 classNames from "classnames";
import React, { useContext, useMemo, useRef } from "react";
import { Line } from "react-chartjs-2";
import { ChartContainer, ChartFilter, ChartStatistic, ChartToolBar, downloadChart } from "../components";
import { defaultColorList } from "../const";
import { useChartDataFilter, useChartStatistics, useChartTheme, useResponsiveSize } from "../hooks";
import { extractAndSortXValues, findDataPointByXValue, hexToRgba, registerLineChartComponents, resolveCssVariable } from "../utils";
import { useStyle } from "./style";
/**
 * 面积图组件
 *
 * 基于 Chart.js 和 react-chartjs-2 实现的面积图组件。
 * 支持数据可视化、交互、配置、统计等功能。
 *
 * @component
 * @param {AreaChartProps} props - 组件属性
 * @returns {React.ReactElement} 面积图组件
 *
 * @example
 * ```tsx
 * <AreaChart
 *   title="销售趋势"
 *   data={[
 *     { x: '2024-01', y: 100, type: '产品A' },
 *     { x: '2024-02', y: 150, type: '产品A' }
 *   ]}
 *   width={800}
 *   height={400}
 *   showLegend={true}
 *   showGrid={true}
 * />
 * ```
 *
 * @since 1.0.0
 */ var AreaChart = function(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, classNamesProp = param.classNames, style = param.style, stylesProp = 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, toolbarExtra = param.toolbarExtra, _param_renderFilterInToolbar = param.renderFilterInToolbar, renderFilterInToolbar = _param_renderFilterInToolbar === void 0 ? false : _param_renderFilterInToolbar, statisticConfig = param.statistic, variant = param.variant, _param_loading = param.loading, loading = _param_loading === void 0 ? false : _param_loading;
    // 注册 Chart.js 组件
    registerLineChartComponents();
    // 响应式尺寸
    var _useResponsiveSize = useResponsiveSize(width, height), responsiveWidth = _useResponsiveSize.responsiveWidth, responsiveHeight = _useResponsiveSize.responsiveHeight, isMobile = _useResponsiveSize.isMobile;
    // 样式注册
    var context = useContext(ConfigProvider.ConfigContext);
    var baseClassName = context === null || context === void 0 ? void 0 : context.getPrefixCls('area-chart-container');
    var _useStyle = useStyle(baseClassName), wrapSSR = _useStyle.wrapSSR, hashId = _useStyle.hashId;
    var chartRef = useRef(null);
    // 处理 ChartStatistic 组件配置
    var statistics = useChartStatistics(statisticConfig);
    // 数据筛选
    var _useChartDataFilter = useChartDataFilter(data), filteredData = _useChartDataFilter.filteredData, filterOptions = _useChartDataFilter.filterOptions, filterLabels = _useChartDataFilter.filterLabels, selectedFilter = _useChartDataFilter.selectedFilter, setSelectedFilter = _useChartDataFilter.setSelectedFilter, selectedFilterLabel = _useChartDataFilter.selectedFilterLabel, setSelectedFilterLabel = _useChartDataFilter.setSelectedFilterLabel, filteredDataByFilterLabel = _useChartDataFilter.filteredDataByFilterLabel;
    // 主题颜色
    var _useChartTheme = useChartTheme(theme), axisTextColor = _useChartTheme.axisTextColor, gridColor = _useChartTheme.gridColor, isLight = _useChartTheme.isLight;
    // 从数据中提取唯一的类型
    var types = useMemo(function() {
        return _to_consumable_array(new Set(filteredData.map(function(item) {
            return item.type;
        })));
    }, [
        filteredData
    ]);
    // 从数据中提取唯一的x值并排序
    var xValues = useMemo(function() {
        return extractAndSortXValues(filteredData);
    }, [
        filteredData
    ]);
    // 从数据中获取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
    ]);
    // 构建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 baseColor = Array.isArray(provided) ? provided[index % provided.length] || defaultColorList[index % defaultColorList.length] : provided || defaultColorList[index % defaultColorList.length];
            // 解析 CSS 变量为实际颜色值（Canvas 需要实际颜色值）
            var resolvedColor = resolveCssVariable(baseColor);
            // 为每个类型收集数据点
            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 : Number(v);
                return Number.isFinite(n) ? n : null;
            });
            return {
                label: type || '默认',
                data: typeData,
                borderColor: resolvedColor,
                backgroundColor: function(ctx) {
                    var chart = ctx.chart;
                    var chartArea = chart.chartArea;
                    // 对于所有颜色（包括解析后的 CSS 变量），使用渐变效果
                    if (!chartArea) return hexToRgba(resolvedColor, 0.2);
                    var top = chartArea.top, bottom = chartArea.bottom;
                    var gradient = chart.ctx.createLinearGradient(0, top, 0, bottom);
                    // 顶部颜色更实，向下逐渐透明，形成柔和的面积过渡
                    gradient.addColorStop(0, hexToRgba(resolvedColor, 0.28));
                    gradient.addColorStop(1, hexToRgba(resolvedColor, 0.05));
                    return gradient;
                },
                pointBackgroundColor: resolvedColor,
                pointBorderColor: '#fff',
                pointBorderWidth: 1,
                borderWidth: 3,
                tension: 0,
                fill: true
            };
        });
        return {
            labels: labels,
            datasets: datasets
        };
    }, [
        filteredData,
        types,
        xValues,
        color
    ]);
    var options = {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            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: {
                // 与交互保持一致：不要求点相交，并按 x 索引联动
                intersect: false,
                mode: 'index',
                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,
                callbacks: {
                    label: function(context) {
                        var label = context.dataset.label || '';
                        var y = context.parsed.y;
                        return "".concat(label, ": ").concat(y);
                    }
                }
            }
        },
        scales: {
            x: {
                display: !hiddenX,
                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,
                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
                }
            }
        },
        elements: {
            point: {
                radius: isMobile ? 2 : 3,
                hoverRadius: isMobile ? 3 : 5,
                borderWidth: isMobile ? 1 : 2,
                hoverBorderWidth: isMobile ? 1 : 2
            },
            line: {
                borderWidth: 3
            }
        },
        animation: {
            duration: isMobile ? 200 : 400
        }
    };
    var handleDownload = function() {
        downloadChart(chartRef.current, 'area-chart');
    };
    var rootClassName = classNames(classNamesProp === null || classNamesProp === void 0 ? void 0 : classNamesProp.root, className);
    var rootStyle = _object_spread({
        width: responsiveWidth,
        height: responsiveHeight
    }, style, stylesProp === null || stylesProp === void 0 ? void 0 : stylesProp.root);
    var toolbarClassName = classNames(classNamesProp === null || classNamesProp === void 0 ? void 0 : classNamesProp.toolbar);
    var toolbarStyle = stylesProp === null || stylesProp === void 0 ? void 0 : stylesProp.toolbar;
    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,
        className: toolbarClassName,
        style: toolbarStyle,
        extra: toolbarExtra,
        dataTime: dataTime,
        loading: loading,
        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"
        })) : undefined
    }), statistics && /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(baseClassName, "-statistic-container"), hashId)
    }, 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
    })), /*#__PURE__*/ React.createElement("div", {
        className: "".concat(baseClassName, "-wrapper"),
        style: {
            marginTop: '20px',
            height: responsiveHeight
        }
    }, /*#__PURE__*/ React.createElement(Line, {
        ref: chartRef,
        data: processedData,
        options: options
    }))));
};
export default AreaChart;
