//初始化sse连接
let eventSource = null
//重连延迟
let retryTimeout = null
export function connectSSE(url, onMessage) {
    // 如果已有连接，先关闭
    if (eventSource) {
        eventSource.close()
    }

    console.log('[SSE] 正在连接:', url)

    eventSource = new EventSource(url)

    eventSource.onopen = () => {
        console.log('[SSE] 连接已建立')
    }

    eventSource.onmessage = (event) => {
        try {
            const data = JSON.parse(event.data)
            if (onMessage) onMessage(data)
        } catch (e) {
            if (onMessage) onMessage(event.data)
            console.warn('[SSE] 消息解析失败:', event.data)
        }
    }

    eventSource.onerror = (err) => {
        console.error('[SSE] 连接错误:', err)

        eventSource.close()
        eventSource = null

        // 避免重复重连
        if (retryTimeout) clearTimeout(retryTimeout)

        // 3秒后重连
        retryTimeout = setTimeout(() => {
            console.log('[SSE] 尝试重新连接...')
            connectSSE(url, onMessage)
        }, 1000)
    }
}