"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.AiCellActions = void 0;
const i18n_1 = __importDefault(require("../../../../../../../locales/i18n.js"));
const react_1 = __importStar(require("react"));
const react_dom_1 = __importDefault(require("react-dom"));
const cn_ui_1 = require("@cainiaofe/cn-ui");
const cn_domain_popup_1 = require("@cainiaofe/cn-domain-popup");
const use_ai_table_icons_1 = require("../../../../../../../cn-ai-table/view/hooks/use-ai-table-icons");
const arms_hot_tag_log_1 = require("../../../../../../../utils/arms/arms-hot-tag-log.js");
require("./ai-cell-actions.scss");
/**
 * AI 单元格操作按钮组件
 * 选中 AI 单元格时，在单元格外部右边显示操作按钮
 * 点击展开按钮时弹出编辑/预览弹窗
 */
const AiCellActions = ({ visible, position, cellLeft = 0, cellValue = '', fieldName, onSave, onRegenerate, }) => {
    const icons = (0, use_ai_table_icons_1.useAiTableIcons)();
    const [popupVisible, setPopupVisible] = (0, react_1.useState)(false);
    const [mode, setMode] = (0, react_1.useState)('edit');
    const [editValue, setEditValue] = (0, react_1.useState)(cellValue);
    // 使用 ref 保存最新的 editValue，避免闭包问题
    const editValueRef = (0, react_1.useRef)(editValue);
    // 使用 ref 保存初始的 cellValue，用于比较是否有变化
    const initialCellValueRef = (0, react_1.useRef)(cellValue);
    // 同步外部 cellValue 变化
    (0, react_1.useEffect)(() => {
        setEditValue(cellValue);
        editValueRef.current = cellValue;
        initialCellValueRef.current = cellValue;
    }, [cellValue]);
    // 当 visible 变为 false 时，关闭弹窗
    (0, react_1.useEffect)(() => {
        if (!visible) {
            setPopupVisible(false);
        }
    }, [visible]);
    // 当弹窗打开时，重置初始值引用
    (0, react_1.useEffect)(() => {
        if (popupVisible) {
            initialCellValueRef.current = editValueRef.current;
        }
    }, [popupVisible]);
    // 处理弹窗关闭，自动保存
    const handlePopupVisibleChange = (newVisible) => {
        // 当弹窗从打开变为关闭时，自动保存
        if (popupVisible && !newVisible && mode === 'edit') {
            // 使用 ref 获取最新的值，避免闭包问题
            const latestValue = editValueRef.current;
            const initialValue = initialCellValueRef.current;
            // 如果值有变化，则保存
            if (latestValue !== initialValue) {
                (0, arms_hot_tag_log_1.armsHottagLog)({
                    hottag: 'cn-ai-table.aiField.save',
                    name: i18n_1.default.get({ id: 'Save', dm: '保存' }),
                    c6: fieldName,
                });
                onSave === null || onSave === void 0 ? void 0 : onSave(latestValue);
            }
        }
        setPopupVisible(newVisible);
    };
    if (!visible)
        return null;
    // 弹窗内容
    const popupContent = (react_1.default.createElement("div", { className: "ai-cell-content-popup", onClick: (e) => e.stopPropagation() },
        react_1.default.createElement("div", { className: "ai-cell-content-popup-header" },
            react_1.default.createElement("div", { className: "ai-cell-content-popup-title" },
                react_1.default.createElement("img", { src: icons.FIELD_AI, alt: i18n_1.default.get({ id: 'AIField', dm: 'AI字段' }), style: { width: '16px', height: '16px' } }),
                react_1.default.createElement("span", null, fieldName || i18n_1.default.get({ id: 'AIField.55YiI', dm: 'AI 字段' }))),
            react_1.default.createElement("div", { className: "ai-cell-content-popup-tabs" },
                react_1.default.createElement(cn_ui_1.CnButton, { type: "normal", onClick: () => {
                        const newMode = mode === 'preview' ? 'edit' : 'preview';
                        (0, arms_hot_tag_log_1.armsHottagLog)({
                            hottag: newMode === 'edit'
                                ? 'cn-ai-table.aiField.switchToEdit'
                                : 'cn-ai-table.aiField.switchToPreview',
                            name: newMode === 'edit'
                                ? i18n_1.default.get({ id: 'SwitchToEdit', dm: '切换到编辑' })
                                : i18n_1.default.get({ id: 'SwitchToPreview', dm: '切换到预览' }),
                            c6: fieldName,
                        });
                        setMode(newMode);
                    } }, mode === 'edit'
                    ? i18n_1.default.get({ id: 'Preview', dm: '预览' })
                    : i18n_1.default.get({ id: 'Edit', dm: '编辑' }))),
            react_1.default.createElement(cn_ui_1.CnIcon, { type: "close", size: "small", className: "ai-cell-content-popup-close", onClick: () => handlePopupVisibleChange(false) })),
        react_1.default.createElement("div", { className: "ai-cell-content-popup-body" },
            react_1.default.createElement(cn_ui_1.CnInputTextArea, { value: editValue, style: { width: '100%' }, onChange: (val) => {
                    const newValue = val;
                    setEditValue(newValue);
                    // 同步更新 ref，确保保存时能获取到最新值
                    editValueRef.current = newValue;
                }, placeholder: i18n_1.default.get({ id: 'PleaseEnterContent.TvWOC', dm: '请输入内容' }), autoHeight: { minRows: 10, maxRows: 20 }, readOnly: mode === 'preview' }))));
    const content = (react_1.default.createElement("div", { className: "ai-cell-actions", style: {
            top: position.top,
            left: position.left,
        } },
        react_1.default.createElement("span", { style: { display: 'contents' }, onClick: (e) => e.stopPropagation(), onPointerDown: (e) => e.stopPropagation() },
            react_1.default.createElement(cn_domain_popup_1.Popup, { visible: popupVisible, onVisibleChange: handlePopupVisibleChange, triggerType: "click", align: "br", offset: { mainAxis: 20, crossAxis: -20 }, trigger: react_1.default.createElement(cn_ui_1.CnIcon, { type: "eye", className: "ai-cell-actions-btn" }) }, popupContent)),
        react_1.default.createElement(cn_ui_1.CnIcon, { type: "refresh", className: "ai-cell-actions-btn", onClick: (e) => {
                e.stopPropagation();
                (0, arms_hot_tag_log_1.armsHottagLog)({
                    hottag: 'cn-ai-table.aiField.regenerate',
                    name: i18n_1.default.get({ id: 'Regenerate', dm: '重新生成' }),
                    c6: fieldName,
                });
                onRegenerate === null || onRegenerate === void 0 ? void 0 : onRegenerate();
            } })));
    // 挂载到 body，避免菜包等场景下父级 transform/overflow 导致 position:fixed 相对错误容器而错位
    if (typeof document !== 'undefined' && document.body) {
        return react_dom_1.default.createPortal(content, document.body);
    }
    return content;
};
exports.AiCellActions = AiCellActions;
exports.default = exports.AiCellActions;
