import axios from "axios"
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import type { HYRequestConfig } from './types'
// import router from "../../router"

/**
 * 两个难点:
 * 1. 拦截器进行精细控制
 *    > 全局拦截器
 *    > 实例拦截器
 *    > 单次请求拦截器
 * 2. 响应结果的类型处理(泛型)
 */

class HYRequest {
  instance: AxiosInstance
  // request 实例 => axios 实例
  constructor(config: HYRequestConfig) {
    this.instance = axios.create(config)


    // 每个 instance 实例都添加拦截器
    this.instance.interceptors.request.use((config) => {
      // loading/token
      return config
    }, err => {
      console.log('全局请求失败的拦截', err)
      return err
    })
    this.instance.interceptors.response.use(res => {
      // console.log('全局相应成功的拦截')
      return res.data
    }, err => {
      if (err.response.data.code === 401) {
        // router.push('/login')
      }
      console.log('全局相应失败的拦截', err.response.data)
      return err
    })

    // 针对特定的 hyRequest 实例添加拦截器
    if (config.interceptors) {
      this.instance.interceptors.request.use(
        config?.interceptors.requestSuccessFn,
        config?.interceptors.requestFailureFn
      )
      this.instance.interceptors.response.use(
        config?.interceptors.responseSuccessFn,
        config?.interceptors.responseFailureFn
      )
    }
  }

  request<T = any>(config: HYRequestConfig<T>) {
    // 单次请求的成功拦截器
    if (config.interceptors?.requestSuccessFn) {
      config = config.interceptors.requestSuccessFn(config)
    }
    return new Promise<T>((resolve, reject) => {
      this.instance.request<any, T>(config).then(res => {
        // 单词响应的成功拦截器
        if (config.interceptors?.responseSuccessFn) {
          res = config.interceptors.responseSuccessFn(res)
        }
        resolve(res)
      }).catch(err => {
        reject(err)
      })
    })
  }

  get<T = any>(config: HYRequestConfig<T>) {
    return this.request({ ...config, method: "GET" })
  }
  post<T = any>(config: HYRequestConfig<T>) {
    return this.request({ ...config, method: "POST" })
  }
  delete<T = any>(config: HYRequestConfig<T>) {
    return this.request({ ...config, method: "DELETE" })
  }
  patch<T = any>(config: HYRequestConfig<T>) {
    return this.request({ ...config, method: "PATCH" })
  }
}

export default HYRequest