import axios from "axios";
import {AxiosCanceler} from "./axiosCanceler";
import {ElMessageBox, ElNotification} from "element-plus";
import {getToken, removeToken} from "./auth";

axios.defaults.headers['Content-Type'] = 'application/json'

const serveice = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 6000
})
const axiosCanceler = new AxiosCanceler()
serveice.interceptors.request.use(config => {
  const ACCESS_TOKEN = getToken() || ''
  if (ACCESS_TOKEN !== undefined && ACCESS_TOKEN !== '') {
    config.headers['Authorization'] = ACCESS_TOKEN
  }
  // 检查是否有重复请求, 有则取消掉
  axiosCanceler.removePendingRequest(config)
  // 将请求加入pendingMap
  axiosCanceler.addPendingRequest(config)
  return config
}, error => {
  Promise.reject(error)
})
serveice.interceptors.response.use(response => {
  axiosCanceler.removePendingRequest(response.config)
  // console.log(response,"response")
  //二进制数据直接返回
  if (response.request.responseType === 'blob' || response.request.responseType === 'arraybuffer') {
    return response.data
  }
  // console.log("1")
  return response.data
}, error => {
  // console.log(error)
  let response = error.response
  if (!response) {
    return Promise.reject()
  }
  const status = response.status;
  if (!status) {
    return Promise.reject()
  }
  switch (status) {
    case 401:
      // ElMessageBox.confirm('登录状态已过期,请重新登录', '系统提示', {
      //     confirmButtonText: '重新登录',
      //     cancelButtonText: '取消',
      //     type: 'warning',
      //     closeOnClickModal: false
      // }).then(() => {
      removeToken()
      let path = window.location.pathname;
      let query = window.location.search
      sessionStorage.setItem('toView', JSON.stringify({
        path: path,
        query: query
      }))
      window.location.href = `${window.location.origin}/api/auth/cas/login`
      // })
      return Promise.reject('会话已过期,请重新登录')
    case 402:
      break;
    case 403:
      ElNotification({
        title: '系统提示',
        message: response.data.msg,
        type: 'warning'
      })
      break;
    case 404:
      ElNotification({
        title: '系统提示',
        message: '不存在的地址',
        type: 'error'
      })
      break;
    case 405:
      ElNotification({
        title: '系统提示',
        message: '传输格式错误,请检查',
        type: 'error'
      })
      break;
    case 511:
      ElNotification({
        title: '系统提示',
        message: '禁止访问',
        type: 'error'
      })
      removeToken()
      window.location = '/forbidden'
      break;
    case 500:
      if (response.data) {
        return response.data
      } else {
        ElNotification({
          title: '系统提示',
          message: '系统未知错误',
          type: 'error'
        })
        break;
      }
  }
  return Promise.reject(error)
})

export default serveice
