import $i18n from '../../../../locales/i18n.js';
import React, { useEffect, useState, useRef } from 'react';
import classNames from 'classnames';
import isEqual from 'lodash/isEqual';
import { CnBox } from '@cainiaofe/cn-ui';
import { useModel } from '../../../../utils/mobx-react-simpler/index.js';
import { FieldManagementButton } from './components/field-management/field-management-button';
import { FilterButton } from './components/filter/filter-button';
import { GroupButton } from './components/group/group-button';
import { SortButton } from './components/sort/sort-button';
import { ColorFillButton } from './components/color-fill/color-fill-button';
// import { ComponentButton } from './components/component/component-button';
// import { UndoButton } from './components/undo/undo-button';
// import { RedoButton } from './components/redo/redo-button';
import { AddFieldButton } from './components/add-field/add-field-button';
import { ToolbarNotification } from './toolbar-notification';
import NormalToolbar from './normal-toolbar';
import { armsHottagLog } from '../../../../utils/arms/arms-hot-tag-log.js';
import './toolbar.scss';
const cloneArray = (value) => {
    return value ? JSON.parse(JSON.stringify(value)) : [];
};
const createSnapshot = (config) => ({
    filter: cloneArray(config.filter),
    sort: cloneArray(config.sort),
    group: cloneArray(config.group),
    colorFill: cloneArray(config.colorFill),
});
/** 不需要填写值的操作符（筛选、填色共用） */
const OPERATORS_NO_VALUE = new Set(['empty', 'notEmpty']);
const isValueEmpty = (val) => val === undefined || val === null || String(val).trim() === '';
const operatorRequiresValue = (operator) => !OPERATORS_NO_VALUE.has(operator || '');
/**
 * 校验「需要值的操作符」下值是否未填（不可保存）；用于筛选、填色
 * @param items 条件列表
 * @param options.skip 返回 true 时跳过该条（如填色的 scope===column）
 */
