import Vue from 'vue'
import ToastHost from '@/components/ToastHost.vue'
import ConfirmHost from '@/components/ConfirmHost.vue'
import ImagePreviewHost from '@/components/ImagePreviewHost.vue'

let toastInstance = null
let confirmInstance = null
let previewInstance = null

function mountInstance(Component) {
  const Ctor = Vue.extend(Component)
  const instance = new Ctor()
  instance.$mount()
  document.body.appendChild(instance.$el)
  return instance
}

function ensureToast() {
  if (!toastInstance) toastInstance = mountInstance(ToastHost)
  return toastInstance
}

function ensureConfirm() {
  if (!confirmInstance) confirmInstance = mountInstance(ConfirmHost)
  return confirmInstance
}

function ensurePreview() {
  if (!previewInstance) previewInstance = mountInstance(ImagePreviewHost)
  return previewInstance
}

export function toast(message, type = 'info', duration = 2000) {
  if (!message) return
  ensureToast().push({ message, type, duration })
}

toast.success = (message, duration) => toast(message, 'success', duration)
toast.error = (message, duration) => toast(message, 'error', duration)
toast.info = (message, duration) => toast(message, 'info', duration)

export function confirm({ title = '提示', content = '', confirmText = '确定', cancelText = '取消', showCancel = true } = {}) {
  return new Promise((resolve) => {
    ensureConfirm().open({
      title,
      content,
      confirmText,
      cancelText,
      showCancel,
      onConfirm: () => resolve({ confirm: true }),
      onCancel: () => resolve({ confirm: false })
    })
  })
}

export function previewImage(urls, current) {
  if (!urls || !urls.length) return
  ensurePreview().open({ urls, current })
}
