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

axios.defaults.headers['Content-Type'] = "application/json;charset=utf-8"

const baseURL =
    import.meta.env.DEV
        ? '/myApi'
        : window.location.origin

const requestHttp = axios.create({
    baseURL: baseURL,
    timeout: 10000,
})

requestHttp.interceptors.request.use((config) => {
    const token = getToken()
    if (token) {
        config.headers["token"] = token
    }
    return config
}, (error) => {
    return Promise.reject(error)
})

requestHttp.interceptors.response.use((response) => {
    console.log(response)
    if (response.status == 200) {
        if (response.data.code == 1) {
            return response.data
        } else {
            ElMessage.error(response.data.msg || response.data.info || "请求失败，请联系管理员")
            return Promise.reject(response)
        }
    }
    else {
        ElMessage.error(response.data.msg || response.data.info || "请求失败，请联系管理员")
        return Promise.reject(response)
    }
}, (error) => {

})

export default requestHttp