import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '../router'

const service = axios.create({
 baseURL: import.meta.env.VITE_API_BASE_URL,
 timeout: 10000
})

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

service.interceptors.response.use(
 response => {
 const res = response.data
 if (res.code !== 0) {
 ElMessage.error(res.message || '请求失败')
 if (res.code === 401) {
 localStorage.removeItem('admin_token')
 router.push('/login')
 }
 return Promise.reject(new Error(res.message || '请求失败'))
 }
 return res
 },
 error => {
 ElMessage.error(error.message || '网络异常')
 return Promise.reject(error)
 }
)

export default service
