import router from '@/router/index'
import axios from 'axios'

const api = import.meta.env.VITE_API_HOST

const instance = axios.create({
  baseURL: api
})

// 请求拦截器
instance.interceptors.request.use((config:any) => {
  config.headers['Authorization'] = sessionStorage.getItem('token')
  return config
}, err => {
  return Promise.reject(err)
})

// 响应拦截器
instance.interceptors.response.use(response => {
  return response
}, err => {
  if (err.response.status === 401) {
    sessionStorage.removeItem('token')
    // Message.error('登录状态已失效！请重新登录！')
    setTimeout(() => {
      router.push({ path: '/login' })
    }, 1000)
  }
  return Promise.reject(err.response)
})

// 导出工具函数
export default instance
