import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'

const request = axios.create({
  baseURL: '/api',
  timeout: 15000,
})

request.interceptors.request.use(config => {
  const token = store.getters['auth/token']
  if (token) config.headers.Authorization = `Bearer ${token}`
  return config
})

request.interceptors.response.use(
  res => {
    const data = res.data
    if (data.code && data.code !== 200) {
      Message.error(data.msg || '请求失败')
      return Promise.reject(new Error(data.msg))
    }
    return data
  },
  err => {
    if (err.response?.status === 401) {
      store.dispatch('auth/logout')
      router.push('/login')
      Message.error('登录已过期，请重新登录')
    } else {
      Message.error(err.response?.data?.detail || err.message || '网络异常')
    }
    return Promise.reject(err)
  }
)

export default request
