"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ColumnHeaderMenuPopup = void 0;
exports.ColumnHeaderMenu = ColumnHeaderMenu;
const React = __importStar(require("react"));
const react_dom_1 = __importDefault(require("react-dom"));
const cn_ui_1 = require("@cainiaofe/cn-ui");
require("./column-header-menu.scss");
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(cn_ui_1.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(cn_ui_1.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;
};
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 react_dom_1.default.createPortal(React.createElement("div", { ref: menuRef, style: menuStyle },
        React.createElement(ColumnHeaderMenu, { items: menuItems, onClose: onClose })), document.body);
};
exports.ColumnHeaderMenuPopup = ColumnHeaderMenuPopup;
