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

export const PartnerID = '8980934e767f5acfa1c7cd92'
export const PartnerKey = 'N64IJm!e#iAWsac'

export const generateHeaders = () => {
  const TS = Date.now()
  return {
    'Content-Type': 'application/json',
    PartnerID,
    TS,
    Version: '1.0.1',
    Authorization: md5(`${PartnerID}+${PartnerKey}+${TS}`),
  }
}

const httpRequest = axios.create({
  withCredentials: true,
})

// 请求拦截器
httpRequest.interceptors.request.use((config) => {
  config.headers = { ...config.headers, ...generateHeaders() }
  return config
})

// 响应拦截器
httpRequest.interceptors.response.use(
  (response) => {
    const { data } = response
    return data
  },
  (error) => {
    return Promise.reject(error.response || error)
  }
)

export default httpRequest

export async function fetchEventSourceFn(url, options) {
  const messages = []
  const defaultOptions = {
    method: 'POST',
    headers: generateHeaders(),
    onmessage(res) {
      const message = JSON.parse(res.data)
      messages.push(message)
      if (options.onmessage) {
        options.onmessage(message)
      }
    },
  }

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