"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.DraggableRow = void 0;
const i18n_1 = __importDefault(require("../../../../../../../locales/i18n.js"));
const context_1 = require("../../../../../../../theme/context.js");
/**
 * @file DraggableRow 组件
 * @description 可拖拽的数据行组件，负责渲染表格中的单个数据行
 *
 * 主要功能：
 * - 行拖拽：通过拖拽把手实现行排序
 * - 单元格渲染：根据列配置渲染不同类型的单元格
 * - 单元格编辑：支持点击进入编辑状态
 * - 行选择：支持单选/多选模式
 * - 固定列：支持左侧固定列和右侧操作列
 * - 颜色填充：支持根据规则设置单元格背景色
 */
const React = __importStar(require("react"));
const classnames_1 = __importDefault(require("classnames"));
const cn_ui_1 = require("@cainiaofe/cn-ui");
const colorFillUtils_1 = require("../../utils/colorFillUtils");
const component_adapter_1 = require("../../../../../../../utils/component-adapter/index.js");
const dropdown_form_item_1 = __importDefault(require("../../../../../../../utils/dropdown-form-item/index.js"));
const drag_utils_1 = require("../../drag-utils");
const primary_key_1 = require("../../../../../../../cn-ai-table/view/utils/primary-key");
const cell_content_with_tooltip_1 = require("../cell-content-with-tooltip");
require("./draggable-row.scss");
/**
 * 可拖拽的数据行组件
 * @description 负责渲染表格中的单个数据行，支持以下功能：
 * - 行拖拽：通过拖拽把手实现行排序
 * - 单元格渲染：根据列配置渲染不同类型的单元格
 * - 单元格编辑：支持点击进入编辑状态
 * - 行选择：支持单选/多选模式
 * - 固定列：支持左侧固定列和右侧操作列
 * - 颜色填充：支持根据规则设置单元格背景色
 */
