"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.useCellEditing = useCellEditing;
const i18n_1 = __importDefault(require("../../locales/i18n.js"));
const React = __importStar(require("react"));
const arms_hot_tag_log_1 = require("../../utils/arms/arms-hot-tag-log.js");
const cell_event_utils_1 = require("../../cn-ai-table/view/components/views/table-view/utils/cell-event-utils");
const cn_ai_list_event_context_1 = require("../../cn-ai-agent/context/cn-ai-list-event-context");
/**
 * 单元格编辑功能 Hook
 * @param onSave 保存回调函数，参数为 (rowId, columnId, value, originalRow)
 * @param columns 列配置数组，用于提取格式化后的显示值
 */
function useCellEditing(onSave, columns) {
    const cnAiListEventNames = (0, cn_ai_list_event_context_1.useCnAiListEventNames)();
    // 编辑状态：正在编辑的单元格
    const [editingCell, setEditingCell] = React.useState(null);
    // 编辑值
    const [editingValue, setEditingValue] = React.useState('');
    // 处理单元格点击事件
    const handleCellClick = React.useCallback((rowId, columnId, currentValue, originalRow, event) => {
        event.stopPropagation(); // 阻止事件冒泡
        (0, arms_hot_tag_log_1.armsHottagLog)({
            hottag: 'cn-ai-table.cell.clickEdit',
            name: i18n_1.default.get({ id: 'ClickEdit', dm: '点击编辑' }),
            c6: rowId,
            c7: columnId,
        });
        setEditingCell({ rowId, columnId, originalRow });
        const valueStr = currentValue != null ? String(currentValue) : '';
        setEditingValue(valueStr);
        // 触发自定义事件，通知 AI Agent 组件单元格被选中（使用工具函数）
        (0, cell_event_utils_1.emitCellSelectEvent)(columnId, currentValue, originalRow, rowId, event, undefined, columns, cnAiListEventNames);
    }, [columns, cnAiListEventNames]);
    // 自动调整 textarea 高度的 effect
    React.useEffect(() => {
        if (editingCell) {
            // 延迟执行，确保 textarea 已渲染
            setTimeout(() => {
                const textarea = document.querySelector('.ai-table-cell-input');
                if (textarea) {
                    textarea.style.height = 'auto';
                    textarea.style.height = `${textarea.scrollHeight}px`;
                }
            }, 0);
        }
    }, [editingCell, editingValue]);
    // 处理 textarea 内容变化，自动调整高度
    const handleTextareaChange = React.useCallback((e) => {
        setEditingValue(e.target.value);
        // 自动调整高度
        e.target.style.height = 'auto';
        e.target.style.height = `${e.target.scrollHeight}px`;
    }, []);
    // 处理输入框失去焦点，保存数据
    const handleCellBlur = React.useCallback(() => {
        if (editingCell && onSave) {
            (0, arms_hot_tag_log_1.armsHottagLog)({
                hottag: 'cn-ai-table.cell.save',
                name: i18n_1.default.get({ id: 'Save', dm: '保存' }),
                c6: editingCell.rowId,
                c7: editingCell.columnId,
            });
            onSave(editingCell.rowId, editingCell.columnId, editingValue, editingCell.originalRow);
        }
        setEditingCell(null);
        setEditingValue('');
    }, [editingCell, editingValue, onSave]);
    // 处理 textarea 键盘事件
    const handleTextareaKeyDown = React.useCallback((e) => {
        // Ctrl+Enter 或 Cmd+Enter 保存
        if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
            e.preventDefault();
            if (editingCell && onSave) {
                (0, arms_hot_tag_log_1.armsHottagLog)({
                    hottag: 'cn-ai-table.cell.save',
                    name: i18n_1.default.get({ id: 'Save', dm: '保存' }),
                    c6: editingCell.rowId,
                    c7: editingCell.columnId,
                });
                onSave(editingCell.rowId, editingCell.columnId, editingValue, editingCell.originalRow);
            }
            setEditingCell(null);
            setEditingValue('');
        }
        else if (e.key === 'Escape') {
            (0, arms_hot_tag_log_1.armsHottagLog)({
                hottag: 'cn-ai-table.cell.cancelEdit',
                name: i18n_1.default.get({ id: 'CancelEdit', dm: '取消编辑' }),
            });
            setEditingCell(null);
            setEditingValue('');
        }
        // 普通 Enter 键允许换行，不阻止默认行为
    }, [editingCell, editingValue, onSave]);
    // 判断单元格是否正在编辑
    const isEditing = React.useCallback((rowId, columnId) => {
        return (editingCell === null || editingCell === void 0 ? void 0 : editingCell.rowId) === rowId && (editingCell === null || editingCell === void 0 ? void 0 : editingCell.columnId) === columnId;
    }, [editingCell]);
    return {
        editingCell: editingCell,
        editingValue,
        setEditingValue,
        setEditingCell,
        handleCellClick,
        handleTextareaChange,
        handleCellBlur,
        handleTextareaKeyDown,
        isEditing,
    };
}
