import MessageBox from '@/components/common/MessageBox/index.vue'
import type { MessageBoxProps } from '@/components/common/MessageBox/types'
import { render, effect } from 'vue'

interface ConfirmProps extends MessageBoxProps {
  useLoading?: boolean // 是否用到loading
}

export const useMessageBox = () => {
  const confirm = (props: ConfirmProps) => {
    return new Promise((resolve, reject) => {
      const visible = ref(false)
      const loading = ref(false)
      const onConfirm = () => {
        if (props.useLoading) {
          // 设置loading
          loading.value = true
          // 关闭全给用户
          resolve({
            close: () => {
              visible.value = false
            },
            setLoading: (value: boolean) => {
              loading.value = value
            },
          })
        } else {
          resolve(true)
        }
      }
      const onCancel = () => {
        reject(false)
      }
      const onClose = () => {
        reject(false)
      }

      effect(() => {
        render(
          <MessageBox
            v-model={visible.value}
            {...props}
            loading={loading.value}
            onConfirm={onConfirm}
            onCancel={onCancel}
            onClose={onClose}
          />,
          document.body,
        )
      })

      visible.value = true
    })
  }

  return { confirm }
}
