import axios from 'axios'
import {Message} from 'element-ui'
import store from "../store";
import router from "../router";
import {BASE_URL} from "@/config/app";

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例

const service = axios.create({
    // axios中请求配置有baseURL选项，表示请求URL公共部分
    baseURL: BASE_URL,
    // 超时
    timeout: 30000
})
// request拦截器
service.interceptors.request.use(
    config => {
        if (store.getters.adminId && store.getters.token) {
            config.headers = {
                ADMIN_ID: store.getters.adminId,
                ADMIN_TOKEN: store.getters.token,
            };
        }
        return config;
    },
    error => {
        Promise.reject(error);
    }
);
service.interceptors.response.use(res => {
    const status = Number(res.status) || 200;
    const data = res.data;
    if (status !== 200) {
        Message({
            message: res.statusText,
            type: 'error'
        })
        return Promise.reject(new Error(res.statusText))
    } else {
        if (data.code) {
            if (data.code === 2) {
                store.dispatch("fedLogout").then(() => {
                    Message.error("验证失败,请重新登录");
                    router.push({
                        path: "/login",
                        query: {redirect: router.currentRoute.fullPath} // 从哪个页面跳转过来
                    });
                });
            }
            if (data.code != 20000) {
                Message.error(data.message);
            }
        }
        return data
    }
})
export default service
