// composables/useMessage.ts
interface Message {
  id: number
  content: string
  messageType: string
  close: () => void
  pause: () => void
  resume: () => void
}

const messages = reactive<Message[]>([])

export const useNiMessage = () => {
  const createMessage = (content: string, messageType: string) => {
    const id = Date.now()
    let timeout: NodeJS.Timeout | null = null

    const close = () => {
      const index = messages.findIndex(msg => msg.id === id)
      if (index > -1) messages.splice(index, 1)
    }

    const startTimer = () => {
      timeout = setTimeout(close, 3000)
    }

    const message: Message = {
      id,
      content,
      messageType,
      close,
      pause: () => timeout && clearTimeout(timeout),
      resume: () => startTimer()
    }

    messages.unshift(message) // 新消息显示在最上方
    startTimer()

    return message
  }

  return {
    messages,
    log: (data: string) => createMessage(data, 'log'),
    info: (data: string) => createMessage(data, 'info'),
    warning: (data: string) => createMessage(data, 'warning'),
    error: (data: string) => createMessage(data, 'error'),
    success: (data: string) => createMessage(data, 'success'),
  }
}
