<template>
  <IxMessage v-for="item in msgList"
      :key="item.id"
      :duration="item.duration"
      :type="item.type"
      :visible="item.visible"
      @update:visible="msgCloseHandler(item.id)"
  >{{ item.msg }}
  </IxMessage>
</template>

<script lang="ts" setup>
import { nanoid } from 'nanoid'
import { MessageType } from '@idux/components/message/src/types'

defineOptions({name: 'Toast'})

const msgList = reactive<{
  id: string
  msg: string,
  type: MessageType,
  visible: boolean,
  duration: number
}[]>([])


function showToast(msg: string, type: MessageType = 'info', autoClose = true) {
  const id = nanoid()
  msgList.push({id, msg, type, visible: true, duration: autoClose ? 3000 : 0})
  return id
}

function closeToast(id: string) {
  const msg = msgList.find(it => it.id === id)
  if (msg != null) {
    msg.visible = false
  }
  msgList.splice(msgList.findIndex(it => it.id === id), 1)
}

function msgCloseHandler(id: string) {
  msgList.splice(msgList.findIndex(it => it.id === id), 1)
}

defineExpose({
  showToast,
  closeToast
})
</script>
