import Vue from 'vue';
import axios from 'axios';
const instance = axios.create({
    baseURL: process.env.VUE_APP_API_URL,
    timeout: 60 * 1000,
    headers: {
        'Content-Type': 'application/json;charset=UTF-8',
    },
    withCredentials: true,
});
window.once = 0
let blobList = [
    '/stock/export',
    '/category/export/model',
    '/stock/export/model'
]
instance.interceptors.request.use((config) => {
    const reqObj = config;
    // 在发送请求之前做些什么   -- 路径参数拼接
    // console.log(reqObj)
    const reg = /\{(.+?)\}/g;
    if (reg.test(reqObj.url)) {
        reqObj.url = reqObj.url.replace(reg, Object.values(reqObj.path)[0]);
    }
    // token
    if (localStorage.getItem('userInfo')) {
        reqObj.headers.token = JSON.parse(localStorage.getItem('userInfo')).token;
    }
    // 流文件下载
    if (blobList.indexOf(config.url) > -1) config.responseType = 'blob'
    return reqObj;
}, (err) => Promise.reject(err));

instance.interceptors.response.use((response) => {
    // 流下载处理 response.config.url会加个api/前缀
    if (blobList.some(item => {
        return response.config.url.indexOf(item) > -1
    })) return response.data

    const res = response.data;
    // 对响应数据做点什么
    if (res.code !== 200 && res.code!==0) {
        // console.log(res);
        Vue.prototype.$message.error(res.message);
        // 未认证
        if (res.code === 401) {
            // 未登录
            if (window.once == 0 && !location.search) {
                Vue.prototype.$message.error(res.message)
                Vue.prototype.$axios({
                    url: '/app/userCenter',
                    method: 'GET'
                }).then(res => {
                    window.open(res.data.url + '?redirect=' + location.origin, '_self')
                }).catch(err => {

                })
            }
            ++window.once
        }
        return Promise.reject(res.message);
    }
    return res;
}, (err) => Promise.reject(err));
Vue.prototype.$axios = instance;
export default instance;
