"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.default = NormalToolbar;
const react_1 = __importStar(require("react"));
const cn_ui_1 = require("@cainiaofe/cn-ui");
const isFunction_1 = __importDefault(require("lodash/isFunction"));
const isEmpty_1 = __importDefault(require("lodash/isEmpty"));
require("./index.scss");
const common_1 = require("../utils/common");
const toolbar_divider_1 = require("../components/toolbar-divider");
/**
 * 处理按钮点击时的 loading 状态
 * 支持异步 onClick 自动管理 loading
 */
function useRenderButtonLoading(item) {
    var _a;
    const [loading, setLoading] = (0, react_1.useState)(false);
    if (!item) {
        return {
            ButtonOnClick: () => { },
            loading: false,
        };
    }
    // 如果 buttonProps.loading 为 true 且有 onClick，则自动管理 loading 状态
    if (((_a = item === null || item === void 0 ? void 0 : item.buttonProps) === null || _a === void 0 ? void 0 : _a.loading) && (0, isFunction_1.default)(item === null || item === void 0 ? void 0 : item.onClick)) {
        const originalOnClick = item.onClick;
        const wrapOnClick = (...args) => {
            setLoading(true);
            const result = originalOnClick(...args);
            if ((0, common_1.isPromise)(result)) {
                result.finally(() => {
                    setLoading(false);
                });
            }
            else {
                setLoading(false);
            }
            return result;
        };
        return {
            ButtonOnClick: wrapOnClick,
            loading,
        };
    }
    if ((0, isFunction_1.default)(item === null || item === void 0 ? void 0 : item.onClick)) {
        return {
            ButtonOnClick: item.onClick,
            loading: false,
        };
    }
    return {
        ButtonOnClick: () => { },
        loading: false,
    };
}
/**
 * 渲染单个工具栏项
 */
function RenderNormalItem({ item, selectInfo, itemKey, }) {
    var _a, _b, _c, _d;
    const { selectKeys, storeSelectInfo } = selectInfo;
    const typedItem = item;
    const { loading, ButtonOnClick } = useRenderButtonLoading(typeof item === 'object' && item !== null && !react_1.default.isValidElement(item) ? typedItem : null);
    if (!item)
        return null;
    // 处理 React 元素
    if (react_1.default.isValidElement(item)) {
        return react_1.default.cloneElement(item, {
            ...(item.props || {}),
            ...((0, isFunction_1.default)(item.type)
                ? {
                    selectKeys,
                    selectRecords: (_a = storeSelectInfo === null || storeSelectInfo === void 0 ? void 0 : storeSelectInfo.current) === null || _a === void 0 ? void 0 : _a[1],
                }
                : {}),
        });
    }
    // 处理函数类型
    if (typeof item === 'function') {
        // ICnTableToolbarItemFunc 接受 2 个参数: (selectKeys, selectInfo)
        return item(selectKeys, (_b = storeSelectInfo === null || storeSelectInfo === void 0 ? void 0 : storeSelectInfo.current) === null || _b === void 0 ? void 0 : _b[1]);
    }
    // 处理对象类型 (ICnTableToolbarItemObj)
    if (typeof typedItem.visible === 'function' &&
        !typedItem.visible(selectKeys, (_c = storeSelectInfo === null || storeSelectInfo === void 0 ? void 0 : storeSelectInfo.current) === null || _c === void 0 ? void 0 : _c[1], storeSelectInfo === null || storeSelectInfo === void 0 ? void 0 : storeSelectInfo.current)) {
        return null;
    }
    return (react_1.default.createElement(cn_ui_1.CnButton, { "data-hottag": `cn-ai-table.${typedItem === null || typedItem === void 0 ? void 0 : typedItem.children}`, key: itemKey, type: typedItem === null || typedItem === void 0 ? void 0 : typedItem.type, onClick: (event) => {
            var _a;
            ButtonOnClick(event, selectKeys, (_a = storeSelectInfo === null || storeSelectInfo === void 0 ? void 0 : storeSelectInfo.current) === null || _a === void 0 ? void 0 : _a[1], storeSelectInfo === null || storeSelectInfo === void 0 ? void 0 : storeSelectInfo.current);
        }, disabled: typedItem && (0, isFunction_1.default)(typedItem.isDisabled)
            ? typedItem.isDisabled(selectKeys, (_d = storeSelectInfo === null || storeSelectInfo === void 0 ? void 0 : storeSelectInfo.current) === null || _d === void 0 ? void 0 : _d[1], storeSelectInfo === null || storeSelectInfo === void 0 ? void 0 : storeSelectInfo.current)
            : false, ...((typedItem === null || typedItem === void 0 ? void 0 : typedItem.buttonProps) || {}), loading: loading }, typedItem === null || typedItem === void 0 ? void 0 : typedItem.children));
}
/**
 * 普通工具栏组件
 * batchArea 和 toolArea 合并显示在同一区域
 * selectKeys 和 storeSelectInfo 从父组件传入，确保与表格选择状态同步
 */
function NormalToolbar(props) {
    const { batchArea, toolArea, selectKeys = [], storeSelectInfo: propsStoreSelectInfo } = props;
    // 默认的 storeSelectInfo ref（当父组件未传入时使用）
    const defaultStoreSelectInfo = (0, react_1.useRef)([]);
    const storeSelectInfo = propsStoreSelectInfo || defaultStoreSelectInfo;
    // 合并 batchArea 和 toolArea 到同一区域，在两者之间插入分割线
    const mergedList = (0, react_1.useMemo)(() => {
        const batch = Array.isArray(batchArea) ? batchArea : [];
        const tool = Array.isArray(toolArea) ? toolArea : [];
        // 如果 batch 和 tool 都不为空，在它们之间插入分割线
        if (batch.length > 0 && tool.length > 0) {
            return [...batch, react_1.default.createElement(toolbar_divider_1.ToolbarDivider, { key: "toolbar-divider" }), ...tool];
        }
        return [...batch, ...tool];
    }, [batchArea, toolArea]);
    // 构建选择信息对象
    const selectInfo = (0, react_1.useMemo)(() => ({
        selectKeys,
        storeSelectInfo,
    }), [selectKeys, storeSelectInfo]);
    // 如果没有任何项，不渲染
    if ((0, isEmpty_1.default)(mergedList)) {
        return null;
    }
    return (react_1.default.createElement("div", { className: "cn-ai-table-toolbar" },
        react_1.default.createElement("div", { className: "cn-ai-table-toolbar-items" }, mergedList.map((item, index) => (
        // eslint-disable-next-line react/no-array-index-key
        react_1.default.createElement(RenderNormalItem, { key: index, item: item, selectInfo: selectInfo, itemKey: index }))))));
}
