"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.ViewMenu = void 0;
const i18n_1 = __importDefault(require("../../../../locales/i18n.js"));
const react_1 = __importStar(require("react"));
const mobx_react_lite_1 = require("mobx-react-lite");
const cn_ui_1 = require("@cainiaofe/cn-ui");
const mobx_react_simpler_1 = require("../../../../utils/mobx-react-simpler/index.js");
const cn_domain_popup_1 = require("@cainiaofe/cn-domain-popup");
const floating_layer_1 = require("../../../../utils/floating-layer.js");
require("./view-menu.scss");
exports.ViewMenu = (0, mobx_react_lite_1.observer)(({ viewId, viewName, trigger, customItems, onCustomItemClick }) => {
    const dataModel = (0, mobx_react_simpler_1.useModel)('dataModel');
    const [menuVisible, setMenuVisible] = (0, react_1.useState)(false);
    const [renameVisible, setRenameVisible] = (0, react_1.useState)(false);
    const [renameValue, setRenameValue] = (0, react_1.useState)(viewName);
    const [deleteVisible, setDeleteVisible] = (0, react_1.useState)(false);
    // 使用 DataModel 的 canDeleteView 方法判断是否可以删除
    const canDelete = dataModel.canDeleteView(viewId);
    // 当 viewName 变化时，更新 renameValue
    react_1.default.useEffect(() => {
        if (!renameVisible) {
            setRenameValue(viewName);
        }
    }, [viewName, renameVisible]);
    // 处理重命名
    const handleRename = () => {
        setMenuVisible(false);
        setRenameVisible(true);
        setRenameValue(viewName);
    };
    const handleRenameConfirm = () => {
        if (renameValue.trim()) {
            dataModel.setViewConfig(viewId, {
                name: renameValue.trim(),
            }, true);
            setRenameVisible(false);
            setRenameValue('');
            dataModel.updateRemoteViews();
        }
    };
    const handleRenameCancel = () => {
        setRenameVisible(false);
        setRenameValue(viewName);
    };
    // 处理拷贝视图副本
    const handleCopyView = () => {
        setMenuVisible(false);
        const viewConfig = dataModel.getViewConfig(viewId);
        if (viewConfig) {
            // 生成新视图名称（原名称 + " (副本)"）
            const newName = i18n_1.default.get({
                id: 'ViewNameCopy',
                dm: '{viewName} (副本)',
            }, { viewName });
            // 创建新视图，直接传入源视图的配置，一次完成创建和配置
            dataModel.createView(viewConfig.type, newName, {
                columnOrder: viewConfig.columnOrder ? [...viewConfig.columnOrder] : [],
                hiddenColumns: viewConfig.hiddenColumns ? [...viewConfig.hiddenColumns] : [],
                filter: Array.isArray(viewConfig.filter) ? [...viewConfig.filter] : [],
                sort: Array.isArray(viewConfig.sort) ? [...viewConfig.sort] : [],
                group: Array.isArray(viewConfig.group) ? [...viewConfig.group] : [],
                aggregate: viewConfig.aggregate ? { ...viewConfig.aggregate } : {},
                custom: viewConfig.custom ? { ...viewConfig.custom } : {},
                colorFill: Array.isArray(viewConfig.colorFill)
                    ? viewConfig.colorFill.map((rule) => ({ ...rule }))
                    : [],
            });
        }
    };
    // 处理删除视图
    const handleDelete = () => {
        setMenuVisible(false);
        setDeleteVisible(true);
    };
    const handleDeleteConfirm = () => {
        dataModel.deleteView(viewId);
        setDeleteVisible(false);
    };
    const handleDeleteCancel = () => {
        setDeleteVisible(false);
    };
    return (react_1.default.createElement(react_1.default.Fragment, null,
        react_1.default.createElement(cn_domain_popup_1.Popup, { triggerType: "click", visible: menuVisible, onVisibleChange: setMenuVisible, trigger: trigger, align: "bl", container: floating_layer_1.getPopupContainer },
            react_1.default.createElement("div", { className: "view-menu-popup" }, customItems ? (customItems.map((item) => (react_1.default.createElement("div", { key: item.key, className: "view-menu-item", onClick: () => {
                    setMenuVisible(false);
                    onCustomItemClick === null || onCustomItemClick === void 0 ? void 0 : onCustomItemClick(item.key);
                } },
                react_1.default.createElement("span", { className: "view-menu-item-icon" }, item.icon),
                react_1.default.createElement("span", { className: "view-menu-item-text" }, item.label))))) : (react_1.default.createElement(react_1.default.Fragment, null,
                react_1.default.createElement("div", { className: "view-menu-item", onClick: handleRename },
                    react_1.default.createElement(cn_ui_1.CnIcon, { type: "edit", size: "small", className: "view-menu-item-icon" }),
                    react_1.default.createElement("span", { className: "view-menu-item-text" }, i18n_1.default.get({ id: 'Rename', dm: '重命名' }))),
                react_1.default.createElement("div", { className: "view-menu-item", onClick: handleCopyView },
                    react_1.default.createElement(cn_ui_1.CnIcon, { type: "copy", size: "small", className: "view-menu-item-icon" }),
                    react_1.default.createElement("span", { className: "view-menu-item-text" }, i18n_1.default.get({ id: 'CopyViewCopy', dm: '拷贝视图副本' }))),
                canDelete && (react_1.default.createElement("div", { className: "view-menu-item view-menu-item-danger", onClick: handleDelete },
                    react_1.default.createElement(cn_ui_1.CnIcon, { type: "delete", size: "small", className: "view-menu-item-icon" }),
                    react_1.default.createElement("span", { className: "view-menu-item-text" }, i18n_1.default.get({ id: 'DeleteView', dm: '删除视图' })))))))),
        react_1.default.createElement(cn_ui_1.CnDialog, { visible: renameVisible, onClose: handleRenameCancel, title: i18n_1.default.get({ id: 'RenameView', dm: '重命名视图' }), size: "small", className: "view-rename-dialog", okProps: { visible: false }, cancelProps: { visible: false }, footer: react_1.default.createElement(react_1.default.Fragment, null,
                react_1.default.createElement(cn_ui_1.CnButton, { onClick: handleRenameCancel }, i18n_1.default.get({ id: 'Cancel', dm: '取消' })),
                react_1.default.createElement(cn_ui_1.CnButton, { type: "primary", onClick: handleRenameConfirm, disabled: !renameValue.trim() }, i18n_1.default.get({ id: 'OK', dm: '确定' }))) },
            react_1.default.createElement(cn_ui_1.CnInput, { value: renameValue, onChange: setRenameValue, placeholder: i18n_1.default.get({ id: 'PleaseEnterAViewName', dm: '请输入视图名称' }), autoFocus: true, onPressEnter: handleRenameConfirm, onMouseDown: (e) => e.stopPropagation(), onPointerDown: (e) => e.stopPropagation() })),
        react_1.default.createElement(cn_ui_1.CnDialog, { visible: deleteVisible, size: "small", onClose: handleDeleteCancel, title: i18n_1.default.get({ id: 'DeleteView', dm: '删除视图' }), okProps: {
                children: i18n_1.default.get({ id: 'DeleteView', dm: '删除视图' }),
            }, cancelProps: {
                children: i18n_1.default.get({ id: 'Cancel', dm: '取消' }),
            }, onOk: handleDeleteConfirm, onCancel: handleDeleteCancel },
            react_1.default.createElement("span", null,
                i18n_1.default.get({ id: 'MakeSureYouWantToDeleteTheView', dm: '确定要删除视图 「' }),
                viewName,
                i18n_1.default.get({
                    id: 'DeletingAViewDoesNotDeleteData',
                    dm: '」吗？删除视图不会删除数据，不会影响其他视图。',
                })))));
});
