import { createApp } from 'vue'
import MjLoading, { type MjLoadingOptions } from './index.vue'
import hud from '@/utils/hud'

let loadingInstance: any = null
type ShowOptions = MjLoadingOptions | string
export type LoadOptions = {
  loading?: ShowOptions
  task: () => Promise<any>
  option?: string
  hideSuccess?: boolean
  hideError?: boolean
}

const isShowing = () => {
  return loadingInstance?.isShowing()
}

const show = (data?: ShowOptions) => {
  if (!loadingInstance) {
    const container = document.createElement('div')
    const app = createApp(MjLoading)
    loadingInstance = app.mount(container)
    document.body.appendChild(container)
  }
  loadingInstance.show(data)
}

const hide = () => {
  if (loadingInstance) {
    loadingInstance.hide()
  }
}

const load = async (options: LoadOptions) => {
  let loadingContent = '加载中...'
  let successContent = '操作成功！'
  let errorContent = '操作失败！'
  if (options.option) {
    loadingContent = `${options.option}中...`
    successContent = `${options.option}成功！`
    errorContent = `${options.option}失败！`
  }
  let showOptions = options.loading
  if (!showOptions) {
    showOptions = loadingContent
  }
  show(showOptions)

  // 默认不想

  try {
    const res = await options.task()
    !options.hideSuccess && hud.success(successContent)
    // 返回出去
    return res
  } catch (err: any) {
    if (err) {
      if (typeof err === 'string') {
        errorContent += `${err}`
      } else if (err.message) {
        errorContent += `${err.message}`
      }
    }
    if (!err?.showed) {
      !options.hideError && hud.error(errorContent)
    }
    throw err
  } finally {
    hide()
  }
}

export const loading = {
  isShowing,
  show,
  hide,
  load,
}
