/** http请求类 */
import axios from "axios"
import type { AxiosInstance, AxiosRequestConfig, Method, AxiosPromise } from "axios"
import Nprogress from "@/plugins/nprogress"
import { ElMessage } from "element-plus"
import { TokenInvalidFlag, CODE401, CODE_ERR_CANCELED } from "@/libs/auth"
import userStore from "@/store/user"

// 重写 axios 传参
interface AxiosConfigType extends AxiosRequestConfig {
  method: Method // method 必须为Method 格式
}

// axiosObj 传值
type axiosObjType = {
  getTokenFun?: () => string | undefined // 获取token的函数
  tokenName?: string // headers token的名字
  nprogress?: boolean // 是否显示滚动条
}

/** api接口 */
export interface axiosApiType {
  (...param: any[]): AxiosPromise<any>
}

class HttpAsynAxios {
  constructor(url: string, axiosObj?: axiosObjType) {
    this.URL = url
    this.axiosObj = axiosObj
  }
  private URL = ""
  private axiosObj: axiosObjType | undefined = undefined
  private httpInterceptor(instance: AxiosInstance) {
    ;(this.axiosObj ? !(this.axiosObj.nprogress === false) : true) && Nprogress.start() // 开启
    // http request 请求拦截器
    instance.interceptors.request.use(
      config => {
        return config
      },
      error => {
        console.log(error)
        Nprogress.done()
        const rejectData: apiResDataType = {
          code: 500,
          message: "系统运行异常，请联系管理员处理",
          data: null
        }
        return Promise.reject(rejectData)
      }
    )
    // http response 结果拦截器
    instance.interceptors.response.use(
      response => {
        Nprogress.done()
        // 如果返回401则跳转到登录页
        if (response.data.code === CODE401) {
          // 如果token登录状态 才提示和退出
          if (TokenInvalidFlag) {
            // const responseData: apiResDataType = response.data
            // ElMessage.error(responseData.message)
            // 登出
            userStore().resetUser()
          }
        }
        return response
      },
      error => {
        console.log(error)
        Nprogress.done()
        // if (error.response) {
        //     // 响应错误之后的操作
        //     switch (error.response.status) {
        //         case 401:
        //     }
        // }
        const rejectData: apiResDataType =
          error.code === CODE_ERR_CANCELED
            ? {
                code: error.code,
                message: "系统取消接口",
                data: null
              }
            : {
                code: 500,
                message: "系统运行异常，请联系管理员处理",
                data: null
              }
        return Promise.reject(rejectData) // 返回接口返回的错误信息
      }
    )
  }
  // 创建实例
  private createInstance() {
    const axiosObj = this.axiosObj
    return axios.create(
      axiosObj?.tokenName
        ? {
            baseURL: this.URL,
            headers: {
              [axiosObj.tokenName]: axiosObj.getTokenFun && axiosObj.getTokenFun()
            }
          }
        : {
            baseURL: this.URL
          }
    )
  }
  /**
      axios请求方法
      ```
      {
          data: data,     //get方法的时候为params：data
          method: "post",
          url: '/auth/loginIn'，
          headers:{
                  'Content-Type':'application/json',
          },
          responseType: 'blob',
      }
      ```
   */
  axioseRquest(opt: AxiosConfigType) {
    const instance = this.createInstance()
    this.httpInterceptor(instance)
    return instance(opt)
  }
}

export default HttpAsynAxios
