import { fetchEventSource } from '@fortaine/fetch-event-source'

function getToken() {
  return window.localStorage.getItem('kiwi.token') ? window.localStorage.getItem('kiwi.token') : ''
}

export default async function fetchEventSourceFn(url, options) {
  const token = getToken()
  // 应用设置
  const appId = 'TzEU5jPk2tu80266'
  const appSecret = '0a006048a4480481b18fef1405120b83'
  const timestamp = Math.floor(Date.now() / 1000)

  const defaultHeaders = {
    Authorization: token,
    AppId: appId,
    AppSecret: appSecret,
    Timestamp: timestamp,
    'Content-Type': 'application/json'
  }
  const messages = []
  const defaultOptions = {
    method: 'POST',
    headers: { ...defaultHeaders },
    onmessage(res) {
      const message = JSON.parse(res.data)
      messages.push(message)
    }
  }

  return await fetchEventSource(url, { ...defaultOptions, ...options }).then(() => messages)
}
