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 _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 { CategoryScale, Chart as ChartJS, Filler, Legend, LinearScale, LineElement, PointElement, Tooltip } from "chart.js";
import classNames from "classnames";
import React, { useContext, useEffect, useMemo, useRef, useState } from "react";
import { Line } from "react-chartjs-2";
import { ChartContainer, ChartFilter, ChartStatistic, ChartToolBar, downloadChart } from "../components";
import { defaultColorList } from "../const";
import { extractAndSortXValues, findDataPointByXValue } from "../utils";
import { useStyle } from "./style";
/**
 * @fileoverview 面积图组件文件
 *
 * 该文件提供了面积图组件的实现，基于 Chart.js 和 react-chartjs-2。
 * 支持数据可视化、交互、配置、统计等功能。
 *
 * @author md-editor
 * @version 1.0.0
 * @since 2024
 */ var areaChartComponentsRegistered = false;
/**
 * 将十六进制颜色转换为带透明度的 RGBA 字符串
 *
 * 支持3位和6位十六进制颜色格式，并添加透明度。
 *
 * @param {string} hex - 十六进制颜色值（如 '#ff0000' 或 '#f00'）
 * @param {number} alpha - 透明度值（0-1之间）
 * @returns {string} RGBA 颜色字符串
 *
 * @example
 * ```typescript
 * hexToRgba('#ff0000', 0.5); // 'rgba(255, 0, 0, 0.5)'
 * hexToRgba('#f00', 0.8); // 'rgba(255, 0, 0, 0.8)'
 * ```
 *
 * @since 1.0.0
 */ var hexToRgba = function(hex, alpha) {
    var sanitized = hex.replace('#', '');
    var isShort = sanitized.length === 3;
    var r = parseInt(isShort ? sanitized[0] + sanitized[0] : sanitized.slice(0, 2), 16);
    var g = parseInt(isShort ? sanitized[1] + sanitized[1] : sanitized.slice(2, 4), 16);
    var b = parseInt(isShort ? sanitized[2] + sanitized[2] : sanitized.slice(4, 6), 16);
    var a = Math.max(0, Math.min(1, alpha));
    return "rgba(".concat(r, ", ").concat(g, ", ").concat(b, ", ").concat(a, ")");
};
/**
 * 面积图组件
 *
 * 基于 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, 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;
    useMemo(function() {
        if (areaChartComponentsRegistered) {
            return undefined;
        }
        if (typeof window === 'undefined') {
            return undefined;
        }
        ChartJS.register(CategoryScale, LinearScale, PointElement, LineElement, Filler, Tooltip, Legend);
        areaChartComponentsRegistered = 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() {
            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('area-chart-container');
    var _useStyle = useStyle(baseClassName), wrapSSR = _useStyle.wrapSSR, hashId = _useStyle.hashId;
    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.category;
        }))).filter(Boolean);
        return uniqueCategories;
    }, [
        safeData
    ]);
    // 从数据中提取 filterLabel，过滤掉 undefined 值
    var validFilterLabels = useMemo(function() {
        return safeData.map(function(item) {
            return 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() {
        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;
        });
    }, [
        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() {
        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];
            // 为每个类型收集数据点
            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: baseColor,
                backgroundColor: function(ctx) {
                    var chart = ctx.chart;
                    var chartArea = chart.chartArea;
                    if (!chartArea) return hexToRgba(baseColor, 0.2);
                    var top = chartArea.top, bottom = chartArea.bottom;
                    var gradient = chart.ctx.createLinearGradient(0, top, 0, bottom);
                    // 顶部颜色更实，向下逐渐透明，形成柔和的面积过渡
                    gradient.addColorStop(0, hexToRgba(baseColor, 0.28));
                    gradient.addColorStop(1, hexToRgba(baseColor, 0.05));
                    return gradient;
                },
                pointBackgroundColor: baseColor,
                pointBorderColor: '#fff',
                pointBorderWidth: 1,
                borderWidth: 3,
                tension: 0,
                fill: true
            };
        });
        return {
            labels: labels,
            datasets: datasets
        };
    }, [
        filteredData,
        types,
        xValues
    ]);
    // 筛选器选项
    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
    ]);
    var isLight = theme === 'light';
    var axisTextColor = isLight ? 'rgba(0, 25, 61, 0.3255)' : 'rgba(255, 255, 255, 0.8)';
    var gridColor = isLight ? 'rgba(0,0,0,0.08)' : 'rgba(255,255,255,0.2)';
    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
            }
        }
    };
    var handleDownload = function() {
        downloadChart(chartRef.current, 'area-chart');
    };
    return wrapSSR(/*#__PURE__*/ React.createElement(ChartContainer, {
        baseClassName: baseClassName,
        className: className,
        theme: theme,
        isMobile: isMobile,
        variant: variant,
        style: {
            width: responsiveWidth,
            height: responsiveHeight
        }
    }, /*#__PURE__*/ React.createElement(ChartToolBar, {
        title: title,
        theme: theme,
        onDownload: handleDownload,
        extra: toolbarExtra,
        dataTime: dataTime,
        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;
