import { fetchEventSource } from '@microsoft/fetch-event-source'
import { BASE_URLS } from '@/config/base-url'
import { useUserStore } from '@/store/modules/user'

const EVENT_SOURCE_BASE_URL = `${BASE_URLS[window.ENV || 'DEV']}`

export function fetchCustomEventSource(config: {
  path: string
  payload: any
  controller: AbortController
  onMessage: (data: string) => void
  onRequestError: (err: any) => void
  onError?: (err: any) => void
  onFinally?: () => void
}) {
  const userStore = useUserStore()
  let responseError = false

  fetchEventSource(`${EVENT_SOURCE_BASE_URL}${config.path}`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Request-Token': userStore.token || '',
    },
    body: JSON.stringify(config.payload || {}),
    signal: config.controller?.signal,
    openWhenHidden: true,
    onmessage: (e) => {
      if (e.data === '[DONE]' && !responseError) {
        config.onMessage(e.data)
        config.onFinally && config.onFinally()

        return
      }

      try {
        const data = JSON.parse(e.data)

        if (data.code === -10) {
          window.$message.info('身份已过期，请重新登陆')

          config.onError && config.onError(data)

          userStore.logout()
          return
        }

        if (data.code === -1) {
          responseError = true

          window.$message.error(data.message)
          config.controller?.abort()

          config.onFinally && config.onFinally()
          config.onError && config.onError(data)

          return
        }

        config.onMessage(data.message)
      } catch (err) {
        config.onRequestError(err)

        config.onFinally && config.onFinally()
      }
    },
    onclose: () => {},
    onerror: (err) => {
      config.onRequestError(err)
      window.$message.error(err.message || '操作失败请重试')
      config.onFinally && config.onFinally()

      throw err
    },
  })
}
