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,
    }))
}

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

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

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

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

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

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

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