import axios from 'axios'
import { ElNotification } from 'element-plus'
import { GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
import useUserStore from '@/store/modules/user'
import pinia from '@/store'
//创建axios实例
const request = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 600000,
})
// 存储需要取消的请求
const requestsToCancel = {};

//请求拦截器
request.interceptors.request.use((config: any) => {
  if (GET_TOKEN()) {
    config.headers.Authorization = GET_TOKEN()
  }
  // 为每个请求生成一个唯一的cancel token
  config.cancelToken = new axios.CancelToken(cancel => {
    requestsToCancel[config.url] = cancel;
  });
  return config
})
//响应拦截器
request.interceptors.response.use(
  (response: any) => {
    return response.data

  },
  (error: any) => {
    //处理网络错误
    if (error.response?.data.code == 20107) {
      return
    }
    // if (error.response?.data.code == 10101) {
    //   Object.values(requestsToCancel).forEach(cancel => cancel());
    // }
    if (error.response?.data.code == 10103) {
      Object.values(requestsToCancel).forEach(cancel => cancel());
      const useUser = useUserStore(pinia)
      useUser.userInfo = {}
      useUser.token = ''
      REMOVE_TOKEN()
      ElNotification({
        type: 'error',
        message: error.response.data.message,
        duration: 2000,
        onClose: () => {
          location.href = '/index'
        }
      })
      return
    }

    ElNotification({
      type: 'error',
      message: error.response.data.message,
      duration: 2000,
    })

    return Promise.reject(error)
  },
)

export default request
