"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.DraggableColumnHeader = void 0;
const React = __importStar(require("react"));
const classnames_1 = __importDefault(require("classnames"));
const sortable_1 = require("@dnd-kit/sortable");
const cn_ui_1 = require("@cainiaofe/cn-ui");
const react_table_1 = require("../../../../../../cn-ai-table/react-table");
const mobx_react_simpler_1 = require("../../../../../../utils/mobx-react-simpler/index.js");
const field_icon_utils_1 = require("../../../../../../cn-ai-table/view/utils/field-icon-utils");
const constants_1 = require("./constants");
const FormulaIcon = cn_ui_1.CnIcon.createFromIconfontCN({
    scriptUrl: '//at.alicdn.com/t/a/font_4448706_i4lwtal07u.js',
});
/**
 * 可拖拽的列表头组件
 */
const DraggableColumnHeader = ({ header, isSelected, onHeaderClick, rowHeight, columnWidth = 200, isFirstColumn = false, currentDragType, pinnedLeft, pinnedIndex, pinnedColumnsCount = 1, onContextMenu, headerRef, }) => {
    var _a;
    const { column } = header;
    const dataModel = (0, mobx_react_simpler_1.useModel)('dataModel');
    const getIcon = (0, field_icon_utils_1.useFieldIcon)();
    const isFormulaColumn = ((_a = column === null || column === void 0 ? void 0 : column.columnDef) === null || _a === void 0 ? void 0 : _a.format) === 'formula';
    // 获取字段图标（仅处理普通字段，AI字段的header中已包含图标，公式字段使用iconfont）
    const fieldIcon = React.useMemo(() => {
        var _a, _b, _c;
        const columnId = column === null || column === void 0 ? void 0 : column.id;
        const isAiColumn = (_b = (_a = dataModel === null || dataModel === void 0 ? void 0 : dataModel.isAiColumn) === null || _a === void 0 ? void 0 : _a.call(dataModel, columnId)) !== null && _b !== void 0 ? _b : false;
        if (isAiColumn || isFormulaColumn) {
            return null;
        }
        const componentType = (0, field_icon_utils_1.getFieldComponentType)(dataModel === null || dataModel === void 0 ? void 0 : dataModel.fieldMap, columnId, (_c = column === null || column === void 0 ? void 0 : column.columnDef) === null || _c === void 0 ? void 0 : _c.format);
        return getIcon(componentType);
    }, [column === null || column === void 0 ? void 0 : column.id, column === null || column === void 0 ? void 0 : column.columnDef, dataModel, getIcon, isFormulaColumn]);
    // 判断是否是固定列
    const isPinnedColumn = pinnedLeft !== undefined && pinnedIndex !== undefined;
    // 固定列禁用拖拽功能
    const { attributes, listeners, setNodeRef, isDragging, isOver } = (0, sortable_1.useSortable)({
        id: column.id,
        data: { type: constants_1.DRAG_TYPES.COLUMN },
        disabled: isPinnedColumn,
    });
    // 合并 ref：同时支持拖拽 ref 和外部传入的 headerRef
    const mergedRef = React.useCallback((node) => {
        // 设置拖拽 ref（固定列不需要）
        if (!isPinnedColumn && !isFirstColumn) {
            setNodeRef(node);
        }
        // 设置外部传入的 headerRef
        if (headerRef) {
            if (typeof headerRef === 'function') {
                headerRef(node);
            }
            else {
                headerRef.current = node;
            }
        }
    }, [setNodeRef, headerRef, isPinnedColumn, isFirstColumn]);
    // 列拖拽时不移动任何列，只显示放置指示器
    const style = isPinnedColumn
        ? {}
        : {
            cursor: 'grab',
            userSelect: 'none',
            opacity: isDragging ? 0.5 : 1,
        };
    // 所有表头都需要固定在顶部，固定列还需要固定在功能列右侧
    const headerStyle = {
        width: columnWidth,
        minWidth: columnWidth,
        ...(isPinnedColumn
            ? {
                position: 'sticky',
                left: pinnedLeft,
                // 必须高于表体冻结格（DraggableRow 内 10+pinnedCount，功能列 15）；内联会覆盖 _features 里 .ai-table-sticky-column 的 z-index，原先 10+ 会导致纵向滚动时表体盖住表头
                zIndex: 20 + (pinnedColumnsCount - (pinnedIndex || 0)),
            }
            : {}),
        ...style,
        // 可拖拽表头低于冻结列表头(20+)，避免横向滚动时其右侧阴影盖住最后一列冻结表头的右侧阴影（thead 内再分档）
        ...(!isPinnedColumn ? { zIndex: 3 } : {}),
    };
    // 列拖拽悄停时添加类名（只有列拖拽时才显示悄停指示器）
    const headerClassName = (0, classnames_1.default)('ai-table-header-cell', `ai-table-row-${rowHeight}`, {
        'ai-table-column-selected': isSelected,
        'ai-table-sticky-column': isPinnedColumn,
        'ai-table-sticky-column-last': isPinnedColumn && pinnedIndex === (pinnedColumnsCount || 1) - 1, // 最后一个固定列
        'ai-table-column-drag-over': isOver && !isDragging && !isPinnedColumn && currentDragType === constants_1.DRAG_TYPES.COLUMN,
    });
    // 列宽拖拽手柄
    const resizeHandler = header.getResizeHandler();
    const isResizing = header.column.getIsResizing();
    return (React.createElement("th", { ref: mergedRef, className: headerClassName, style: headerStyle, "data-column-id": column.id, onClick: () => !header.isPlaceholder && onHeaderClick(column.id), onContextMenu: onContextMenu },
        header.isPlaceholder ? null : (React.createElement("div", { ...(isPinnedColumn ? {} : attributes), ...(isPinnedColumn ? {} : listeners), className: "ai-table-header-content", style: {
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'flex-start',
                cursor: isPinnedColumn ? 'default' : 'grab',
            } },
            isFormulaColumn && React.createElement(FormulaIcon, { type: "icon-formula", style: { fontSize: '14px', marginRight: '4px' } }),
            fieldIcon && React.createElement("img", { src: fieldIcon, alt: "" }),
            React.createElement("span", null, (0, react_table_1.flexRender)(header.column.columnDef.header, header.getContext())))),
        header.column.getCanResize() && (React.createElement("div", { className: (0, classnames_1.default)('ai-table-column-resize-handle', {
                'ai-table-column-resize-handle--active': isResizing,
            }), onMouseDown: (e) => {
                e.stopPropagation();
                e.preventDefault();
                resizeHandler(e);
            }, onTouchStart: (e) => {
                e.stopPropagation();
                resizeHandler(e);
            }, onClick: (e) => e.stopPropagation(), onDoubleClick: (e) => e.stopPropagation(), onContextMenu: (e) => e.stopPropagation() }))));
};
exports.DraggableColumnHeader = DraggableColumnHeader;
