import * as React from 'react';
import ReactDOM from 'react-dom';
import { CnIcon } from '@cainiaofe/cn-ui';
import './column-header-menu.scss';
export function ColumnHeaderMenu({ items, onClose }) {
    const handleItemClick = (item) => {
        if (item.disabled)
            return;
        item.onClick();
        onClose === null || onClose === void 0 ? void 0 : onClose();
    };
    // 定义需要分隔线的位置
    const dividerKeys = ['insertLeft', 'sortAsc', 'delete'];
    return (React.createElement("div", { className: "column-header-menu" }, items
        .filter((item) => item.label) // 过滤掉空的分隔线项
        .map((item, index) => {
        // 检查是否需要添加分隔线
        const needDivider = index > 0 && dividerKeys.includes(item.key);
        return (React.createElement(React.Fragment, { key: item.key },
            needDivider && React.createElement("div", { className: "column-header-menu-divider" }),
            React.createElement("div", { className: `column-header-menu-item ${item.danger ? 'column-header-menu-item-danger' : ''} ${item.disabled ? 'column-header-menu-item-disabled' : ''}`, onClick: () => handleItemClick(item) },
                item.icon && (React.createElement(CnIcon, { type: item.icon, size: "small", className: "column-header-menu-item-icon" })),
                React.createElement("span", { className: "column-header-menu-item-text" }, item.label),
                item.badge && React.createElement("span", { className: "column-header-menu-item-badge" }, item.badge),
                item.hasSubMenu && (React.createElement(CnIcon, { type: "right", size: "small", className: "column-header-menu-item-arrow" })))));
    })));
}
// 查找元素的所有滚动容器
const findScrollContainers = (element) => {
    const containers = [window];
    let parent = element.parentElement;
    while (parent) {
        const style = window.getComputedStyle(parent);
        const hasScroll = style.overflow === 'auto' ||
            style.overflow === 'scroll' ||
            style.overflowY === 'auto' ||
            style.overflowY === 'scroll' ||
            style.overflowX === 'auto' ||
            style.overflowX === 'scroll';
        if (hasScroll) {
            containers.push(parent);
        }
        parent = parent.parentElement;
    }
    return containers;
};
export const ColumnHeaderMenuPopup = ({ visible, headerRef, menuItems, onClose, }) => {
    const menuRef = React.useRef(null);
    const triggerElement = headerRef.current;
    const [menuStyle, setMenuStyle] = React.useState({
        position: 'fixed',
        visibility: 'hidden',
    });
    // 更新菜单位置并设置事件监听
    React.useEffect(() => {
        if (!triggerElement || !visible) {
            return;
        }
        // 计算并更新菜单位置
        const updatePosition = () => {
            const rect = triggerElement.getBoundingClientRect();
            setMenuStyle({
                position: 'fixed',
                left: `${rect.left}px`,
                top: `${rect.top + rect.height}px`,
                visibility: 'visible',
                zIndex: 1000,
            });
        };
        updatePosition();
        // 查找所有滚动容器
        const scrollContainers = findScrollContainers(triggerElement);
        // 滚动时关闭菜单
        const handleScroll = onClose;
        // 窗口大小变化时更新位置
        window.addEventListener('resize', updatePosition);
        scrollContainers.forEach((container) => {
            container.addEventListener('scroll', handleScroll, true);
        });
        return () => {
            window.removeEventListener('resize', updatePosition);
            scrollContainers.forEach((container) => {
                container.removeEventListener('scroll', handleScroll, true);
            });
        };
    }, [triggerElement, visible, onClose]);
    // 点击外部关闭菜单
    React.useEffect(() => {
        if (!visible)
            return;
        const handleClickOutside = (e) => {
            var _a;
            const target = e.target;
            const isClickInsideMenu = (_a = menuRef.current) === null || _a === void 0 ? void 0 : _a.contains(target);
            const isClickInsideTrigger = triggerElement === null || triggerElement === void 0 ? void 0 : triggerElement.contains(target);
            if (!isClickInsideMenu && !isClickInsideTrigger) {
                onClose();
            }
        };
        // 延迟添加事件监听，避免立即触发
        const timer = setTimeout(() => {
            document.addEventListener('mousedown', handleClickOutside);
        }, 0);
        return () => {
            clearTimeout(timer);
            document.removeEventListener('mousedown', handleClickOutside);
        };
    }, [visible, onClose, triggerElement]);
    if (!visible || !triggerElement || menuItems.length === 0) {
        return null;
    }
    // 使用 Portal 渲染到 body，确保在编辑态和预览态下位置计算一致
    return ReactDOM.createPortal(React.createElement("div", { ref: menuRef, style: menuStyle },
        React.createElement(ColumnHeaderMenu, { items: menuItems, onClose: onClose })), document.body);
};
