import { ElLoading, type LoadingInstance } from 'element-plus' export interface GlobalLoadingOptions { text?: string lock?: boolean } let activeLoadingCount = 0 let loadingInstance: LoadingInstance | null = null const openGlobalLoading = (options?: GlobalLoadingOptions) => { activeLoadingCount += 1 if (typeof window === 'undefined' || loadingInstance) { return } loadingInstance = ElLoading.service({ lock: options?.lock ?? true, text: options?.text ?? '\u52a0\u8f7d\u4e2d', background: 'rgba(255, 255, 255, 0.72)' }) } const closeGlobalLoading = () => { activeLoadingCount = Math.max(0, activeLoadingCount - 1) if (activeLoadingCount > 0) { return } loadingInstance?.close() loadingInstance = null } export const runWithGlobalLoading = async ( task: (() => Promise) | Promise, options?: GlobalLoadingOptions ) => { openGlobalLoading(options) try { if (typeof task === 'function') { return await task() } return await task } finally { closeGlobalLoading() } }