// 封装全局请求 loading 控制

import { ElLoading } from 'element-plus'

let loadingInstance = null

export function showLoading(text = '') {
  if (!loadingInstance) {
    loadingInstance = ElLoading.service({
      lock: true,
      text,
      spinner: 'el-icon-loading',
      background: 'rgba(43, 48, 67, 0.65)',
    })
  }
}

export function hideLoading() {
  if (loadingInstance) {
    loadingInstance.close()
    loadingInstance = null
  }
}

// 通用封装：包装一个异步函数，自动显示/隐藏 loading
export async function withLoading(fn, text = '') {
  showLoading(text)
  try {
    const res = await fn()
    return res
  } finally {
    hideLoading()
  }
}
