import type { AxiosRequestConfig } from 'axios'

import obj from '@/utils/obj'

// 同时有多个请求时，只有最后一个请求生效
export const only_last_id = 'on_last_id'
const only_last_req_id = 'only_last_req_id'
const controllers = {} as Record<string, AbortController>
const reqIds = {} as Record<string, string>

export type RequestConfig = AxiosRequestConfig & {
  [only_last_id]?: any
  [only_last_req_id]?: any
}

function processRequest(config: RequestConfig) {
  if (!config) return

  const onlyLastId = config[only_last_id]
  if (!onlyLastId) return

  // 取消上一个请求
  let ctl = controllers[onlyLastId]
  if (ctl) {
    ctl.abort()
    // console.log('❌取消❌', onlyLastId, reqIds[onlyLastId], config.url)
  }

  // 重新赋值
  ctl = new AbortController()
  config.signal = ctl.signal
  controllers[onlyLastId] = ctl
  // 赋值一个请求的唯一id
  const reqId = obj.snowflakeId()
  reqIds[onlyLastId] = reqId
  config[only_last_req_id] = reqId
  // console.log('💪🏻开启💪🏻', onlyLastId, reqId, config.url)
}

function processResponse(config: RequestConfig) {
  if (!config) return true
  const onlyLastId = config[only_last_id]
  // 忽略
  if (!onlyLastId) return true

  const reqId = config[only_last_req_id]
  if (reqId === reqIds[onlyLastId]) {
    // console.log('✅选用✅', onlyLastId, reqId, config.url)
    delete reqIds[onlyLastId]
    delete controllers[onlyLastId]
    // 忽略
    return true
  } else {
    // console.log('⭕️抛弃⭕️', onlyLastId, reqId, config.url)
    // 过滤请求
    return false
  }
}

const onlyLastApi = {
  processRequest,
  processResponse,
}

export default onlyLastApi
