import { ref } from 'vue'

const visible = ref(false)
const message = ref('')
const type = ref('confirm') // 'confirm' | 'prompt' | 'date' | 'time'
const inputValue = ref('')
const inputType = ref('text')
let resolvePromise = null

export function useDialog() {
  function showDialog(msg, dialogType = 'confirm', defaultVal = '') {
    return new Promise(resolve => {
      resolvePromise = resolve
      message.value = msg
      type.value = dialogType
      if (dialogType === 'prompt') {
        inputType.value = msg.includes('密码') ? 'password' : 'text'
      } else if (dialogType === 'date') {
        inputType.value = 'date'
      } else if (dialogType === 'time') {
        inputType.value = 'time'
      }
      inputValue.value = defaultVal
      visible.value = true
    })
  }

  function closeDialog(value) {
    visible.value = false
    if (resolvePromise) {
      resolvePromise(value)
      resolvePromise = null
    }
  }

  return {
    visible,
    message,
    type,
    inputValue,
    inputType,
    showDialog,
    closeDialog,
  }
}
