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 _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 _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 { CloseCircleFilled, EditOutlined } from "@ant-design/icons";
import { Copy } from "@sofa-design/icons";
import { Button, Table, Typography } from "antd";
import copy from "copy-to-clipboard";
import React, { useContext, useMemo } from "react";
import { I18nContext } from "../I18n";
import { ActionIconBox } from "../index";
import { MarkdownEditor, parserSlateNodeToMarkdown } from "../MarkdownEditor";
import { CostMillis } from "./CostMillis";
/**
 * ToolCall 组件用于显示 SQL 查询的执行状态和结果。
 *
 * @param props - 组件的属性。
 * @param props.isFinished - 表示 SQL 查询是否已完成。
 * @param props.input - 包含 SQL 查询的输入数据。
 * @param props.output - 包含 SQL 查询的输出数据。
 * @param props.costMillis - SQL 查询执行的耗时。
 *
 * @returns 返回一个包含 SQL 查询状态和结果的 JSX 元素。
 *
 * 组件功能：
 * - 显示 SQL 查询语句，并提供复制功能。
 * - 在 SQL 查询执行中时，显示执行中的提示。
 * - 显示 SQL 查询结果，并提供复制功能。
 * - 如果 SQL 查询出错，显示错误信息，并提供复制功能。
 */ export var TableSql = function(props) {
    var _props_input;
    var locale = useContext(I18nContext).locale;
    var _React_useState = _sliced_to_array(React.useState(false), 2), editor = _React_useState[0], setEditor = _React_useState[1];
    var editorRef = React.useRef(undefined);
    return useMemo(function() {
        var _props_output, _sourceData_fistKey, _props_output1, _props_output2, _props_output_response, _props_output3, _props_input_sql, _props_input;
        if (editor) {
            var _props_input_sql1, _props_input1;
            return /*#__PURE__*/ React.createElement("div", {
                "data-testid": props['data-testid'],
                style: {
                    display: 'flex',
                    gap: '10px',
                    flexDirection: 'column'
                }
            }, /*#__PURE__*/ React.createElement("div", {
                style: {
                    flex: 1,
                    display: 'flex',
                    flexDirection: 'column',
                    justifyContent: 'center',
                    padding: '8px 12px',
                    gap: '10px',
                    alignSelf: 'stretch',
                    wordBreak: 'break-all',
                    wordWrap: 'break-word',
                    background: '#FBFCFD',
                    zIndex: 1,
                    borderRadius: '12px'
                }
            }, /*#__PURE__*/ React.createElement("div", {
                style: {
                    display: 'flex',
                    flexDirection: 'row',
                    gap: '10px',
                    alignItems: 'center',
                    justifyContent: 'space-between'
                }
            }, locale === null || locale === void 0 ? void 0 : locale.executeSQL), /*#__PURE__*/ React.createElement("div", {
                style: {
                    display: 'flex',
                    borderRadius: '12px',
                    alignSelf: 'stretch',
                    background: '#FFFFFF'
                },
                className: "code-view"
            }, /*#__PURE__*/ React.createElement(MarkdownEditor, _object_spread_props(_object_spread({
                style: {
                    padding: 0,
                    width: '100%'
                }
            }, props.markdownRenderProps), {
                toc: false,
                editorRef: editorRef,
                contentStyle: {
                    padding: 0,
                    width: '100%'
                },
                initValue: "```sql\n".concat((_props_input1 = props.input) === null || _props_input1 === void 0 ? void 0 : (_props_input_sql1 = _props_input1.sql) === null || _props_input_sql1 === void 0 ? void 0 : _props_input_sql1.trim(), "\n```").trim()
            })))), /*#__PURE__*/ React.createElement("div", {
                style: {
                    gap: 12,
                    display: 'flex',
                    alignItems: 'flex-end',
                    justifyContent: 'flex-end',
                    width: '100%'
                }
            }, /*#__PURE__*/ React.createElement(Button, {
                style: {
                    border: '1px solid #F0F2F5',
                    background: '#FFFFFF',
                    padding: '4px 24px',
                    borderRadius: '12px 12px 12px 12px'
                },
                onClick: function() {
                    var _props_input_sql, _props_input, _editorRef_current_store, _editorRef_current;
                    setEditor(false);
                    (_editorRef_current = editorRef.current) === null || _editorRef_current === void 0 ? void 0 : (_editorRef_current_store = _editorRef_current.store) === null || _editorRef_current_store === void 0 ? void 0 : _editorRef_current_store.setMDContent("```sql\n".concat((_props_input = props.input) === null || _props_input === void 0 ? void 0 : (_props_input_sql = _props_input.sql) === null || _props_input_sql === void 0 ? void 0 : _props_input_sql.trim(), "\n```"));
                }
            }, locale === null || locale === void 0 ? void 0 : locale.cancel), /*#__PURE__*/ React.createElement(Button, {
                style: {
                    border: '1px solid #F0F2F5',
                    padding: '4px 24px',
                    borderRadius: '12px 12px 12px 12px'
                },
                type: "primary",
                onClick: function() {
                    var _editorRef_current_store_editor, _editorRef_current, _parserSlateNodeToMarkdown;
                    setEditor(false);
                    var schema = editorRef === null || editorRef === void 0 ? void 0 : (_editorRef_current = editorRef.current) === null || _editorRef_current === void 0 ? void 0 : (_editorRef_current_store_editor = _editorRef_current.store.editor) === null || _editorRef_current_store_editor === void 0 ? void 0 : _editorRef_current_store_editor.children;
                    var value = (_parserSlateNodeToMarkdown = parserSlateNodeToMarkdown(schema || [])) === null || _parserSlateNodeToMarkdown === void 0 ? void 0 : _parserSlateNodeToMarkdown.replaceAll('```sql\n', '').replaceAll('\n```', '').replaceAll('<!--{}-->\n', '');
                    // 优先使用新的事件名，保持向后兼容
                    if (props.onItemChange) {
                        props.onItemChange(props, {
                            feedbackContent: value || '',
                            feedbackType: 'sql',
                            feedbackRunId: props.runId || ''
                        });
                    } else if (props.onChangeItem) {
                        props.onChangeItem(props, {
                            feedbackContent: value || '',
                            feedbackType: 'sql',
                            feedbackRunId: props.runId || ''
                        });
                    }
                }
            }, locale === null || locale === void 0 ? void 0 : locale.retry)));
        }
        var sourceData = (_props_output = props.output) === null || _props_output === void 0 ? void 0 : _props_output.tableData;
        var keys = Object.keys(sourceData || {});
        var fistKey = keys[0];
        var dataSource = sourceData === null || sourceData === void 0 ? void 0 : (_sourceData_fistKey = sourceData[fistKey]) === null || _sourceData_fistKey === void 0 ? void 0 : _sourceData_fistKey.map(function(_, index) {
            return keys === null || keys === void 0 ? void 0 : keys.reduce(function(prev, key) {
                return _object_spread_props(_object_spread({}, prev), _define_property({}, key, sourceData[key][index]));
            }, {});
        });
        var columns = ((_props_output1 = props.output) === null || _props_output1 === void 0 ? void 0 : _props_output1.columns) || Object.keys((dataSource === null || dataSource === void 0 ? void 0 : dataSource.at(0)) || {});
        var errorMsg = ((_props_output2 = props.output) === null || _props_output2 === void 0 ? void 0 : _props_output2.errorMsg) || ((_props_output3 = props.output) === null || _props_output3 === void 0 ? void 0 : (_props_output_response = _props_output3.response) === null || _props_output_response === void 0 ? void 0 : _props_output_response.errorMsg);
        return /*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement("div", {
            "data-testid": props['data-testid'],
            style: {
                display: 'flex',
                gap: '10px',
                flexDirection: 'column'
            }
        }, /*#__PURE__*/ React.createElement("div", {
            style: {
                flex: 1,
                display: 'flex',
                flexDirection: 'column',
                justifyContent: 'center',
                padding: '8px 12px',
                gap: '10px',
                alignSelf: 'stretch',
                wordBreak: 'break-all',
                wordWrap: 'break-word',
                background: '#FBFCFD',
                zIndex: 1,
                borderRadius: '12px'
            }
        }, /*#__PURE__*/ React.createElement("div", {
            style: {
                display: 'flex',
                flexDirection: 'row',
                gap: '10px',
                alignItems: 'center',
                justifyContent: 'space-between'
            }
        }, locale === null || locale === void 0 ? void 0 : locale.executeSQL, /*#__PURE__*/ React.createElement("div", {
            style: {
                display: 'flex',
                flexDirection: 'row',
                gap: '10px',
                alignItems: 'center'
            }
        }, props.costMillis ? /*#__PURE__*/ React.createElement(CostMillis, {
            costMillis: props.costMillis
        }) : null, /*#__PURE__*/ React.createElement(ActionIconBox, {
            title: locale === null || locale === void 0 ? void 0 : locale.copy,
            onClick: function() {
                try {
                    var _props_input;
                    copy(((_props_input = props.input) === null || _props_input === void 0 ? void 0 : _props_input.sql) || '');
                } catch (error) {
                    console.error('复制失败:', error);
                }
            }
        }, /*#__PURE__*/ React.createElement(Copy, null)), props.onItemChange || props.onChangeItem ? /*#__PURE__*/ React.createElement(ActionIconBox, {
            title: locale === null || locale === void 0 ? void 0 : locale.edit,
            onClick: function() {
                setEditor(true);
            }
        }, /*#__PURE__*/ React.createElement(EditOutlined, null)) : null)), /*#__PURE__*/ React.createElement("div", {
            style: {
                display: 'flex',
                borderRadius: '12px',
                alignSelf: 'stretch',
                background: '#FFFFFF'
            },
            className: "code-view"
        }, /*#__PURE__*/ React.createElement(MarkdownEditor, _object_spread_props(_object_spread({
            style: {
                padding: 0,
                width: '100%'
            }
        }, props.markdownRenderProps), {
            toc: false,
            readonly: true,
            contentStyle: {
                padding: 0,
                width: '100%'
            },
            initValue: "```sql\n".concat((_props_input = props.input) === null || _props_input === void 0 ? void 0 : (_props_input_sql = _props_input.sql) === null || _props_input_sql === void 0 ? void 0 : _props_input_sql.trim(), "\n```").trim()
        })))), !props.isFinished ? /*#__PURE__*/ React.createElement("div", {
            style: {
                display: 'flex',
                flexDirection: 'row',
                gap: '10px',
                alignItems: 'center',
                justifyContent: 'center',
                padding: '8px 12px',
                alignSelf: 'stretch',
                wordBreak: 'break-all',
                wordWrap: 'break-word',
                background: '#FBFCFD',
                zIndex: 1,
                borderRadius: '12px'
            }
        }, locale === null || locale === void 0 ? void 0 : locale.executing) : null, props.isFinished && !errorMsg ? /*#__PURE__*/ React.createElement("div", {
            style: {
                display: 'flex',
                flexDirection: 'column',
                gap: '10px',
                padding: '8px 12px',
                alignSelf: 'stretch',
                wordBreak: 'break-all',
                wordWrap: 'break-word',
                background: '#FBFCFD',
                zIndex: 1,
                borderRadius: '12px'
            }
        }, /*#__PURE__*/ React.createElement("div", {
            style: {
                display: 'flex',
                flexDirection: 'row',
                gap: '10px',
                alignItems: 'center',
                justifyContent: 'space-between'
            }
        }, locale === null || locale === void 0 ? void 0 : locale.queryResults, /*#__PURE__*/ React.createElement("div", {
            style: {
                display: 'flex',
                flexDirection: 'row',
                gap: '10px',
                alignItems: 'center'
            }
        }, /*#__PURE__*/ React.createElement(ActionIconBox, {
            title: locale === null || locale === void 0 ? void 0 : locale.copy,
            onClick: function() {
                try {
                    var _props_output;
                    copy(JSON.stringify(((_props_output = props.output) === null || _props_output === void 0 ? void 0 : _props_output.tableData) || {}, null, 2));
                } catch (error) {
                    console.error('复制失败:', error);
                }
            }
        }, /*#__PURE__*/ React.createElement(Copy, null)))), /*#__PURE__*/ React.createElement("div", {
            style: {
                display: 'flex',
                borderRadius: '12px',
                alignSelf: 'stretch',
                background: '#FFFFFF'
            }
        }, /*#__PURE__*/ React.createElement(Table, {
            style: {
                width: '100%'
            },
            size: "small",
            pagination: false,
            rowKey: function(row) {
                return Object.values(row || {}).join('-');
            },
            dataSource: dataSource,
            columns: columns === null || columns === void 0 ? void 0 : columns.map(function(item) {
                return {
                    title: item,
                    dataIndex: item,
                    key: item
                };
            })
        }))) : null, props.isFinished && errorMsg ? /*#__PURE__*/ React.createElement("div", {
            style: {
                display: 'flex',
                flexDirection: 'column',
                gap: '10px',
                padding: '8px 12px',
                alignSelf: 'stretch',
                wordBreak: 'break-all',
                wordWrap: 'break-word',
                background: '#FBFCFD',
                zIndex: 1,
                borderRadius: '12px'
            }
        }, /*#__PURE__*/ React.createElement("div", {
            style: {
                display: 'flex',
                flexDirection: 'row',
                gap: '10px',
                alignItems: 'center',
                justifyContent: 'space-between'
            }
        }, /*#__PURE__*/ React.createElement("div", {
            style: {
                display: 'flex',
                flexDirection: 'row',
                gap: '10px',
                alignItems: 'center'
            }
        }, /*#__PURE__*/ React.createElement(CloseCircleFilled, {
            style: {
                color: '#ff4d4f'
            }
        }), locale === null || locale === void 0 ? void 0 : locale.queryFailed), /*#__PURE__*/ React.createElement("div", {
            style: {
                display: 'flex',
                flexDirection: 'row',
                gap: '10px',
                alignItems: 'center'
            }
        }, /*#__PURE__*/ React.createElement(ActionIconBox, {
            title: locale === null || locale === void 0 ? void 0 : locale.copy,
            onClick: function() {
                try {
                    copy(errorMsg);
                } catch (error) {
                    console.error('复制失败:', error);
                }
            }
        }, /*#__PURE__*/ React.createElement(Copy, null)))), /*#__PURE__*/ React.createElement("div", {
            style: {
                display: 'flex',
                borderRadius: '12px',
                alignSelf: 'stretch',
                background: '#FFFFFF'
            }
        }, /*#__PURE__*/ React.createElement(Typography.Text, {
            type: "danger"
        }, errorMsg))) : null));
    }, [
        editor,
        (_props_input = props.input) === null || _props_input === void 0 ? void 0 : _props_input.sql,
        props.output,
        props.isFinished,
        props.costMillis
    ]);
};
