import axios from 'axios'
import md5 from 'js-md5'
export default class PendingRequest {
  request = new Map()
  add(config) {
    const requestKey = this.generateReqKey(config)
    config.cancelToken =
      config.cancelToken ||
      new axios.CancelToken((cancel) => {
        if (!this.request.has(requestKey)) {
          this.request.set(requestKey, cancel)
        } else {
          cancel(`${requestKey} 取消请求`)
        }
      })
  }
  generateReqKey(config) {
    let { method, url, params, data } = config
    if(data && typeof data ==='string') data = JSON.parse(data)
    let pwd = md5(JSON.stringify({method, url, params, data}))
    return pwd
  }
  remove(config) {
    const requestKey = this.generateReqKey(config)
    if (this.request.has(requestKey)) {
      this.request.delete(requestKey)
    }
  }
  clear(){
    this.request.clear()
  }
}
