import * as React from 'react';
import classNames from 'classnames';
import { useSortable } from '@dnd-kit/sortable';
import { CnIcon } from '@cainiaofe/cn-ui';
import { flexRender } from '../../../../../../cn-ai-table/react-table';
import { useModel } from '../../../../../../utils/mobx-react-simpler/index.js';
import { useFieldIcon, getFieldComponentType, } from '../../../../../../cn-ai-table/view/utils/field-icon-utils';
import { DRAG_TYPES } from './constants';
const FormulaIcon = CnIcon.createFromIconfontCN({
    scriptUrl: '//at.alicdn.com/t/a/font_4448706_i4lwtal07u.js',
});
/**
 * 可拖拽的列表头组件
 */
export const DraggableColumnHeader = ({ header, isSelected, onHeaderClick, rowHeight, columnWidth = 200, isFirstColumn = false, currentDragType, pinnedLeft, pinnedIndex, pinnedColumnsCount = 1, onContextMenu, headerRef, }) => {
    var _a;
    const { column } = header;
    const dataModel = useModel('dataModel');
    const getIcon = 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 = 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 } = useSortable({
        id: column.id,
        data: { type: 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 = classNames('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 === 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, flexRender(header.column.columnDef.header, header.getContext())))),
        header.column.getCanResize() && (React.createElement("div", { className: classNames('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() }))));
};
