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

/**
 * 查询token合法
 * @params
 */
export function fetchCheckTokenApi() {
  return http.post('/user/api/user_center/mobile/v1/check_token', {})
}
const STREAM_TIMEOUT_MS = 30 * 60 * 1000 // 流式请求超时：半小时

export function fetchStreamResponse(url: string, body: Record<string, any>, onMessage: (msg: any) => void, signal?: AbortSignal): Promise<void> {
  body.stream = true
  const decoder = new TextDecoder('utf-8')
  let buffer = ''
  let dataMsgBuffer = ''

  const controller = new AbortController()
  const timeoutId = setTimeout(() => controller.abort(), STREAM_TIMEOUT_MS)
  if (signal) {
    signal.addEventListener('abort', () => controller.abort())
  }
  const effectiveSignal = controller.signal
  const cleanup = () => clearTimeout(timeoutId)

  return new Promise<void>((resolve, reject) => {
  function processMessage(reader: any) {
    reader.read().then((content: any) => {
      // 检查是否已被中止
      if (effectiveSignal.aborted) {
          cleanup()
          resolve()
        return
      }
      buffer += decoder.decode(content.value, { stream: !content.done })
      const lines = buffer.split('\n')
      buffer = lines.pop() as string
      lines.forEach((line) => {
        if (line === '') { // 读取到空行，一个数据块发送完成
          try {
            onMessage({
              type: 'DATA',
              content: JSON.parse(dataMsgBuffer),
            })
          }
          catch {
            // 解析失败时静默处理，避免报错
          }
          dataMsgBuffer = ''
          return
        }
        const [type] = line.split(':', 1)
        const content = line.substring(type.length + 1)
        if (type === 'data') { // 数据块没有收到空行之前放入buffer中
          // SSE 格式中，data: 后面的内容前面可能有一个空格，trim 可以安全处理
          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 {
          cleanup()
          resolve()
      }
    }).catch((error: unknown) => {
      if (error instanceof Error && error.name === 'AbortError') {
          cleanup()
          resolve()
        return
      }
      onMessage({ type: 'ERROR', content: error })
      cleanup()
      reject(error)
    })
  }
  const tokenStr = window.localStorage.getItem('__TOKEN__') || '""'
  let token = ''
  try {
    token = JSON.parse(tokenStr)
  }
  catch {
    token = ''
  }

  fetch(url, {
    headers: {
      'accept': 'text/event-stream',
      'Content-Type': 'application/json',
      'X-Token': token,
    },
    method: 'POST',
    body: JSON.stringify(body),
    signal: effectiveSignal,
  })
    .then((response) => {
      return response.body?.getReader()
    })
    .then((reader) => {
        if (!reader) {
          cleanup()
          reject(new Error('Failed to get reader from response'))
          return
        }
      return processMessage(reader)
    })
    .catch((error: unknown) => {
      if (error instanceof Error && error.name === 'AbortError') {
          cleanup()
          resolve()
        return
      }
      onMessage({ type: 'ERROR', content: error })
      cleanup()
      reject(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
 * @param recordId
 * @param toolId 可选的工具ID
 * @param busiType 可选的业务类型
 * @param recordType 可选的记录类型
 * @returns Promise<any>
 */
export function fetchQueryRecommendQuestion(
  conversationId: string,
  recordId: string,
  toolId?: string,
  busiType?: string,
  recordType?: string,
) {
  return http.post('/conversation/api/conversation/mobile/v1/query_recommend_question', {
    conversationId,
    recordId,
    ...(toolId ? { toolId } : {}),
    ...(busiType ? { busiType } : {}),
    ...(recordType ? { recordType } : {}),
  })
}

/**
 * 查询推荐问题 工单/提质增效
 * @param conversationId
 * @param recordId
 * @param toolId 可选的工具ID
 * @param busiType 可选的业务类型
 * @param recordType 可选的记录类型
 * @returns Promise<any>
 */
export function fetchOrderQueryRecommendQuestion(
  conversationId: string,
  recordId: string,
  toolId?: string,
  busiType?: string,
  recordType?: string,
) {
  return http.post('/conversation/api/conversation/mobile/v1/query_strategy_recommend_question', {
    conversationId,
    recordId,
    ...(toolId ? { toolId } : {}),
    ...(busiType ? { busiType } : {}),
    ...(recordType ? { recordType } : {}),
  })
}

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

/**
 * 获取业务洞察常见问题list
 * @param params
 * configTypeList: ['10']
 * @returns Promise<any>
 */
export function fetchBusinessInsightList(params: any) {
  return http.post('/conversation/api/commonconfig/mobile/v1/query_config_list', params)
}
