import { ref, onUnmounted } from 'vue'

export function useSSE(url: string) {
  const data = ref<string>('')
  const isConnected = ref(false)
  const error = ref<string | null>(null)
  let eventSource: EventSource | null = null

  const connect = () => {
    try {
      eventSource = new EventSource(url)
      isConnected.value = true
      error.value = null

      eventSource.onmessage = (event) => {
        data.value += event.data
      }

      eventSource.onerror = (e) => {
        console.error('SSE error:', e)
        error.value = 'SSE连接出错'
        isConnected.value = false
      }

      eventSource.onopen = () => {
        console.log('SSE连接已建立')
        isConnected.value = true
      }
    } catch (e) {
      console.error('SSE连接失败:', e)
      error.value = 'SSE连接失败'
      isConnected.value = false
    }
  }

  const disconnect = () => {
    if (eventSource) {
      eventSource.close()
      eventSource = null
      isConnected.value = false
    }
  }

  const reset = () => {
    data.value = ''
    error.value = null
  }

  onUnmounted(() => {
    disconnect()
  })

  return {
    data,
    isConnected,
    error,
    connect,
    disconnect,
    reset
  }
}
