/**
 * @desc：axios请求库全局配置
 */
import axios from "axios";
import {getToken} from "@/util/auth";
import {Base64} from "js-base64";
import {serialize} from "@/util/util";
import website from "@/config/website";
import {ElMessage} from "element-plus";
import store from '@/store';
import router from "@/router";
//根据.env文件切换环境
if (import.meta.env.MODE == 'development') {
    axios.defaults.baseURL = import.meta.env.VITE_SERVER_HOST
}
if (import.meta.env.MODE == 'production') {
    axios.defaults.baseURL = import.meta.env.VITE_SERVER_SITE
}
axios.defaults.timeout = 36000000;
axios.interceptors.request.use(
    config => {
        // let token = localStorage.getItem("userInfo").token;
        // config.headers["accessToken"] = token;
        const meta = (config.meta || {});
        const isToken = meta.isToken === false;
        config.headers['Authorization'] = `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`;
        //让每个请求携带token
        if (getToken() && !isToken) {
            config.headers[website.tokenHeader] = 'bearer ' + getToken()
        }
        //headers中配置text请求
        if (config.text === true) {
            config.headers["Content-Type"] = "text/plain";
        }
        //headers中配置serialize为true开启序列化
        if (config.method === 'post' && meta.isSerialize === true) {
            config.data = serialize(config.data);
        }
        return config
    },
    error => {
        return Promise.reject(error);
    }
);

axios.interceptors.response.use(
    response => {
        // console.log("response", response);
        const status = response.data.code || response.status;
        const message = response.data.data || '未知错误';
        if (status !== 200) {
            ElMessage({
                message: message,
                type: 'error'
            });
            return Promise.reject(new Error(message))
        }
        if (response.data) {
            return response;
        } else {
            // message.error(response.data.msg);
            throw new Error(response.data.msg);
        }
    },
    error => {
        ElMessage({
            message: error.response.data.msg,
            type: 'error'
        });
        if (error && error.response) {
            let data  = error.response.data
            switch (error.response.status) {
                case 400:
                    error.message = "请求出错(400)";
                    return Promise.reject(error);
                case 401:
                    store.dispatch('FedLogOut').then(() => router.push({
                        path: '/login'
                    }))
                    //跳登录页
                    return Promise.reject(error);
                case 403:
                    error.message = "禁止访问(403)";
                    break;
                case 404:
                    error.message = "资源未找到(404)";
                    return Promise.reject(error);
                case 500:
                    return Promise.reject(error);
                case 501:
                    error.message = "服务未实现(501)";
                    return Promise.reject(error);
                case 502:
                    error.message = "网络错误(502)";
                    return Promise.reject(error);
                case 503:
                    error.message = "服务不可用(503)";
                    return Promise.reject(error);
                case 504:
                    error.message = "网络超时(504)";
                    return Promise.reject(error);
                case 505:
                    error.message = "HTTP版本不受支持(505)";
                    return Promise.reject(error);
                default:
                    error.message = `请求出错(${error.response.status})!`;
                    return Promise.reject(error);
            }
        } else {
            error.message = "连接服务器失败!";
        }
    }
);

export default axios;
