import { fetchEventSource } from '@fortaine/fetch-event-source'
import { ElMessage } from 'element-plus'
export function useChat() {
  const messages = ref([])
  const isLoading = ref(false)

  function post(message, isReplace = true) {
    isLoading.value = true
    return new Promise((resolve, reject) => {
      fetchEventSource('/api/lab/v1/experiment/qwen/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ model: 'qwen-long', messages: [message] }),
        async onopen(response) {
          if (response.ok) {
            return response
          } else {
            isLoading.value = false
            reject(response)
            throw response
          }
        },
        onmessage(res) {
          console.log(res.data)
          if (res.data === '[DONE]') {
            isLoading.value = false
            resolve(messages.value.at(-1))
            return
          }
          try {
            const message = JSON.parse(res.data)
            if (message.error) {
              ElMessage.error(message.error.message)
              return
            }
            const id = message.id
            const messageIndex = messages.value.findIndex((session) => session.id === id)
            let content = message?.choices[0]?.delta.content || ''
            if (isReplace) {
              content = content.replaceAll('\n', '<br/>')
            }
            if (messageIndex === -1) {
              messages.value.push({ id, role: 'assistant', content })
            } else {
              messages.value[messageIndex].content = messages.value[messageIndex].content + content
            }
          } catch (error) {
            console.log(error)
            isLoading.value = false
            reject(error)
          }
        },
        onerror(err) {
          isLoading.value = false
          reject(err)
          throw err
        },
      })
    })
  }

  return { messages, post, isLoading }
}
