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

  async function post() {
    isLoading.value = true
    await fetchEventSource('/api/lab/v1/experiment/qwen/chat', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ model: 'qwen-long', messages: messages.value }),
      async onopen(response) {
        if (response.ok) {
          return response
        } else {
          throw response
        }
      },
      onmessage(res) {
        console.log(res.data)
        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 || ''
          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
          }
          isLoading.value = false
        } catch (error) {
          console.log(error)
          isLoading.value = false
        }
      },
      onerror(err) {
        isLoading.value = false
        throw err
      }
    })
  }

  return { messages, post, isLoading }
}
