import { createApp } from 'vue'
import MjDialog, { type MjDialogOptions } from './index.vue'
import { loading, LoadOptions as LoadingLoadOptions } from '../mj-loading'
import obj from '@/utils/obj'

let dialogMap: Record<string, any> = {}

type LoadOptions = {
  dialog: MjDialogOptions | string
} & LoadingLoadOptions

function createDialog(): any {
  const container = document.createElement('div')
  const _destroy = () => {
    app.unmount()
    document.body.removeChild(container)
    delete dialogMap[dialog._snowflakeId]
  }
  const app = createApp(MjDialog, {
    modelValue: false,
    js_destroy: _destroy,
  })
  const dialog = app.mount(container) as any
  dialog._snowflakeId = obj.snowflakeId()
  document.body.appendChild(container)
  dialogMap[dialog._snowflakeId] = dialog
  return dialog
}

export const dialog = {
  isShowing() {
    return Object.keys(dialogMap)?.length
  },
  show(data?: MjDialogOptions) {
    const dialog = createDialog()
    dialog.show(data)
    return dialog._snowflakeId
  },
  hide(snowflakeId?: any) {
    if (snowflakeId) {
      const dialog = dialogMap[snowflakeId]
      if (dialog) {
        dialog.hide()
        delete dialogMap[snowflakeId]
      }
    } else {
      for (const id in dialogMap) {
        dialogMap[id].hide()
      }
      dialogMap = {}
    }
  },
  async load(options: LoadOptions) {
    return new Promise((resolve, reject) => {
      let dialogOptions = options.dialog
      if (typeof dialogOptions === 'string') {
        dialogOptions = {
          content: dialogOptions,
        }
      }
      dialog.show({
        ...dialogOptions,
        ok: async () => {
          try {
            const res = await loading.load(options)
            resolve(true)
            return res
          } catch (err) {
            reject(err)
            // 不关闭窗口
            return true
          }
        },
      })
    })
  },
}
