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 _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 _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 "clsx";
import React, { useContext, useLayoutEffect, 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, useDetectTheme, useResponsiveSize } from "../hooks";
import { extractAndSortXValues, findDataPointByXValue, hexToRgba, registerLineChartComponents, resolveCssVariable } from "../utils";
import { useStyle } from "./style";
var LineChart = function LineChart(_0) {
    var title = _0.title, data = _0.data, _0_width = _0.width, width = _0_width === void 0 ? 600 : _0_width, _0_height = _0.height, height = _0_height === void 0 ? 400 : _0_height, className = _0.className, classNamesProp = _0.classNames, dataTime = _0.dataTime, theme = _0.theme, color = _0.color, _0_showLegend = _0.showLegend, showLegend = _0_showLegend === void 0 ? true : _0_showLegend, _0_legendPosition = _0.legendPosition, legendPosition = _0_legendPosition === void 0 ? 'bottom' : _0_legendPosition, _0_legendAlign = _0.legendAlign, legendAlign = _0_legendAlign === void 0 ? 'start' : _0_legendAlign, _0_showGrid = _0.showGrid, showGrid = _0_showGrid === void 0 ? true : _0_showGrid, _0_xPosition = _0.xPosition, xPosition = _0_xPosition === void 0 ? 'bottom' : _0_xPosition, _0_yPosition = _0.yPosition, yPosition = _0_yPosition === void 0 ? 'left' : _0_yPosition, _0_hiddenX = _0.hiddenX, hiddenX = _0_hiddenX === void 0 ? false : _0_hiddenX, _0_hiddenY = _0.hiddenY, hiddenY = _0_hiddenY === void 0 ? false : _0_hiddenY, 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, [
        "title",
        "data",
        "width",
        "height",
        "className",
        "classNames",
        "dataTime",
        "theme",
        "color",
        "showLegend",
        "legendPosition",
        "legendAlign",
        "showGrid",
        "xPosition",
        "yPosition",
        "hiddenX",
        "hiddenY",
        "toolbarExtra",
        "renderFilterInToolbar",
        "statistic",
        "loading"
    ]);
    var _props_styles, _props_styles1;
    // 注册 Chart.js 组件
    useLayoutEffect(function() {
        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('line-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 detectedTheme = useDetectTheme();
    var resolvedTheme = theme !== null && theme !== void 0 ? theme : detectedTheme;
    var _useChartTheme = useChartTheme(resolvedTheme), 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: hexToRgba(resolvedColor, 0.2),
                pointBackgroundColor: resolvedColor,
                pointBorderColor: isLight ? '#fff' : resolvedColor,
                pointBorderWidth: isLight ? 1 : 0,
                borderWidth: 3,
                tension: 0,
                fill: false
            };
        });
        return {
            labels: labels,
            datasets: datasets
        };
    }, [
        filteredData,
        types,
        xValues,
        color,
        isLight
    ]);
    var options = {
        responsive: true,
        maintainAspectRatio: false,
        // 允许在任意垂直方向的区域悬停时触发同一 x 索引的数据提示
        interaction: {
            mode: 'index',
            intersect: false,
            axis: 'x'
        },
        plugins: {
            legend: {
                display: showLegend && types.length > 0,
                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,
                callbacks: {
                    label: function label(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 handleDownload() {
        downloadChart(chartRef.current, 'line-chart');
    };
    var rootClassName = classNames(classNamesProp === null || classNamesProp === void 0 ? void 0 : classNamesProp.root, className);
    var rootStyle = _object_spread({
        width: responsiveWidth
    }, props.style, (_props_styles = props.styles) === null || _props_styles === void 0 ? void 0 : _props_styles.root);
    var toolbarClassName = classNames(classNamesProp === null || classNamesProp === void 0 ? void 0 : classNamesProp.toolbar);
    var toolbarStyle = (_props_styles1 = props.styles) === null || _props_styles1 === void 0 ? void 0 : _props_styles1.toolbar;
    return wrapSSR(/*#__PURE__*/ React.createElement(ChartContainer, {
        baseClassName: baseClassName,
        className: rootClassName,
        theme: resolvedTheme,
        isMobile: isMobile,
        variant: props.variant,
        style: rootStyle
    }, /*#__PURE__*/ React.createElement(ChartToolBar, {
        title: title,
        theme: resolvedTheme,
        className: toolbarClassName,
        style: toolbarStyle,
        onDownload: handleDownload,
        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: resolvedTheme,
            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: resolvedTheme
        }));
    })), !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: resolvedTheme
    })), /*#__PURE__*/ React.createElement("div", {
        className: "".concat(baseClassName, "-wrapper"),
        style: {
            height: responsiveHeight
        }
    }, /*#__PURE__*/ React.createElement(Line, {
        ref: chartRef,
        data: processedData,
        options: options
    }))));
};
export default LineChart;
