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 _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_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 _object_spread(target) {
    for(var i = 1; i < arguments.length; i++){
        var source = arguments[i] != null ? arguments[i] : {};
        var ownKeys = Object.keys(source);
        if (typeof Object.getOwnPropertySymbols === "function") {
            ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
                return Object.getOwnPropertyDescriptor(source, sym).enumerable;
            }));
        }
        ownKeys.forEach(function(key) {
            _define_property(target, key, source[key]);
        });
    }
    return target;
}
function ownKeys(object, enumerableOnly) {
    var keys = Object.keys(object);
    if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object);
        if (enumerableOnly) {
            symbols = symbols.filter(function(sym) {
                return Object.getOwnPropertyDescriptor(object, sym).enumerable;
            });
        }
        keys.push.apply(keys, symbols);
    }
    return keys;
}
function _object_spread_props(target, source) {
    source = source != null ? source : {};
    if (Object.getOwnPropertyDescriptors) {
        Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
        ownKeys(Object(source)).forEach(function(key) {
            Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
        });
    }
    return target;
}
function _object_without_properties(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys, key, i;
    if (typeof Reflect !== "undefined" && Reflect.ownKeys) {
        sourceKeys = Reflect.ownKeys(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
        return target;
    }
    target = _object_without_properties_loose(source, excluded);
    if (Object.getOwnPropertySymbols) {
        sourceKeys = Object.getOwnPropertySymbols(source);
        for(i = 0; i < sourceKeys.length; i++){
            key = sourceKeys[i];
            if (excluded.indexOf(key) >= 0) continue;
            if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
            target[key] = source[key];
        }
    }
    return target;
}
function _object_without_properties_loose(source, excluded) {
    if (source == null) return {};
    var target = {}, sourceKeys = Object.getOwnPropertyNames(source), key, i;
    for(i = 0; i < sourceKeys.length; i++){
        key = sourceKeys[i];
        if (excluded.indexOf(key) >= 0) continue;
        if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
        target[key] = source[key];
    }
    return target;
}
function _sliced_to_array(arr, i) {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _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 { Button, ConfigProvider } from "antd";
import clsx from "clsx";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { ErrorBoundary } from "react-error-boundary";
import { Loading } from "../../Components/Loading";
import { ChartRender } from "../../Plugins/chart/ChartRender";
import { parseChineseCurrencyToNumber } from "../../Plugins/chart/utils";
var extractTextContent = function extractTextContent1(children) {
    var _children_props;
    if (typeof children === 'string') return children;
    if (typeof children === 'number') return String(children);
    if (Array.isArray(children)) return children.map(extractTextContent).join('');
    if (/*#__PURE__*/ React.isValidElement(children) && ((_children_props = children.props) === null || _children_props === void 0 ? void 0 : _children_props.children)) {
        return extractTextContent(children.props.children);
    }
    return '';
};
/**
 * 解析图表 JSON 配置。
 * 支持两种格式：
 * 1. 完整格式：{ config: [...], dataSource: [...], columns: [...] }
 * 2. 简单格式：{ chartType, x, y, data: [...] }
 * 3. algTypes 格式：{ type: "histogram", value: { data: [...], dataMetaMap: {...} } }
 */ var parseChartData = function parseChartData(code) {
    try {
        var parsed = JSON.parse(code.trim());
        if (!parsed || (typeof parsed === "undefined" ? "undefined" : _type_of(parsed)) !== 'object') return null;
        if (Array.isArray(parsed)) {
            return {
                config: parsed
            };
        }
        // Handle { type: "histogram", value: { data: [...], dataMetaMap: {...} } } format
        if (typeof parsed.type === 'string' && parsed.value && Array.isArray(parsed.value.data)) {
            return {
                chartType: parsed.type,
                data: parsed.value.data,
                dataMetaMap: parsed.value.dataMetaMap
            };
        }
        return parsed;
    } catch (unused) {
        return null;
    }
};
/** 图表渲染失败时用相同 props 重试一次（销毁再重建） */ var ChartWithRetry = function ChartWithRetry(props) {
    var index = props.index, columnLength = props.columnLength, setColumnLength = props.setColumnLength, chartType = props.chartType, chartDataItems = props.chartDataItems, rest = props.rest, height = props.height, x = props.x, y = props.y, columns = props.columns;
    var _useState = _sliced_to_array(useState(0), 2), retryKey = _useState[0], setRetryKey = _useState[1];
    var handleChartError = React.useCallback(function(error, info) {
        console.error('[MarkdownRenderer ChartBlockRenderer] 渲染失败:', {
            chartType: chartType,
            title: rest === null || rest === void 0 ? void 0 : rest.title,
            x: x,
            y: y,
            dataSourceLength: chartDataItems.length,
            columnsLength: columns.length,
            error: error.message,
            stack: error.stack,
            componentStack: info.componentStack
        });
        setRetryKey(function(k) {
            return k === 0 ? 1 : k;
        });
    }, [
        chartType,
        rest === null || rest === void 0 ? void 0 : rest.title,
        x,
        y,
        chartDataItems.length,
        columns.length
    ]);
    var handleRetry = React.useCallback(function() {
        setRetryKey(function(k) {
            return k + 1;
        });
    }, []);
    var chartFallback = /*#__PURE__*/ React.createElement("div", {
        style: {
            padding: 12,
            color: '#999',
            fontSize: 12,
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'flex-start',
            gap: 8
        }
    }, /*#__PURE__*/ React.createElement("span", null, "Chart: ", (rest === null || rest === void 0 ? void 0 : rest.title) || chartType), /*#__PURE__*/ React.createElement(Button, {
        type: "link",
        size: "small",
        onClick: handleRetry
    }, "重新渲染"));
    return /*#__PURE__*/ React.createElement("div", {
        style: {
            margin: 'auto',
            minWidth: 0,
            width: columnLength === 1 ? '100%' : "calc(".concat(100 / columnLength, "% - 8px)"),
            maxWidth: '100%',
            flex: 1,
            userSelect: 'none'
        }
    }, /*#__PURE__*/ React.createElement(ErrorBoundary, {
        key: retryKey,
        fallback: chartFallback,
        onError: handleChartError
    }, /*#__PURE__*/ React.createElement(ChartRender, {
        chartType: chartType,
        chartData: chartDataItems,
        columnLength: columnLength,
        onColumnLengthChange: setColumnLength,
        title: rest === null || rest === void 0 ? void 0 : rest.title,
        dataTime: rest === null || rest === void 0 ? void 0 : rest.dataTime,
        groupBy: rest === null || rest === void 0 ? void 0 : rest.groupBy,
        filterBy: rest === null || rest === void 0 ? void 0 : rest.filterBy,
        colorLegend: rest === null || rest === void 0 ? void 0 : rest.colorLegend,
        config: {
            height: height,
            x: x,
            y: y,
            columns: columns,
            index: index,
            rest: rest
        }
    })));
};
/**
 * 图表渲染器——复用 MarkdownEditor 的 ChartRender 组件。
 *
 * 在 MarkdownEditor 中，图表由 HTML 注释（配置）+ 表格（数据）组合而成，
 * Slate 解析器将其合并为 chart 节点（otherProps.config / dataSource / columns）。
 *
 * 在 MarkdownRenderer 中，chart 代码块的内容是序列化后的 JSON，
 * 包含 config、dataSource、columns 等字段。
 */ export var ChartBlockRenderer = function ChartBlockRenderer(props) {
    var children = props.children, className = props.className;
    var getPrefixCls = React.useContext(ConfigProvider.ConfigContext).getPrefixCls;
    var prefixCls = getPrefixCls('agentic-md-editor');
    var containerRef = useRef(null);
    var _useState = _sliced_to_array(useState(2), 2), columnLength = _useState[0], setColumnLength = _useState[1];
    var _useState1 = _sliced_to_array(useState(false), 2), mounted = _useState1[0], setMounted = _useState1[1];
    var code = extractTextContent(children);
    var chartData = useMemo(function() {
        return parseChartData(code);
    }, [
        code
    ]);
    useEffect(function() {
        // 延迟一帧渲染图表，确保容器已挂载到 DOM 且有正确的宽度
        // 解决 recharts ResponsiveContainer 在零宽容器中崩溃的问题
        var cancelled = false;
        var raf = requestAnimationFrame(function() {
            if (cancelled) {
                return;
            }
            setMounted(true);
        });
        return function() {
            cancelled = true;
            cancelAnimationFrame(raf);
        };
    }, []);
    useEffect(function() {
        if (!mounted) return;
        if (typeof window === 'undefined') {
            return;
        }
        var updateWidth = function updateWidth() {
            var _containerRef_current;
            var width = ((_containerRef_current = containerRef.current) === null || _containerRef_current === void 0 ? void 0 : _containerRef_current.clientWidth) || 400;
            var configs = (chartData === null || chartData === void 0 ? void 0 : chartData.config) ? Array.isArray(chartData.config) ? chartData.config : [
                chartData.config
            ] : [
                chartData
            ];
            setColumnLength(Math.min(Math.floor(Math.max(width, 256) / 256), configs.length));
        };
        updateWidth();
        window.addEventListener('resize', updateWidth);
        return function() {
            return window.removeEventListener('resize', updateWidth);
        };
    }, [
        chartData,
        mounted
    ]);
    if (!chartData) {
        return /*#__PURE__*/ React.createElement("div", {
            className: clsx("".concat(prefixCls, "-chart-block"), "".concat(prefixCls, "-chart-block--error"), className)
        }, /*#__PURE__*/ React.createElement("pre", {
            style: {
                margin: 0,
                padding: 12,
                fontSize: 12
            }
        }, code));
    }
    var configs = Array.isArray(chartData.config) ? chartData.config : chartData.config ? [
        chartData.config
    ] : [
        chartData
    ];
    var dataSource = chartData.dataSource || chartData.data || [];
    var columns = chartData.columns || [];
    return /*#__PURE__*/ React.createElement("div", {
        ref: containerRef,
        "data-be": "chart",
        className: clsx(className),
        style: {
            flex: 1,
            minWidth: 0,
            width: '100%',
            maxWidth: '100%',
            margin: '1em 0',
            overflow: 'hidden'
        }
    }, !mounted ? /*#__PURE__*/ React.createElement("div", {
        style: {
            padding: 12
        }
    }, /*#__PURE__*/ React.createElement(Loading, null)) : /*#__PURE__*/ React.createElement("div", {
        style: {
            display: 'flex',
            flexWrap: 'wrap',
            gap: 8,
            userSelect: 'none'
        }
    }, configs.map(function(cfg, index) {
        var _containerRef_current;
        var chartType = cfg.chartType, x = cfg.x, y = cfg.y, rest = _object_without_properties(cfg, [
            "chartType",
            "x",
            "y"
        ]);
        if (!chartType) {
            return /*#__PURE__*/ React.createElement("div", {
                key: index,
                style: {
                    padding: 12,
                    color: '#999'
                }
            }, /*#__PURE__*/ React.createElement(Loading, null));
        }
        var chartDataItems = dataSource.map(function(item) {
            var _chartType = item.chartType, rowData = _object_without_properties(item, [
                "chartType"
            ]);
            var row = _object_spread_props(_object_spread({}, rowData), {
                column_list: Object.keys(rowData)
            });
            var coerceChartAxisCell = function coerceChartAxisCell(raw) {
                if (typeof raw === 'number' && Number.isFinite(raw)) return raw;
                var n = Number(raw);
                if (Number.isFinite(n)) return n;
                if (typeof raw === 'string') {
                    var cn = parseChineseCurrencyToNumber(raw);
                    if (cn !== null) return cn;
                }
                return raw;
            };
            if (x && row[x] !== undefined) {
                row[x] = coerceChartAxisCell(row[x]);
            }
            if (y && row[y] !== undefined) {
                row[y] = coerceChartAxisCell(row[y]);
            }
            return row;
        });
        var height = Math.min(400, ((_containerRef_current = containerRef.current) === null || _containerRef_current === void 0 ? void 0 : _containerRef_current.clientWidth) || 400);
        return /*#__PURE__*/ React.createElement(ChartWithRetry, {
            key: index,
            index: index,
            columnLength: columnLength,
            setColumnLength: setColumnLength,
            chartType: chartType,
            chartDataItems: chartDataItems,
            rest: rest,
            height: height,
            x: x,
            y: y,
            columns: columns
        });
    })));
};
ChartBlockRenderer.displayName = 'ChartBlockRenderer';
