import axios from 'axios'
import { ElMessage } from 'element-plus'

const request = axios.create({ timeout: 5000 })

request.interceptors.request.use((config) => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

request.interceptors.response.use(
  (res) => {
    if (res.data.code !== 200) {
      if (res.data.code === 401) {
        localStorage.removeItem('token')
        localStorage.removeItem('username')
        window.location.hash = '#/login'
      }
      ElMessage.error(res.data.msg || '请求失败')
      return Promise.reject(res.data)
    }
    return res.data
  },
  (err) => {
    ElMessage.error('网络错误')
    return Promise.reject(err)
  }
)

export default request
