import $i18n from '../../../../locales/i18n.js';
import React, { useState } from 'react';
import { observer } from 'mobx-react-lite';
import { CnButton, CnIcon, CnInput, CnDialog } from '@cainiaofe/cn-ui';
import { useModel } from '../../../../utils/mobx-react-simpler/index.js';
import { Popup } from '@cainiaofe/cn-domain-popup';
import { getPopupContainer } from '../../../../utils/floating-layer.js';
import './view-menu.scss';
export const ViewMenu = observer(({ viewId, viewName, trigger, customItems, onCustomItemClick }) => {
    const dataModel = useModel('dataModel');
    const [menuVisible, setMenuVisible] = useState(false);
    const [renameVisible, setRenameVisible] = useState(false);
    const [renameValue, setRenameValue] = useState(viewName);
    const [deleteVisible, setDeleteVisible] = useState(false);
    // 使用 DataModel 的 canDeleteView 方法判断是否可以删除
    const canDelete = dataModel.canDeleteView(viewId);
    // 当 viewName 变化时，更新 renameValue
    React.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.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.createElement(React.Fragment, null,
        React.createElement(Popup, { triggerType: "click", visible: menuVisible, onVisibleChange: setMenuVisible, trigger: trigger, align: "bl", container: getPopupContainer },
            React.createElement("div", { className: "view-menu-popup" }, customItems ? (customItems.map((item) => (React.createElement("div", { key: item.key, className: "view-menu-item", onClick: () => {
                    setMenuVisible(false);
                    onCustomItemClick === null || onCustomItemClick === void 0 ? void 0 : onCustomItemClick(item.key);
                } },
                React.createElement("span", { className: "view-menu-item-icon" }, item.icon),
                React.createElement("span", { className: "view-menu-item-text" }, item.label))))) : (React.createElement(React.Fragment, null,
                React.createElement("div", { className: "view-menu-item", onClick: handleRename },
                    React.createElement(CnIcon, { type: "edit", size: "small", className: "view-menu-item-icon" }),
                    React.createElement("span", { className: "view-menu-item-text" }, $i18n.get({ id: 'Rename', dm: '重命名' }))),
                React.createElement("div", { className: "view-menu-item", onClick: handleCopyView },
                    React.createElement(CnIcon, { type: "copy", size: "small", className: "view-menu-item-icon" }),
                    React.createElement("span", { className: "view-menu-item-text" }, $i18n.get({ id: 'CopyViewCopy', dm: '拷贝视图副本' }))),
                canDelete && (React.createElement("div", { className: "view-menu-item view-menu-item-danger", onClick: handleDelete },
                    React.createElement(CnIcon, { type: "delete", size: "small", className: "view-menu-item-icon" }),
                    React.createElement("span", { className: "view-menu-item-text" }, $i18n.get({ id: 'DeleteView', dm: '删除视图' })))))))),
        React.createElement(CnDialog, { visible: renameVisible, onClose: handleRenameCancel, title: $i18n.get({ id: 'RenameView', dm: '重命名视图' }), size: "small", className: "view-rename-dialog", okProps: { visible: false }, cancelProps: { visible: false }, footer: React.createElement(React.Fragment, null,
                React.createElement(CnButton, { onClick: handleRenameCancel }, $i18n.get({ id: 'Cancel', dm: '取消' })),
                React.createElement(CnButton, { type: "primary", onClick: handleRenameConfirm, disabled: !renameValue.trim() }, $i18n.get({ id: 'OK', dm: '确定' }))) },
            React.createElement(CnInput, { value: renameValue, onChange: setRenameValue, placeholder: $i18n.get({ id: 'PleaseEnterAViewName', dm: '请输入视图名称' }), autoFocus: true, onPressEnter: handleRenameConfirm, onMouseDown: (e) => e.stopPropagation(), onPointerDown: (e) => e.stopPropagation() })),
        React.createElement(CnDialog, { visible: deleteVisible, size: "small", onClose: handleDeleteCancel, title: $i18n.get({ id: 'DeleteView', dm: '删除视图' }), okProps: {
                children: $i18n.get({ id: 'DeleteView', dm: '删除视图' }),
            }, cancelProps: {
                children: $i18n.get({ id: 'Cancel', dm: '取消' }),
            }, onOk: handleDeleteConfirm, onCancel: handleDeleteCancel },
            React.createElement("span", null,
                $i18n.get({ id: 'MakeSureYouWantToDeleteTheView', dm: '确定要删除视图 「' }),
                viewName,
                $i18n.get({
                    id: 'DeletingAViewDoesNotDeleteData',
                    dm: '」吗？删除视图不会删除数据，不会影响其他视图。',
                })))));
});
