import { ERRORTYPES } from '@/common/constant'
import { EMethods } from '@/types'
import { ReportDataType, TransportDataType } from '@/types/transportData'
const promiseMessages = ['Request failed with status code 401', 'undefined', '', 'Error: Request failed with status code 401', 'cancel', 'false']
// const promiseCodes = [1000, -100, -1000]
function isPromiseFilter(msg: string): boolean {
  if (promiseMessages.indexOf(msg.trim()) !== -1) {
    return true
  }
  // try {
  //   const obj = JSON.parse(msg)
  //   // ==：公司返回code竟然是字符串 淦
  //   if (obj && obj.code && promiseCodes.some((errorCode) => obj.code == errorCode)) {
  //     return true
  //   }
  //   return false
  // } catch (error) {
  //   return false
  // }
  return false
}

export async function requestEnd(data: TransportDataType) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.open(EMethods.Get, this.url)
    xhr.send()
  })
}

export async function beforeDataReport(data: TransportDataType, customTag: string) {
  const { data: errorData } = data
  const javaScriptMessages = ['ResizeObserver loop limit exceeded', 'Script error.', 'Unexpected identifier']
  switch (errorData.type) {
    case ERRORTYPES.JAVASCRIPT_ERROR:
      if (javaScriptMessages.indexOf(errorData.message.trim()) !== -1) return false
    case ERRORTYPES.PROMISE_ERROR:
      if (isPromiseFilter(errorData.message)) return false
    default:
      break
  }
  if (!errorData.customTag && customTag) {
    errorData.customTag = customTag
  }
  if (data.record && Array.isArray(data.record) && data.record.length > 2 && Math.round(Math.random() * 100) < 16) {
    try {
      await requestEnd(data)
    } catch (error) {
      console.log('isNeedRecord false')
      data.record = []
    }
  }
  return data
}
