import { useEffect } from "react";
import { message } from "antd";


export interface Props {
    // 显示loading 默认 false
    loading?: boolean,
    loadingTip?: any,
}

let count = 0;
let messageRef = { current: null };
let st;
const show = (loadingTip) => {
    clearTimeout(st);
    st = setTimeout(() => {
        count += 1;
        if (count > 0 && !messageRef.current) {
            messageRef.current = message.loading(loadingTip, 0);
        }
    }, 500);
};
const destroy = () => {
    clearTimeout(st);
    count -= 1;
    if (count < 0) count = 0;

    if (count <= 0 && messageRef.current) {
        messageRef.current();
        messageRef.current = null;
    }
};
export default function MessageLoading(props: Props) {
    const { loading, loadingTip } = props;
    useEffect(() => {
        if (!loading) return;
        show(loadingTip);
    }, [ loading, loadingTip ]);

    useEffect(() => {
        if (loading) return;
        destroy();
    }, [ loading, loadingTip ]);

    useEffect(() => {
        return () => destroy();
    }, []);

    return null;
}
