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, signal?: AbortSignal) {
  body.stream = true
  const decoder = new TextDecoder('utf-8')
  let buffer = ''
  let dataMsgBuffer = ''

  function processMessage(reader: any) {
    reader.read().then((content: any) => {
      // 检查是否已被中止
      if (signal?.aborted) {
        return
      }
      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',
        })
      }
    }).catch((error) => {
      // 如果是 AbortError，不发送错误消息
      if (error.name === 'AbortError') {
        return
      }
      onMessage({
        type: 'ERROR',
        content: error,
      })
    })
  }
  fetch(url, {
    headers: {
      'accept': 'text/event-stream',
      'Content-Type': 'application/json',
      'X-Token': JSON.parse(window.localStorage.getItem('__TOKEN__') || ''),
    },
    method: 'POST',
    body: JSON.stringify(body),
    signal,
  })
    .then((response) => {
      return response.body?.getReader()
    })
    .then((reader) => {
      return processMessage(reader)
    })
    .catch((error) => {
      // 如果是 AbortError，不发送错误消息
      if (error.name === 'AbortError') {
        return
      }
      onMessage({
        type: 'ERROR',
        content: error,
      })
    })
}

/**
 * 提交收藏
 * @param recordId
 * @returns Promise<any>
 */
export function fetchSubmitCollection(recordId: string) {
  return http.post('/conversation/api/collection/mobile/v1/submit_collection', { recordId })
}

/**
 * 删除收藏
 * @param collectionIdList
 * @returns Promise<any>
 */
export function fetchDelCollection(collectionIdList: string[]) {
  return http.post('/conversation/api/collection/mobile/v1/delete_user_collection', { collectionIdList })
}

/**
 * 取消收藏
 * @param recordId
 * @returns Promise<any>
 */
export function fetchCancelCollection(recordId: string) {
  return http.post('/conversation/api/collection/mobile/v1/cancel_user_collection', { recordId })
}

/**
 * 提交反馈
 * @returns Promise<any>
 */
export function fetchSubmitFeedback(params: any) {
  return http.post('/conversation/api/feedback/mobile/v1/submit_feedback', {
    ...params,
    scene: '01',
  })
}

/**
 * 获取反馈配置
 * @returns Promise<any>
 */
export function fetchGetFeedbackConfig() {
  return http.post('/conversation/api/feedback/mobile/v1/get_config', {
    scene: '01',
  })
}

/**
 * 查询推荐问题
 * @param conversationId
 * @returns Promise<any>
 */
export function fetchQueryRecommendQuestion(conversationId: string, recordId: string) {
  return http.post('/conversation/api/conversation/mobile/v1/query_recommend_question', {
    conversationId,
    recordId,
  })
}

/**
 * 停止问答
 * @param params
 * @returns Promise<any>
 */
export function fetchTerminateQuestion(params: any) {
  return http.post('/conversation/api/conversation/mobile/v1/terminate_question', params)
}
