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 _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;
}
import { debugInfo } from "../../../../Utils/debugUtils";
import { EditorUtils } from "../../utils";
import { createMediaNodeFromElement, decodeURIComponentUrl, findImageElement } from "./parseHtml";
import { handleAttachmentLink, handleLinkCard } from "./parseMedia";
import { handleTextAndInlineElementsPure, setFinishedProp } from "./parseText";
/**
 * 处理标题节点
 */ export var handleHeading = function(currentElement, parseNodes) {
    var _currentElement_children, _currentElement_children1, _result_children;
    debugInfo('handleHeading - 处理标题', {
        depth: currentElement.depth,
        childrenCount: (_currentElement_children = currentElement.children) === null || _currentElement_children === void 0 ? void 0 : _currentElement_children.length
    });
    var result = {
        type: 'head',
        level: currentElement.depth,
        children: ((_currentElement_children1 = currentElement.children) === null || _currentElement_children1 === void 0 ? void 0 : _currentElement_children1.length) ? parseNodes(currentElement.children, false, currentElement) : [
            {
                text: ''
            }
        ]
    };
    debugInfo('handleHeading - 标题处理完成', {
        level: result.level,
        childrenCount: (_result_children = result.children) === null || _result_children === void 0 ? void 0 : _result_children.length
    });
    return result;
};
/**
 * 处理列表节点
 */ export var handleList = function(currentElement, parseNodes) {
    var _currentElement_children, _el_children, _el_children1;
    debugInfo('handleList - 处理列表', {
        ordered: currentElement.ordered,
        start: currentElement.start,
        finished: currentElement.finished,
        childrenCount: (_currentElement_children = currentElement.children) === null || _currentElement_children === void 0 ? void 0 : _currentElement_children.length
    });
    var el = _object_spread_props(_object_spread({
        type: 'list',
        order: currentElement.ordered,
        start: currentElement.start
    }, currentElement.finished !== undefined && {
        finished: currentElement.finished
    }), {
        children: parseNodes(currentElement.children, false, currentElement)
    });
    el.task = (_el_children = el.children) === null || _el_children === void 0 ? void 0 : _el_children.some(function(s) {
        return typeof s.checked === 'boolean';
    });
    debugInfo('handleList - 列表处理完成', {
        type: el.type,
        order: el.order,
        start: el.start,
        task: el.task,
        childrenCount: (_el_children1 = el.children) === null || _el_children1 === void 0 ? void 0 : _el_children1.length
    });
    return el;
};
/**
 * 处理脚注定义节点
 */ export var handleFootnoteDefinition = function(currentElement, parseNodes) {
    var _parseNodes, _linkNode_children;
    var linkNode = (_parseNodes = parseNodes(currentElement.children, false, currentElement)) === null || _parseNodes === void 0 ? void 0 : _parseNodes.at(0);
    var cellNode = linkNode === null || linkNode === void 0 ? void 0 : (_linkNode_children = linkNode.children) === null || _linkNode_children === void 0 ? void 0 : _linkNode_children.at(0);
    return {
        value: cellNode === null || cellNode === void 0 ? void 0 : cellNode.text,
        url: cellNode === null || cellNode === void 0 ? void 0 : cellNode.url,
        type: 'footnoteDefinition',
        identifier: currentElement.identifier,
        children: [
            cellNode
        ]
    };
};
/**
 * 处理列表项节点
 */ export var handleListItem = function(currentElement, parseNodes) {
    var _currentElement_children, _currentElement_children1, _currentElement_children__children_, _currentElement_children__children, _currentElement_children_, _currentElement_children2, _currentElement_children__children1, _currentElement_children_1, _currentElement_children3, _result_children;
    debugInfo('handleListItem - 处理列表项', {
        checked: currentElement.checked,
        childrenCount: (_currentElement_children = currentElement.children) === null || _currentElement_children === void 0 ? void 0 : _currentElement_children.length
    });
    var children = ((_currentElement_children1 = currentElement.children) === null || _currentElement_children1 === void 0 ? void 0 : _currentElement_children1.length) ? parseNodes(currentElement.children, false, currentElement) : [
        {
            type: 'paragraph',
            children: [
                {
                    text: ''
                }
            ]
        }
    ];
    var mentions = undefined;
    if (((_currentElement_children2 = currentElement.children) === null || _currentElement_children2 === void 0 ? void 0 : (_currentElement_children_ = _currentElement_children2[0]) === null || _currentElement_children_ === void 0 ? void 0 : (_currentElement_children__children = _currentElement_children_.children) === null || _currentElement_children__children === void 0 ? void 0 : (_currentElement_children__children_ = _currentElement_children__children[0]) === null || _currentElement_children__children_ === void 0 ? void 0 : _currentElement_children__children_.type) === 'link' && ((_currentElement_children3 = currentElement.children) === null || _currentElement_children3 === void 0 ? void 0 : (_currentElement_children_1 = _currentElement_children3[0]) === null || _currentElement_children_1 === void 0 ? void 0 : (_currentElement_children__children1 = _currentElement_children_1.children) === null || _currentElement_children__children1 === void 0 ? void 0 : _currentElement_children__children1.length) > 1) {
        var _children__children, _children_;
        var item = children === null || children === void 0 ? void 0 : (_children_ = children[0]) === null || _children_ === void 0 ? void 0 : (_children__children = _children_.children) === null || _children__children === void 0 ? void 0 : _children__children[0];
        var label = item === null || item === void 0 ? void 0 : item.text;
        if (label) {
            var _item_url, _children__children1, _children_1;
            mentions = [
                {
                    avatar: item === null || item === void 0 ? void 0 : item.url,
                    name: label,
                    id: new URLSearchParams('?' + (item === null || item === void 0 ? void 0 : (_item_url = item.url) === null || _item_url === void 0 ? void 0 : _item_url.split('?')[1])).get('id') || undefined
                }
            ];
            children === null || children === void 0 ? true : (_children_1 = children[0]) === null || _children_1 === void 0 ? true : (_children__children1 = _children_1.children) === null || _children__children1 === void 0 ? true : delete _children__children1[0];
            debugInfo('handleListItem - 提取 mentions', {
                mentions: mentions
            });
        }
    }
    var result = {
        type: 'list-item',
        checked: currentElement.checked,
        children: children,
        mentions: mentions
    };
    debugInfo('handleListItem - 列表项处理完成', {
        type: result.type,
        checked: result.checked,
        childrenCount: (_result_children = result.children) === null || _result_children === void 0 ? void 0 : _result_children.length,
        hasMentions: !!result.mentions
    });
    return result;
};
/**
 * 处理段落子节点
 */ export var processParagraphChildren = function(currentElement, parseNodes) {
    var elements = [];
    var textNodes = [];
    var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
    try {
        for(var _iterator = (currentElement.children || [])[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
            var currentChild = _step.value;
            if (currentChild.type === 'image') {
                // 将累积的文本节点生成段落
                if (textNodes.length) {
                    elements.push({
                        type: 'paragraph',
                        children: parseNodes(textNodes, false, currentElement)
                    });
                    textNodes = [];
                }
                // 添加图片节点
                elements.push(EditorUtils.createMediaNode(decodeURIComponentUrl(currentChild === null || currentChild === void 0 ? void 0 : currentChild.url), 'image', _object_spread({
                    alt: currentChild.alt
                }, currentChild.finished !== undefined && {
                    finished: currentChild.finished
                })));
            } else if (currentChild.type === 'html') {
                // 跳过媒体标签的结束标签
                if (currentChild.value.match(/^<\/(img|video|iframe)>/)) {
                    continue;
                }
                var mediaElement = findImageElement(currentChild.value);
                if (mediaElement) {
                    var node = createMediaNodeFromElement(mediaElement);
                    if (node) {
                        elements.push(node);
                    }
                } else {
                    textNodes.push({
                        type: 'html',
                        value: currentChild.value
                    });
                }
            } else {
                textNodes.push(currentChild);
            }
        }
    } catch (err) {
        _didIteratorError = true;
        _iteratorError = err;
    } finally{
        try {
            if (!_iteratorNormalCompletion && _iterator.return != null) {
                _iterator.return();
            }
        } finally{
            if (_didIteratorError) {
                throw _iteratorError;
            }
        }
    }
    // 处理剩余的文本节点
    if (textNodes.length) {
        elements.push({
            type: 'paragraph',
            children: parseNodes(textNodes, false, currentElement)
        });
    }
    return elements;
};
/**
 * 处理段落节点
 */ export var handleParagraph = function(currentElement, config, parseNodes) {
    var _currentElement_children, _currentElement_children_, _currentElement_children1, _currentElement_children2, _currentElement_children_at, _currentElement_children3;
    debugInfo('handleParagraph - 处理段落', {
        childrenCount: (_currentElement_children = currentElement.children) === null || _currentElement_children === void 0 ? void 0 : _currentElement_children.length,
        firstChildType: (_currentElement_children1 = currentElement.children) === null || _currentElement_children1 === void 0 ? void 0 : (_currentElement_children_ = _currentElement_children1[0]) === null || _currentElement_children_ === void 0 ? void 0 : _currentElement_children_.type,
        configType: config === null || config === void 0 ? void 0 : config.type
    });
    // 检查是否是附件链接
    if (((_currentElement_children2 = currentElement.children) === null || _currentElement_children2 === void 0 ? void 0 : _currentElement_children2[0].type) === 'html' && currentElement.children[0].value.startsWith('<a')) {
        debugInfo('handleParagraph - 检测到附件链接');
        var attachNode = handleAttachmentLink(currentElement);
        if (attachNode) {
            debugInfo('handleParagraph - 返回附件节点', {
                type: attachNode === null || attachNode === void 0 ? void 0 : attachNode.type
            });
            return attachNode;
        }
    }
    // 检查是否是链接卡片
    if ((currentElement === null || currentElement === void 0 ? void 0 : (_currentElement_children3 = currentElement.children) === null || _currentElement_children3 === void 0 ? void 0 : (_currentElement_children_at = _currentElement_children3.at(0)) === null || _currentElement_children_at === void 0 ? void 0 : _currentElement_children_at.type) === 'link' && config.type === 'card') {
        debugInfo('handleParagraph - 检测到链接卡片');
        var linkCard = handleLinkCard(currentElement, config);
        debugInfo('handleParagraph - 返回链接卡片', {
            type: linkCard === null || linkCard === void 0 ? void 0 : linkCard.type
        });
        return linkCard;
    }
    // 处理混合内容段落
    debugInfo('handleParagraph - 处理混合内容段落');
    var result = processParagraphChildren(currentElement, parseNodes);
    debugInfo('handleParagraph - 段落处理完成', {
        resultType: Array.isArray(result) ? 'array' : result === null || result === void 0 ? void 0 : result.type,
        resultLength: Array.isArray(result) ? result.length : 1
    });
    return result;
};
/**
 * 处理引用块节点
 */ export var handleBlockquote = function(currentElement, parseNodes) {
    var _currentElement_children, _currentElement_children1, _result_children;
    debugInfo('handleBlockquote - 处理引用块', {
        childrenCount: (_currentElement_children = currentElement.children) === null || _currentElement_children === void 0 ? void 0 : _currentElement_children.length
    });
    var result = {
        type: 'blockquote',
        children: ((_currentElement_children1 = currentElement.children) === null || _currentElement_children1 === void 0 ? void 0 : _currentElement_children1.length) ? parseNodes(currentElement.children, false, currentElement) : [
            {
                type: 'paragraph',
                children: [
                    {
                        text: ''
                    }
                ]
            }
        ]
    };
    debugInfo('handleBlockquote - 引用块处理完成', {
        type: result.type,
        childrenCount: (_result_children = result.children) === null || _result_children === void 0 ? void 0 : _result_children.length
    });
    return result;
};
/**
 * 应用内联格式到叶子节点
 */ export var applyInlineFormatting = function(leaf, currentElement, config) {
    var result = _object_spread({}, leaf);
    var elementType = currentElement.type;
    var finished = currentElement.finished;
    if (elementType === 'strong') {
        return setFinishedProp(_object_spread_props(_object_spread({}, result), {
            bold: true
        }), finished);
    }
    if (elementType === 'emphasis') {
        return setFinishedProp(_object_spread_props(_object_spread({}, result), {
            italic: true
        }), finished);
    }
    if (elementType === 'delete') {
        result.strikethrough = true;
        return result;
    }
    if (elementType === 'link') {
        try {
            result.url = currentElement === null || currentElement === void 0 ? void 0 : currentElement.url;
            var shouldOpenInNewTab = (config === null || config === void 0 ? void 0 : config.openLinksInNewTab) || finished === false;
            if (shouldOpenInNewTab) {
                if (!result.otherProps) {
                    result.otherProps = {};
                }
                result.otherProps.target = '_blank';
                result.otherProps.rel = 'noopener noreferrer';
                if (finished === false) {
                    result.otherProps.finished = finished;
                }
            }
        } catch (unused) {
            result.url = currentElement === null || currentElement === void 0 ? void 0 : currentElement.url;
        }
        return result;
    }
    return result;
};
/**
 * 处理文本和内联元素节点
 */ export var handleTextAndInlineElements = function(currentElement, htmlTag, parseNodes, config) {
    return handleTextAndInlineElementsPure(currentElement, htmlTag, function(leaf, element) {
        return applyInlineFormatting(leaf, element, config);
    }, parseNodes);
};
