"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.useColumnHeaderMenu = useColumnHeaderMenu;
const i18n_1 = __importDefault(require("../../../../../../../locales/i18n.js"));
const React = __importStar(require("react"));
const fieldSortUtils_1 = require("../../../../../../../cn-ai-table/view/components/toolbar/utils/fieldSortUtils");
const get_column_meta_data_1 = require("../../../../../../../utils/data/get-column-meta-data.js");
const constants_1 = require("../../../../../../../cn-ai-table/view/components/toolbar/components/group/constants");
const mobx_react_simpler_1 = require("../../../../../../../utils/mobx-react-simpler/index.js");
const table_column_feature_utils_1 = require("../../../../../../../cn-ai-table/view/utils/table-column-feature-utils");
/**
 * 构建列头右键菜单项
 */
function buildMenuItems(options) {
    var _a;
    const { columnId, columnName, columnIndex, fieldMap, columnDefinitions, viewConfig, onFreezeToColumn, onUnfreezeColumn, onFillColor, 
    // onInsertLeft,
    // onInsertRight,
    onSortAsc, onSortDesc, onGroupBy, onFilterBy, onDeleteField, onEditAiColumn, onEditFormulaColumn, onEditLookupColumn, isFieldDeletable, onClose, currentGroupCount = 0, maxGroupLevels = 1, toolbarPermissions, } = options;
    const columnDef = columnDefinitions === null || columnDefinitions === void 0 ? void 0 : columnDefinitions.find((col) => col.dataIndex === columnId);
    // columnName 可能不是字符串（如 AI字段的columnName是React 组件），兜底使用 columnDef.title
    const resolvedColumnName = (typeof columnName === 'string' && columnName) || (columnDef === null || columnDef === void 0 ? void 0 : columnDef.title);
    const isAiColumn = (columnDef === null || columnDef === void 0 ? void 0 : columnDef.isAiColumn) === true;
    const isFormulaColumn = (columnDef === null || columnDef === void 0 ? void 0 : columnDef.format) === 'formula';
    const isLookupColumn = (columnDef === null || columnDef === void 0 ? void 0 : columnDef.format) === 'lookup';
    /** AI / 公式 / 引用：无低码 fieldMap，列头菜单需追加「编辑/删除」 */
    const isExtendedFieldColumn = isAiColumn || isFormulaColumn || isLookupColumn;
    const rawField = fieldMap === null || fieldMap === void 0 ? void 0 : fieldMap[columnId];
    const field = (0, table_column_feature_utils_1.getToolbarFieldSchema)(rawField, columnDef);
    if (!field || !(0, get_column_meta_data_1.shouldKeepField)(field)) {
        return [];
    }
    const canDelete = !!onDeleteField && (typeof isFieldDeletable !== 'function' || isFieldDeletable(columnId));
    // 判断字段是否可排序（含按文本排序的 AI/公式/引用列）
    const canSort = (0, fieldSortUtils_1.isSortableField)(field, columnDef);
    const items = [];
    // 整列填色 —— 与工具栏「填色」共用权限
    if ((toolbarPermissions === null || toolbarPermissions === void 0 ? void 0 : toolbarPermissions.colorFill) !== false) {
        items.push({
            key: 'fillColor',
            label: i18n_1.default.get({ id: 'EntireFill', dm: '整列填色' }),
            icon: 'fill',
            onClick: () => {
                onFillColor === null || onFillColor === void 0 ? void 0 : onFillColor(columnId);
                onClose === null || onClose === void 0 ? void 0 : onClose();
            },
        });
    }
    // 冻结/取消冻结（只有前3列才支持）
    if (columnIndex < 3) {
        // 判断当前列是否已冻结
        const pinnedFieldIds = ((_a = viewConfig === null || viewConfig === void 0 ? void 0 : viewConfig.custom) === null || _a === void 0 ? void 0 : _a.pinnedFieldIds) || [];
        const isFrozen = pinnedFieldIds.includes(columnId);
        if (isFrozen && onUnfreezeColumn && pinnedFieldIds.length > 1) {
            // 已冻结，显示"取消冻结"
            items.push({
                key: 'unfreeze',
                label: i18n_1.default.get({ id: 'Unfreeze.socJm', dm: '取消冻结' }),
                icon: 'unlock',
                onClick: () => {
                    onUnfreezeColumn(columnId, columnIndex);
                    onClose === null || onClose === void 0 ? void 0 : onClose();
                },
            });
        }
        else if (!isFrozen && onFreezeToColumn) {
            // 未冻结，显示"冻结至此字段/列"
            items.push({
                key: 'freeze',
                label: i18n_1.default.get({ id: 'FreezeToThisFieldcolumn', dm: '冻结至此字段/列' }),
                icon: 'lock',
                onClick: () => {
                    onFreezeToColumn(columnId, columnIndex);
                    onClose === null || onClose === void 0 ? void 0 : onClose();
                },
            });
        }
    }
    // 分隔线
    items.push({
        key: 'divider1',
        label: '',
        onClick: () => { },
        disabled: true,
    });
    // // 向左插入字段/列
    // items.push({
    //   key: 'insertLeft',
    //   label: '向左插入字段/列',
    //   icon: 'left',
    //   onClick: () => {
    //     onInsertLeft?.(columnId);
    //     onClose?.();
    //   },
    // });
    // // 向右插入字段/列
    // items.push({
    //   key: 'insertRight',
    //   label: '向右插入字段/列',
    //   icon: 'right',
    //   onClick: () => {
    //     onInsertRight?.(columnId);
    //     onClose?.();
    //   },
    // });
    // // 分隔线
    // items.push({
    //   key: 'divider2',
    //   label: '',
    //   onClick: () => {},
    //   disabled: true,
    // });
    // 正序 —— 字段可排序且工具栏「排序」未关闭
    const sortAllowed = canSort && (toolbarPermissions === null || toolbarPermissions === void 0 ? void 0 : toolbarPermissions.sort) !== false;
    if (sortAllowed) {
        items.push({
            key: 'sortAsc',
            label: i18n_1.default.get({ id: 'PositiveSequence', dm: '正序' }),
            icon: 'sort-asc',
            onClick: () => {
                onSortAsc === null || onSortAsc === void 0 ? void 0 : onSortAsc(columnId);
                onClose === null || onClose === void 0 ? void 0 : onClose();
            },
        });
    }
    // 倒序 —— 同正序
    if (sortAllowed) {
        items.push({
            key: 'sortDesc',
            label: i18n_1.default.get({ id: 'ReverseOrder', dm: '倒序' }),
            icon: 'sort-desc',
            onClick: () => {
                onSortDesc === null || onSortDesc === void 0 ? void 0 : onSortDesc(columnId);
                onClose === null || onClose === void 0 ? void 0 : onClose();
            },
        });
    }
    // 如果字段不支持分组或已达到最大级别，则不显示此菜单项；同时受工具栏「分组」权限控制
    const fieldType = field === null || field === void 0 ? void 0 : field['x-component'];
    const isGroupableField = (0, get_column_meta_data_1.shouldKeepField)(field) &&
        ((0, table_column_feature_utils_1.isAiFormulaOrLookupColumnDef)(columnDef) ||
            !!constants_1.GROUP_FIELD_TYPE[fieldType]) &&
        currentGroupCount < maxGroupLevels &&
        (toolbarPermissions === null || toolbarPermissions === void 0 ? void 0 : toolbarPermissions.group) !== false;
    if (isGroupableField) {
        items.push({
            key: 'groupBy',
            label: React.createElement(React.Fragment, null, i18n_1.default.get({ id: 'GroupBy', dm: '按「' }), React.createElement('span', { className: 'column-header-menu-field-name', title: resolvedColumnName }, resolvedColumnName), i18n_1.default.get({ id: 'UIdmr', dm: '」分组' })),
            icon: 'group',
            onClick: () => {
                onGroupBy === null || onGroupBy === void 0 ? void 0 : onGroupBy(columnId);
                onClose === null || onClose === void 0 ? void 0 : onClose();
            },
        });
    }
    // 按字段筛选 —— 与工具栏筛选共用同一份权限，关掉工具栏 filter 时同步隐藏此项
    if ((toolbarPermissions === null || toolbarPermissions === void 0 ? void 0 : toolbarPermissions.filter) !== false) {
        items.push({
            key: 'filterBy',
            label: React.createElement(React.Fragment, null, i18n_1.default.get({ id: 'GroupBy', dm: '按「' }), React.createElement('span', { className: 'column-header-menu-field-name', title: resolvedColumnName }, resolvedColumnName), i18n_1.default.get({ id: 'Filter.8HFse', dm: '」筛选' })),
            icon: 'filter',
            onClick: () => {
                onFilterBy === null || onFilterBy === void 0 ? void 0 : onFilterBy(columnId);
                onClose === null || onClose === void 0 ? void 0 : onClose();
            },
        });
    }
    // AI / 公式 / 引用：在通用能力后追加编辑、删除（文案区分）
    if (isExtendedFieldColumn) {
        if ((isAiColumn && onEditAiColumn) ||
            (isFormulaColumn && onEditFormulaColumn) ||
            (isLookupColumn && onEditLookupColumn) ||
            canDelete) {
            items.push({
                key: 'divider-managed-field',
                label: '',
                onClick: () => { },
                disabled: true,
            });
        }
        if (isAiColumn && onEditAiColumn) {
            items.push({
                key: 'edit-ai',
                label: i18n_1.default.get({ id: 'EditAIColumn', dm: '编辑AI列' }),
                icon: 'edit',
                onClick: () => {
                    onEditAiColumn(columnId);
                    onClose === null || onClose === void 0 ? void 0 : onClose();
                },
            });
        }
        if (isFormulaColumn && onEditFormulaColumn) {
            items.push({
                key: 'edit-formula',
                label: i18n_1.default.get({ id: 'EditFormulaField', dm: '编辑公式字段' }),
                icon: 'edit',
                onClick: () => {
                    onEditFormulaColumn(columnId);
                    onClose === null || onClose === void 0 ? void 0 : onClose();
                },
            });
        }
        if (isLookupColumn && onEditLookupColumn) {
            items.push({
                key: 'edit-lookup',
                label: i18n_1.default.get({ id: 'EditReferenceField', dm: '编辑引用字段' }),
                icon: 'edit',
                onClick: () => {
                    onEditLookupColumn(columnId);
                    onClose === null || onClose === void 0 ? void 0 : onClose();
                },
            });
        }
        if (canDelete) {
            let deleteLabel;
            if (isAiColumn) {
                deleteLabel = i18n_1.default.get({ id: 'DeleteAnAIColumn', dm: '删除AI列' });
            }
            else if (isFormulaColumn) {
                deleteLabel = i18n_1.default.get({ id: 'DeleteFormulaField', dm: '删除公式字段' });
            }
            else {
                deleteLabel = i18n_1.default.get({ id: 'DeleteReferenceField', dm: '删除引用字段' });
            }
            items.push({
                key: 'delete-managed',
                label: deleteLabel,
                icon: 'delete',
                danger: true,
                onClick: () => {
                    onDeleteField(columnId);
                    onClose === null || onClose === void 0 ? void 0 : onClose();
                },
            });
        }
    }
    else if (canDelete) {
        items.push({
            key: 'divider-delete',
            label: '',
            onClick: () => { },
            disabled: true,
        });
        items.push({
            key: 'delete',
            label: i18n_1.default.get({ id: 'DeleteField', dm: '删除字段' }),
            icon: 'delete',
            danger: true,
            onClick: () => {
                onDeleteField(columnId);
                onClose === null || onClose === void 0 ? void 0 : onClose();
            },
        });
    }
    return items;
}
function useColumnHeaderMenu(options) {
    var _a, _b;
    const { fieldMap, columnDefinitions, viewConfig, onFreezeToColumn, onUnfreezeColumn, onFillColor, onInsertLeft, onInsertRight, onSortAsc, onSortDesc, onGroupBy, onFilterBy, onDeleteField, onEditAiColumn, onEditFormulaColumn, onEditLookupColumn, isFieldDeletable, currentGroupCount = 0, maxGroupLevels = 1, } = options;
    // 工具栏权限由 cn-ai-table 同步至 DataModel，列右键菜单直接读取，避免逐层透传
    const dataModel = (0, mobx_react_simpler_1.useModel)('dataModel');
    const toolbarPermissions = (_a = dataModel === null || dataModel === void 0 ? void 0 : dataModel.gridToolbarPermissions) !== null && _a !== void 0 ? _a : undefined;
    // 列头右键菜单关闭开关；true 时不绑定 onContextMenu，浏览器走原生菜单
    const hideColumnHeaderMenu = (_b = dataModel === null || dataModel === void 0 ? void 0 : dataModel.hideColumnHeaderMenu) !== null && _b !== void 0 ? _b : false;
    // 右键菜单状态
    const [contextMenuState, setContextMenuState] = React.useState({
        visible: false,
        columnId: null,
    });
    // 处理右键菜单打开；总开关关闭时返回 undefined，使列头不绑定 onContextMenu，浏览器走原生菜单
    const handleContextMenu = React.useCallback((columnId) => {
        if (hideColumnHeaderMenu)
            return undefined;
        return (e) => {
            e.preventDefault();
            e.stopPropagation();
            setContextMenuState({
                visible: true,
                columnId,
            });
        };
    }, [hideColumnHeaderMenu]);
    // 关闭右键菜单
    const handleContextMenuClose = React.useCallback(() => {
        setContextMenuState({ visible: false, columnId: null });
    }, []);
    // 构建菜单项的回调函数
    const getMenuItems = React.useCallback((columnId, columnName, columnIndex) => {
        if (hideColumnHeaderMenu)
            return [];
        return buildMenuItems({
            columnId,
            columnName,
            columnIndex,
            fieldMap,
            columnDefinitions,
            viewConfig,
            onFreezeToColumn,
            onUnfreezeColumn,
            onFillColor,
            onInsertLeft,
            onInsertRight,
            onSortAsc,
            onSortDesc,
            onGroupBy,
            onFilterBy,
            onDeleteField,
            onEditAiColumn,
            onEditFormulaColumn,
            onEditLookupColumn,
            isFieldDeletable,
            onClose: handleContextMenuClose,
            currentGroupCount,
            maxGroupLevels,
            toolbarPermissions,
        });
    }, [
        fieldMap,
        columnDefinitions,
        viewConfig,
        handleContextMenuClose,
        onFreezeToColumn,
        onUnfreezeColumn,
        onFillColor,
        onInsertLeft,
        onInsertRight,
        onSortAsc,
        onSortDesc,
        onGroupBy,
        onFilterBy,
        onDeleteField,
        onEditAiColumn,
        onEditFormulaColumn,
        onEditLookupColumn,
        isFieldDeletable,
        currentGroupCount,
        maxGroupLevels,
        toolbarPermissions,
        hideColumnHeaderMenu,
    ]);
    return {
        contextMenuState,
        handleContextMenu,
        handleContextMenuClose,
        getMenuItems,
    };
}