const DraggableRow = ({ row, virtualRow, rowHeight, selectedColumnId, colorFillRules, widthMap, dataModel, isEditing, handleCellClick, renderCellContent, currentDragType, handleSubmit, form, showIndex = true, rowIndex = 0, rowSelectionEnabled = true, isRowSelected = false, isRowDisabled = false, selectionType = 'multiple', onRowSelectChange, pinnedModel, hasOperateColumn = false, renderOperateCell, operateColumnWidth = 150, measureElement, primaryKey = primary_key_1.DEFAULT_PRIMARY_KEY, isLastInGroup = false, isSmartFollowRunning = false, selectedCell = null, }) => {
    const brandAssets = (0, context_1.useBrandAssets)();
    const rowId = String((0, primary_key_1.safeGetRowKey)(row.original, primaryKey, rowIndex));
    // 拖拽配置 行拖拽不使用 transform 和 transition，和列拖拽一样只通过 DragOverlay 显示预览
    const { attributes, listeners, setNodeRef, isDragging, isOver } = (0, drag_utils_1.useSortable)({
        id: rowId,
        data: { type: drag_utils_1.DRAG_TYPES.ROW },
    });
    // 跟单态透明叠加色
    const SMART_FOLLOW_OVERLAY_COLOR = 'rgba(0, 71, 255, 0.1)';
    // -------- 行样式 --------
    // height 由虚拟滚动动态指定，其余静态样式由 SCSS 承载
    // --cell-follow-bg 设在行级，所有子单元格通过 CSS 变量继承
    const style = {
        height: `${virtualRow.size}px`,
        ['--cell-follow-bg']: isSmartFollowRunning
            ? `linear-gradient(${SMART_FOLLOW_OVERLAY_COLOR}, ${SMART_FOLLOW_OVERLAY_COLOR})`
            : undefined,
    };
    // -------- Ref 合并 --------
    // 合并 ref：拖拽 ref（用于 dnd-kit）和虚拟滚动测量 ref（用于动态行高）
    const mergedRef = React.useCallback((node) => {
        setNodeRef(node);
        if (measureElement) {
            measureElement(node);
        }
    }, [setNodeRef, measureElement]);
    // 功能列宽度（考虑序号和多选框）
    const actionColumnWidth = (0, drag_utils_1.getActionColumnWidth)(showIndex, rowSelectionEnabled);
    return (React.createElement("tr", { ref: mergedRef, 
        // cn-table-row onePage 写死样式，需要兼容
        className: (0, classnames_1.default)('cn-table-row', 'ai-table-row', `ai-table-row-${rowHeight}`, {
            dragging: isDragging,
            'ai-table-row-drag-over': isOver && !isDragging && currentDragType === drag_utils_1.DRAG_TYPES.ROW,
            'grouped-row-last': isLastInGroup,
            'ai-table-row-special-border': isSmartFollowRunning,
        }), style: style },
        React.createElement("td", { className: "ai-table-data-cell ai-table-sticky-column ai-table-action-column", style: {
                width: actionColumnWidth,
                minWidth: actionColumnWidth,
                maxWidth: actionColumnWidth,
            } },
            React.createElement("div", { className: "ai-table-action-column-content" },
                isSmartFollowRunning && (React.createElement("div", { className: "ai-table-special-border-badge" },
                    React.createElement("img", { src: brandAssets.table.selectedBadgeIconUrl, alt: "" }))),
                React.createElement("div", { ...attributes, ...listeners, className: "ai-table-row-drag-handle", "aria-label": i18n_1.default.get({ id: 'DragLine', dm: '拖拽行' }) },
                    React.createElement(cn_ui_1.CnIcon, { type: "bar", size: "medium" })),
                showIndex && (React.createElement("div", { className: "ai-table-row-index-selection-wrapper" },
                    React.createElement("div", { className: "ai-table-row-index" }, rowIndex + 1),
                    rowSelectionEnabled && (React.createElement("div", { className: (0, classnames_1.default)('ai-table-row-checkbox', {
                            'ai-table-row-checkbox-checked': isRowSelected,
                            'ai-table-row-checkbox-disabled': isRowDisabled,
                        }), onClick: (e) => {
                            e.stopPropagation();
                            if (!isRowDisabled) {
                                onRowSelectChange === null || onRowSelectChange === void 0 ? void 0 : onRowSelectChange(rowId, !isRowSelected);
                            }
                        } }, selectionType === 'single' ? (React.createElement(cn_ui_1.CnRadio, { checked: isRowSelected, disabled: isRowDisabled })) : (React.createElement(cn_ui_1.CnCheckbox, { checked: isRowSelected, disabled: isRowDisabled })))))),
                !showIndex && rowSelectionEnabled && (React.createElement("div", { className: (0, classnames_1.default)('ai-table-row-checkbox-only', {
                        'ai-table-row-checkbox-disabled': isRowDisabled,
                    }), onClick: (e) => {
                        e.stopPropagation();
                        if (!isRowDisabled) {
                            onRowSelectChange === null || onRowSelectChange === void 0 ? void 0 : onRowSelectChange(rowId, !isRowSelected);
                        }
                    } }, selectionType === 'single' ? (React.createElement(cn_ui_1.CnRadio, { checked: isRowSelected, disabled: isRowDisabled })) : (React.createElement(cn_ui_1.CnCheckbox, { checked: isRowSelected, disabled: isRowDisabled })))))),
        row.getVisibleCells().map((cell, cellIndex) => {
            var _a, _b, _c;
            const isSelected = selectedColumnId === cell.column.id;
            const cellValue = cell.getValue();
            const columnId = cell.column.id;
            const cellIsEditing = isEditing(row.id, columnId);
            const isEditable = dataModel.isFieldEditable(columnId);
            const fillColors = (0, colorFillUtils_1.getCellColorFillLayers)(row.original, columnId, colorFillRules, dataModel.fieldMap);
            // 每条命中规则生成独立 gradient 层，由浏览器原生 alpha 合成
            const cellFillBg = fillColors.length > 0
                ? fillColors.map((c) => `linear-gradient(${c}, ${c})`).join(', ')
                : undefined;
            const columnWidth = widthMap[columnId] || 200;
            const isPinnedColumn = (_a = pinnedModel === null || pinnedModel === void 0 ? void 0 : pinnedModel.isPinned(columnId)) !== null && _a !== void 0 ? _a : false;
            const isAiColumn = dataModel.isAiColumn(columnId);
            const isCellSelected = !dataModel.supportBatchEdit &&
                !isAiColumn &&
                (selectedCell === null || selectedCell === void 0 ? void 0 : selectedCell.rowId) == rowId &&
                (selectedCell === null || selectedCell === void 0 ? void 0 : selectedCell.columnId) === columnId;
            const isClickable = isEditable || (!dataModel.supportBatchEdit && !isAiColumn) || isAiColumn;
            const cellClassName = (0, classnames_1.default)('ai-table-data-cell', {
                'ai-table-column-selected': isSelected,
                'ai-table-cell-editing': cellIsEditing,
                'ai-table-cell-editing-ai': cellIsEditing && isAiColumn,
                'ai-table-cell-selected': isCellSelected && !cellIsEditing,
                'has-color-fill': fillColors.length > 0,
                'ai-table-cell-readonly': !isEditable,
                'ai-table-sticky-column': isPinnedColumn,
                'ai-table-sticky-column-last': isPinnedColumn && ((_b = pinnedModel === null || pinnedModel === void 0 ? void 0 : pinnedModel.isLastPinned(columnId)) !== null && _b !== void 0 ? _b : false),
            });
            const stickyStyle = isPinnedColumn && pinnedModel
                ? {
                    position: 'sticky',
                    left: (_c = pinnedModel.pinnedOffsets[columnId]) !== null && _c !== void 0 ? _c : 0,
                    zIndex: pinnedModel.getPinnedZIndex(columnId, 10),
                }
                : {};
            return (React.createElement("td", { key: cell.id, className: cellClassName, style: {
                    ['--cell-fill-bg']: cellFillBg || undefined,
                    width: columnWidth,
                    minWidth: columnWidth,
                    // 非冻结格显式压低层级，避免横向滚动时其 box-shadow 盖住右侧冻结列最后一列的阴影（冻结格 z 为 10+Δ）
                    ...(isPinnedColumn ? stickyStyle : { zIndex: 1 }),
                } },
                React.createElement("div", { className: "ai-table-cell-content-wrapper" }, (() => {
                    // 编辑状态
                    if (cellIsEditing && isEditable) {
                        // 获取列的 dataIndex
                        // 根据列元数据选择编辑组件
                        let itemSchema = dataModel.getFieldItem(columnId);
                        // AI 字段没有在 fieldMap 中定义，使用默认的 Input 配置
                        if (!itemSchema) {
                            itemSchema = {
                                type: 'string',
                                'x-decorator': 'CnFormItem',
                                'x-component': 'CnInputTextArea',
                                'x-component-props': {
                                    placeholder: i18n_1.default.get({ id: 'PleaseEnter', dm: '请输入' }),
                                    style: {
                                        width: '100%',
                                    },
                                },
                                'x-decorator-props': {},
                            };
                        }
                        // 重置表单并设置初始值
                        form.setValues({
                            [columnId]: cellValue,
                        });
                        const renderNode = renderCellContent(cell, cellValue, virtualRow.index, row.original);
                        // 为字段添加 onBlur 处理
                        const fieldSchemaWithValue = {
                            ...itemSchema,
                            'x-component-props': {
                                ...itemSchema['x-component-props'],
                            },
                            'x-decorator-props': {
                                ...itemSchema['x-decorator-props'],
                                renderNode,
                                formInstance: form,
                                onSubmit: () => handleSubmit(columnId, row),
                                columnWidth,
                            },
                        };
                        return (React.createElement(cn_ui_1.CnForm, { form: form, hasFooterSubmit: false, components: {
                                ...cn_ui_1.componentMap,
                                ...component_adapter_1.componentAdapterMapForTable,
                                CnFormItem: dropdown_form_item_1.default,
                            }, schema: {
                                type: 'object',
                                properties: {
                                    [columnId]: fieldSchemaWithValue,
                                },
                            } }));
                    }
                    // 默认显示状态
                    return (React.createElement(cell_content_with_tooltip_1.CellContentWithTooltip, { isClickable: isClickable, onClick: (e) => {
                            handleCellClick(row.id, columnId, cellValue, row.original, e);
                        } }, renderCellContent(cell, cellValue, virtualRow.index, row.original)));
                })())));
        }),
        hasOperateColumn && renderOperateCell && (React.createElement("td", { className: "ai-table-data-cell ai-table-operate-column-cell", style: {
                width: operateColumnWidth,
                minWidth: operateColumnWidth,
            } },
            React.createElement("div", { className: "ai-table-cell-content-wrapper" }, renderOperateCell(row.original, virtualRow.index))))));
};
exports.DraggableRow = DraggableRow;
exports.default = exports.DraggableRow;
