import axios from 'axios'
import { locale } from 'core-js';
import { globalApi } from "./urlPatterns";
import { Message } from 'element-ui';
// 创建axios实例
import router from '../router'
const service = axios.create({
    baseURL: globalApi.netBASE_URL, // api的base_url
    timeout: 500000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(config => {
    // console.log(config);
    config.headers["X-Token"] = localStorage.getItem('X-Token') || ""
    return config
}, error => {
    console.log(error) // for debug
    Promise.reject(error)
})

// response拦截器
service.interceptors.response.use(
    response => {
        let res = response.data;
        if (res.code !== 200) {
            // 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
            if (res.code === 401) {
                Message.error('登录过期')
                router.push("/")
                localStorage.removeItem('X-Token');
            } else if (res.code == 500) {
                Message.error(res.message)
            } else {
                Message.error(res.msg)
            }
            // console.log('token过期或其他', res);
            return Promise.reject(response);
        } else {
            return response;
        }
    },
    error => {
        console.log(error);
        if (String(error) === 'Error: Request failed with status code 401') {
            console.log("Error: Request failed with status code 401'")
            // Message.error('登录过期')
            router.push("/")
        }
        return Promise.reject(error)
    })

export default service

