import { http } from '@/utils/request'

/**
 * 查询token合法
 * @params
 */
export function fetchCheckTokenApi() {
  return http.post('/user/api/user_center/mobile/v1/check_token', {})
}
export function fetchStreamResponse(url: string, body: Record<string, any>, onMessage: (msg: any) => void) {
  body.stream = true
  const decoder = new TextDecoder('utf-8')
  let buffer = ''
  let dataMsgBuffer = ''

  function processMessage(reader: any) {
    reader.read().then((content: any) => {
      buffer += decoder.decode(content.value, { stream: !content.done })
      const lines = buffer.split('\n')
      buffer = lines.pop() as string
      lines.forEach((line) => {
        if (line === '') { // 读取到空行，一个数据块发送完成
          onMessage({
            type: 'DATA',
            content: JSON.parse(dataMsgBuffer),
          })
          dataMsgBuffer = ''
          return
        }
        const [type] = line.split(':', 1)
        const content = line.substring(type.length + 1)
        if (type === 'data') { // 数据块没有收到空行之前放入buffer中
          dataMsgBuffer += content.trim()
        }
        else if (type === '' && content !== '') { // 服务端发送的注释，用于保证链接不断开
          onMessage({
            type: 'COMMENT',
            content: content.trim(),
          })
        }
        else {
          onMessage({
            type,
            content: content.trim(),
          })
        }
      })
      if (!content.done) {
        processMessage(reader)
      }
      else {
        onMessage({
          type: 'END',
        })
      }
    })
  }
  fetch(url, {
    headers: {
      'Content-Type': 'application/json',
      'X-Token': JSON.parse(window.localStorage.getItem('__TOKEN__') as string) || '',
    },
    method: 'POST',
    body: JSON.stringify(body),
  })
    .then(response => response.body?.getReader())
    .then(reader => processMessage(reader))
    .catch(error => onMessage({
      type: 'ERROR',
      content: error,
    }))
}
