import axios from 'axios'
import store from "@/store"
import router from "@/router";
// axios 配置
axios.defaults.timeout = 3000;
axios.defaults.baseURL = 'http://api.lions-vote.cnskl.com/api/';

const axiosConf = (config) => {
    // config.headers.Authorization = store.state.accessToken;
    config.headers.Authorization = localStorage.getItem('accessToken')
    return config;
};

axios.interceptors.request.use(axiosConf, err => {
    return Promise.reject(err);
});

axios.interceptors.response.use(async (response) => {
    let data = {};
    let code = Number(response.data.status_code);
    if (code === 401 || code == 0) {
        if (response.data.status == 'EXCEPTION') {
            return Promise.reject(response.data)
        }
        if (response.headers.authorization) {
            await store.commit('login', response.headers.authorization);

            response.config.headers.Authorization = response.headers.authorization;
            const result = await axios.request(axiosConf(response.config));
            if (result) {
                data = result;
            }
        } else if (router.currentRoute.name != 'AuthLogin') {
            setTimeout(() => {
                router.replace({name: 'AuthLogin', query: {redirect: router.currentRoute.fullPath}});
            }, 1000);
        }
    } else if (code === 200) {
        data = response.data.data;
    } else if (code === 403) {
        await router.replace({path: '/403', query: {redirect: router.currentRoute.fullPath}});
    } else if (code === 410) {
        setTimeout(() => {
            router.replace({name: 'AuthLogin', query: {redirect: router.currentRoute.fullPath}});
        }, 1200);
    } else if (code == 404) {
        return Promise.reject(response.data);
    } else {
        return Promise.reject(response.data);
    }
    return data;
}, (error) => {
    return Promise.reject(error.response.data);
});

export default axios;
