import { useEffect, useState, useCallback } from 'react'
import { fetchEventSource } from '@fortaine/fetch-event-source'

// 获取本地存储中的令牌
function getToken() {
  return window.localStorage.getItem('kiwi.token') || ''
}

// 生成请求头部信息
const getHeaders = () => {
  const token = getToken()
  const appId = 'TzEU5jPk2tu80266'
  const appSecret = '0a006048a4480481b18fef1405120b83'
  const timestamp = Math.floor(Date.now() / 1000)

  return {
    Authorization: token,
    AppId: appId,
    AppSecret: appSecret,
    Timestamp: timestamp,
    'Content-Type': 'application/json'
  }
}

// 默认的响应打开处理函数
const defaultOnOpen = async response => {
  if (!response.ok) {
    throw response
  }
  return response
}

// 默认的消息处理函数
const defaultOnMessage = setMessages => res => {
  const message = JSON.parse(res.data)
  setMessages(prevMessages => [...prevMessages, message])
}

// 自定义 Hook，用于使用 Fetch 事件源
export function useFetchEventSource(url, options = {}) {
  const [isLoading, setLoading] = useState(false)
  const [messages, setMessages] = useState([])
  const [error, setError] = useState(null)

  // 定义 fetch 函数
  const fetch = useCallback(() => {
    setLoading(true)
    const headers = getHeaders()

    const defaultOptions = {
      method: 'POST',
      headers,
      onopen: defaultOnOpen,
      onmessage: defaultOnMessage(setMessages),
      onerror: err => setError(err)
    }

    fetchEventSource(url, { ...defaultOptions, ...options })
      .catch(err => setError(err))
      .finally(() => setLoading(false))
  }, [url, options])

  // 在组件挂载时执行 fetch 函数
  useEffect(() => {
    fetch()
  }, [fetch])

  return { isLoading, error, messages, fetch }
}
