import Loading from './index.vue'
import { mount } from '@/helper/mount'
import type { App } from 'vue'
import type { LoadingProps } from './props'

export type LoginMark = string | symbol | number

type Stack = { key?: LoginMark; close?: () => void }[]
const closeStack: Stack = []

export const showLoading = function (
  props?: LoadingProps,
  app?: App,
  key?: LoginMark
) {
  if (closeStack.length) {
    closeStack.push({ key })
  } else {
    const timeout = setTimeout(() => {
      const { destroy } = mount(Loading, { app, props })
      item.close = destroy
    }, 300)
    const item: Stack[number] = {
      key,
      close: () => clearTimeout(timeout)
    }
    closeStack.push(item)
  }
}

export const hideLoading = function (hkey?: LoginMark) {
  if (closeStack.length) {
    const { key } = closeStack[closeStack.length - 1]
    if (key === hkey) {
      const stack = closeStack.pop()
      stack?.close && stack?.close()
    }
  }
}

export const hideLoadingAll = function () {
  for (const { close } of closeStack) {
    close && close()
  }
  closeStack.length = 0
}

export { Loading }
export default Loading