function getSaveValidationHasError(items, options) {
    if (!(items === null || items === void 0 ? void 0 : items.length))
        return false;
    const { skip } = options !== null && options !== void 0 ? options : {};
    for (const item of items) {
        if (!(item === null || item === void 0 ? void 0 : item.field))
            continue;
        if (skip === null || skip === void 0 ? void 0 : skip(item))
            continue;
        if (!operatorRequiresValue(item.operator))
            continue;
        if (isValueEmpty(item.value))
            return true;
    }
    return false;
}
export function Toolbar({ viewId, enableAiFields = true, enableLookup = true, enableFormula = true, toolbarVisible = true, permissions = {
    addRecord: true,
    fieldManagement: true,
    viewConfig: true,
    filter: true,
    sort: true,
    group: true,
    colorFill: true,
    component: false, // TODO: 组件功能后续实现，暂时隐藏
}, onFieldVisibilityChange, onFilterChange, onSortChange, onGroupChange, onColorFillChange, renderRightContent, renderLeftContent, groupMaxLevels = 1, showFilterPanelTrigger, showSortPanelTrigger, showGroupPanelTrigger, showColorFillPanelTrigger, 
// NormalToolbar 相关属性
batchArea, toolArea, buttonSize, selectKeys, storeSelectInfo, }) {
    const dataModel = useModel('dataModel');
    const [notificationType, setNotificationType] = useState(null);
    const [notificationVisible, setNotificationVisible] = useState(false);
    const [justSaved, setJustSaved] = useState(false);
    const [notificationClosing, setNotificationClosing] = useState(false);
    const [savedChangedCount, setSavedChangedCount] = useState(1); // 保存时的变化数量，用于显示"多个配置已保存"
    const saveCloseTimerRef = useRef(null);
    const closeTimerRef = useRef(null);
    const rafRef = useRef(null);
    // 监听 notificationType 变化，延一帧再设置 visible，确保入场 transition 生效
    useEffect(() => {
        if (notificationType && !notificationClosing) {
            if (rafRef.current)
                cancelAnimationFrame(rafRef.current);
            setNotificationVisible(false);
            rafRef.current = requestAnimationFrame(() => {
                setNotificationVisible(true);
                rafRef.current = null;
            });
        }
        else {
            setNotificationVisible(false);
        }
    }, [notificationType, notificationClosing]);
    // 统一关闭通知栏的函数，带退出动画
    const closeNotification = (callback) => {
        if (closeTimerRef.current) {
            clearTimeout(closeTimerRef.current);
        }
        setNotificationClosing(true);
        closeTimerRef.current = setTimeout(() => {
            setNotificationType(null);
            setNotificationClosing(false);
            setJustSaved(false);
            setSavedChangedCount(1); // 重置变化数量
            closeTimerRef.current = null;
            callback === null || callback === void 0 ? void 0 : callback();
        }, 280); // 与 CSS transition 时间一致
    };
    const [viewConfigSnapshot, setViewConfigSnapshot] = useState(() => createSnapshot(dataModel.getViewConfig(viewId)));
    const [isToolbarCompact, setIsToolbarCompact] = useState(false);
    const toolbarContainerRef = useRef(null);
    // 清理延时器
    useEffect(() => {
        return () => {
            if (saveCloseTimerRef.current)
                clearTimeout(saveCloseTimerRef.current);
            if (closeTimerRef.current)
                clearTimeout(closeTimerRef.current);
            if (rafRef.current)
                cancelAnimationFrame(rafRef.current);
        };
    }, []);
    // 切换视图时同步快照（通知栏仅在手点取消/保存时关闭）
    useEffect(() => {
        setViewConfigSnapshot(createSnapshot(dataModel.getViewConfig(viewId)));
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [viewId]);
    // 监听各种面板触发器的变化，显示对应的条件设置面板
    useEffect(() => {
        if (showFilterPanelTrigger && showFilterPanelTrigger > 0) {
            setNotificationType('filter');
        }
    }, [showFilterPanelTrigger]);
    useEffect(() => {
        if (showSortPanelTrigger && showSortPanelTrigger > 0) {
            setNotificationType('sort');
        }
    }, [showSortPanelTrigger]);
    useEffect(() => {
        if (showGroupPanelTrigger && showGroupPanelTrigger > 0) {
            setNotificationType('group');
        }
    }, [showGroupPanelTrigger]);
    useEffect(() => {
        if (showColorFillPanelTrigger && showColorFillPanelTrigger > 0) {
            setNotificationType('colorFill');
        }
    }, [showColorFillPanelTrigger]);
    // 响应式布局：检测表格容器宽度变化，决定是否只显示图标
    useEffect(() => {
        const containerElement = toolbarContainerRef.current;
        if (!containerElement) {
            return;
        }
        // 查找表格容器（.cn-mutiply-ai-table-main）
        const findTableContainer = (element) => {
            var _a;
            if (!element)
                return null;
            // 向上查找包含 .cn-mutiply-ai-table-main 的容器
            let current = element;
            while (current) {
                if ((_a = current.classList) === null || _a === void 0 ? void 0 : _a.contains('cn-mutiply-ai-table-container')) {
                    return current;
                }
                current = current.parentElement;
            }
            return null;
        };
        const tableContainer = findTableContainer(containerElement);
        if (!tableContainer) {
            return;
        }
        // 检查容器宽度
        const checkWidth = () => {
            const containerWidth = tableContainer.offsetWidth;
            // 当表格容器宽度小于 1200px 时，只显示图标
            setIsToolbarCompact(containerWidth < 800);
        };
        // 立即检查一次
        checkWidth();
        // 使用 ResizeObserver 监听表格容器宽度变化
        const resizeObserver = new ResizeObserver(() => {
            checkWidth();
        });
        resizeObserver.observe(tableContainer);
        return () => {
            resizeObserver.disconnect();
        };
    }, []);
    const handleAddFilterCondition = () => {
        armsHottagLog({
            hottag: 'cn-ai-table.filter',
            name: $i18n.get({ id: 'Filter', dm: '筛选' }),
        });
        setNotificationType('filter');
    };
    const handleAddSortCondition = () => {
        armsHottagLog({
            hottag: 'cn-ai-table.sort',
            name: $i18n.get({ id: 'Sort', dm: '排序' }),
        });
        setNotificationType('sort');
    };
    const handleAddGroupCondition = () => {
        armsHottagLog({
            hottag: 'cn-ai-table.group',
            name: $i18n.get({ id: 'Grouping', dm: '分组' }),
        });
        setNotificationType('group');
    };
    const handleAddColorFillCondition = () => {
        armsHottagLog({
            hottag: 'cn-ai-table.colorFill',
            name: $i18n.get({ id: 'Fill', dm: '填色' }),
        });
        setNotificationType('colorFill');
    };
    const handleConditionCleared = (type) => {
        if (notificationType !== type) {
            const hottagMap = {
                filter: 'cn-ai-table.filter.clear',
                sort: 'cn-ai-table.sort.clear',
                group: 'cn-ai-table.group.clear',
                colorFill: 'cn-ai-table.colorFill.clear',
            };
            const nameMap = {
                filter: $i18n.get({ id: 'EmptyFilterCriteria', dm: '清空筛选条件' }),
                sort: $i18n.get({ id: 'ClearSortCondition', dm: '清空排序条件' }),
                group: $i18n.get({ id: 'ClearGroupingCondition', dm: '清空分组条件' }),
                colorFill: $i18n.get({ id: 'EmptyFillCondition', dm: '清空填色条件' }),
            };
            armsHottagLog({
                hottag: hottagMap[type],
                name: nameMap[type],
            });
            setNotificationType(type);
        }
        else {
            // 当前类型下条件被全部清空：保持通知栏显示，仅用户点击取消/保存时关闭
        }
    };
    const handleNotificationCancel = () => {
        if (!notificationType) {
            return;
        }
        const hottagMap = {
            filter: 'cn-ai-table.filter.cancel',
            sort: 'cn-ai-table.sort.cancel',
            group: 'cn-ai-table.group.cancel',
            colorFill: 'cn-ai-table.colorFill.cancel',
        };
        armsHottagLog({
            hottag: hottagMap[notificationType],
            name: $i18n.get({ id: 'Cancel', dm: '取消' }),
        });
        if (saveCloseTimerRef.current) {
            clearTimeout(saveCloseTimerRef.current);
            saveCloseTimerRef.current = null;
        }
        // 还原上一次保存的视图配置，然后关闭通知栏
        dataModel.setViewConfig(viewId, {
            filter: cloneArray(viewConfigSnapshot.filter),
            sort: cloneArray(viewConfigSnapshot.sort),
            group: cloneArray(viewConfigSnapshot.group),
            colorFill: cloneArray(viewConfigSnapshot.colorFill),
        });
        closeNotification();
    };
    const handleNotificationSave = () => {
        if (!notificationType)
            return;
        const viewConfig = dataModel.getViewConfig(viewId);
        // 检查哪些配置项满足保存条件，不满足的将被"丢弃"（恢复为快照状态）
        const canSaveFilter = !getSaveValidationHasError(viewConfig.filter);
        const canSaveColorFill = !getSaveValidationHasError(viewConfig.colorFill, {
            skip: (item) => item.scope === 'column',
        });
        // 如果当前操作的类型不满足保存条件，直接返回
        if (notificationType === 'filter' && !canSaveFilter) {
            return;
        }
        if (notificationType === 'colorFill' && !canSaveColorFill) {
            return;
        }
        // 构建最终保存的配置：满足条件的用当前值，不满足的用快照值（丢弃变更）
        const finalConfig = {
            ...viewConfig,
            filter: canSaveFilter ? viewConfig.filter : cloneArray(viewConfigSnapshot.filter),
            colorFill: canSaveColorFill ? viewConfig.colorFill : cloneArray(viewConfigSnapshot.colorFill),
        };
        // 计算实际保存的配置项数量（用于文案显示）
        const actuallySavedCount = [
            canSaveFilter && !isEqual(viewConfig.filter, viewConfigSnapshot.filter),
            canSaveColorFill && !isEqual(viewConfig.colorFill, viewConfigSnapshot.colorFill),
            !isEqual(viewConfig.sort, viewConfigSnapshot.sort),
            !isEqual(viewConfig.group, viewConfigSnapshot.group),
        ].filter(Boolean).length;
        const hottagMap = {
            filter: 'cn-ai-table.filter.save',
            sort: 'cn-ai-table.sort.save',
            group: 'cn-ai-table.group.save',
            colorFill: 'cn-ai-table.colorFill.save',
        };
        armsHottagLog({
            hottag: hottagMap[notificationType],
            name: $i18n.get({ id: 'Save', dm: '保存' }),
        });
        // 应用最终配置并保存到远程
        dataModel.setViewConfig(viewId, finalConfig);
        dataModel.updateRemoteViews();
        setViewConfigSnapshot(createSnapshot(finalConfig));
        // 记录实际保存的变化数量，用于显示"多个配置已保存"
        setSavedChangedCount(actuallySavedCount || 1);
        // 仅做效果优化：进入「已保存」状态并播退出动画后关闭（不改变原有「保存后关闭」规则）
        setJustSaved(true);
        if (saveCloseTimerRef.current)
            clearTimeout(saveCloseTimerRef.current);
        saveCloseTimerRef.current = setTimeout(() => {
            closeNotification();
        }, 800); // 显示「已保存」状态 800ms 后再关闭
    };
    // 重置配置信息 注意：测试用
    // const handleResetConfig = async () => {
    //   await dataModel.resetViewConfig(viewId);
    //   setNotificationType(null);
    //   setViewConfigSnapshot(createSnapshot(dataModel.getViewConfig(viewId)));
    // };
    const hasAnyFieldType = enableAiFields || enableLookup || enableFormula;
    const currentViewConfig = dataModel.getViewConfig(viewId);
    const currentSnapshot = createSnapshot(currentViewConfig);
    // 计算哪些配置项发生了变化
    const changedTypes = [];
    if (!isEqual(currentSnapshot.filter, viewConfigSnapshot.filter)) {
        changedTypes.push('filter');
    }
    if (!isEqual(currentSnapshot.sort, viewConfigSnapshot.sort)) {
        changedTypes.push('sort');
    }
    if (!isEqual(currentSnapshot.group, viewConfigSnapshot.group)) {
        changedTypes.push('group');
    }
    if (!isEqual(currentSnapshot.colorFill, viewConfigSnapshot.colorFill)) {
        changedTypes.push('colorFill');
    }
    const changedCount = changedTypes.length;
    // 筛选/填色：需要值的条件未填值则禁用保存按钮
    let saveDisabled = false;
    if (notificationType === 'filter') {
        saveDisabled = getSaveValidationHasError(currentViewConfig.filter);
    }
    else if (notificationType === 'colorFill') {
        saveDisabled = getSaveValidationHasError(currentViewConfig.colorFill, {
            skip: (item) => item.scope === 'column',
        });
    }
    return (React.createElement("div", { className: "toolbar-container", ref: toolbarContainerRef },
        React.createElement("div", { className: "toolbar-content" },
            React.createElement(CnBox, { direction: "row", spacing: 0, className: "toolbar-left" },
                React.createElement(NormalToolbar, { batchArea: batchArea, toolArea: toolArea, buttonSize: buttonSize, selectKeys: selectKeys, storeSelectInfo: storeSelectInfo })),
            toolbarVisible && (React.createElement("div", { className: "toolbar-center-right" },
                React.createElement("div", { className: classNames('toolbar-right', {
                        'toolbar-right-compact': isToolbarCompact,
                    }) },
                    notificationType && (React.createElement(ToolbarNotification, { type: notificationType, visible: !notificationClosing && notificationVisible, closing: notificationClosing, onCancel: handleNotificationCancel, onSave: handleNotificationSave, saveDisabled: saveDisabled, changedCount: justSaved ? savedChangedCount : changedCount })),
                    permissions.fieldManagement && (React.createElement(FieldManagementButton, { viewId: viewId, onFieldVisibilityChange: onFieldVisibilityChange, isCompact: isToolbarCompact, enableAiFields: enableAiFields, enableLookup: enableLookup, enableFormula: enableFormula })),
                    renderLeftContent && renderLeftContent({ isCompact: isToolbarCompact }),
                    permissions.filter && (React.createElement(FilterButton, { viewId: viewId, onFilterChange: (filter) => {
                            onFilterChange === null || onFilterChange === void 0 ? void 0 : onFilterChange(filter);
                            // 条件变化时显示 notification
                            if (!notificationType) {
                                setNotificationType('filter');
                            }
                        }, onAddCondition: handleAddFilterCondition, onConditionCleared: () => handleConditionCleared('filter'), keepVisible: notificationType === 'filter', isCompact: isToolbarCompact })),
                    permissions.group && (React.createElement(GroupButton, { viewId: viewId, onGroupChange: (group) => {
                            onGroupChange === null || onGroupChange === void 0 ? void 0 : onGroupChange(group);
                            // 条件变化时显示 notification
                            if (!notificationType) {
                                setNotificationType('group');
                            }
                        }, onAddCondition: handleAddGroupCondition, onConditionCleared: () => handleConditionCleared('group'), keepVisible: notificationType === 'group', maxGroupLevels: groupMaxLevels, isCompact: isToolbarCompact })),
                    permissions.sort && (React.createElement(SortButton, { viewId: viewId, onSortChange: (fields, order) => {
                            onSortChange === null || onSortChange === void 0 ? void 0 : onSortChange(fields, order);
                            // 条件变化时显示 notification
                            if (!notificationType) {
                                setNotificationType('sort');
                            }
                        }, onAddCondition: handleAddSortCondition, onConditionCleared: () => handleConditionCleared('sort'), keepVisible: notificationType === 'sort', showDivider: !!(permissions.colorFill || permissions.component || renderRightContent), isCompact: isToolbarCompact })),
                    permissions.colorFill && (React.createElement(ColorFillButton, { viewId: viewId, onColorFillChange: (rules) => {
                            onColorFillChange === null || onColorFillChange === void 0 ? void 0 : onColorFillChange(rules);
                            // 条件变化时显示 notification
                            if (!notificationType) {
                                setNotificationType('colorFill');
                            }
                        }, onAddCondition: handleAddColorFillCondition, onConditionCleared: () => handleConditionCleared('colorFill'), keepVisible: notificationType === 'colorFill', showDivider: !!(permissions.component || renderRightContent), isCompact: isToolbarCompact })),
                    renderRightContent && renderRightContent()),
                React.createElement(CnBox, { direction: "row", spacing: 0, className: "toolbar-actions" }, dataModel.getViewConfig(viewId).type === 'Grid' && hasAnyFieldType && (React.createElement(AddFieldButton, { viewId: viewId, enableAiFields: enableAiFields, enableLookup: enableLookup, enableFormula: enableFormula }))))))));
}
