import React, { useState, useMemo, useRef } from 'react';
import { CnButton } from '@cainiaofe/cn-ui';
import isFunction from 'lodash/isFunction';
import isEmpty from 'lodash/isEmpty';
import './index.scss';
import { isPromise } from '../utils/common';
import { ToolbarDivider } from '../components/toolbar-divider';
/**
 * 处理按钮点击时的 loading 状态
 * 支持异步 onClick 自动管理 loading
 */
function useRenderButtonLoading(item) {
    var _a;
    const [loading, setLoading] = 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) && isFunction(item === null || item === void 0 ? void 0 : item.onClick)) {
        const originalOnClick = item.onClick;
        const wrapOnClick = (...args) => {
            setLoading(true);
            const result = originalOnClick(...args);
            if (isPromise(result)) {
                result.finally(() => {
                    setLoading(false);
                });
            }
            else {
                setLoading(false);
            }
            return result;
        };
        return {
            ButtonOnClick: wrapOnClick,
            loading,
        };
    }
    if (isFunction(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.isValidElement(item) ? typedItem : null);
    if (!item)
        return null;
    // 处理 React 元素
    if (React.isValidElement(item)) {
        return React.cloneElement(item, {
            ...(item.props || {}),
            ...(isFunction(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.createElement(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 && isFunction(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 从父组件传入，确保与表格选择状态同步
 */
export default function NormalToolbar(props) {
    const { batchArea, toolArea, selectKeys = [], storeSelectInfo: propsStoreSelectInfo } = props;
    // 默认的 storeSelectInfo ref（当父组件未传入时使用）
    const defaultStoreSelectInfo = useRef([]);
    const storeSelectInfo = propsStoreSelectInfo || defaultStoreSelectInfo;
    // 合并 batchArea 和 toolArea 到同一区域，在两者之间插入分割线
    const mergedList = 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.createElement(ToolbarDivider, { key: "toolbar-divider" }), ...tool];
        }
        return [...batch, ...tool];
    }, [batchArea, toolArea]);
    // 构建选择信息对象
    const selectInfo = useMemo(() => ({
        selectKeys,
        storeSelectInfo,
    }), [selectKeys, storeSelectInfo]);
    // 如果没有任何项，不渲染
    if (isEmpty(mergedList)) {
        return null;
    }
    return (React.createElement("div", { className: "cn-ai-table-toolbar" },
        React.createElement("div", { className: "cn-ai-table-toolbar-items" }, mergedList.map((item, index) => (
        // eslint-disable-next-line react/no-array-index-key
        React.createElement(RenderNormalItem, { key: index, item: item, selectInfo: selectInfo, itemKey: index }))))));
}
