import axios from 'axios'
import { Message } from 'element-ui';
const getLocationParams = (keyWords) => {
    // 提取路由值（字符串）
    let href = window.location.href;
    // 从占位符开始截取路由（不包括占位符）
    let query = href.substring(href.indexOf("?") + 1);
    // 根据 & 切割字符串
    let vars = query.split("&");
    for (let i = 0; i < vars.length; i++) {
        let pair = vars[i].split("=");
        // 根据指定的参数名去筛选参数值
        if (pair[0] == keyWords) {
            return pair[1];
        }
    }
    return "";
};
const noLoadingrequest = axios.create({
    withCredentials: false,
    baseURL: getLocationParams("api_type") ? process.env.VUE_APP_API_URL : '',
})

noLoadingrequest.interceptors.request.use(
    config => {
        const Authorization = localStorage.getItem('Authorization')
        const PermitAuthorization = localStorage.getItem('PermitAuthorization')
        if (Authorization) {
            config.headers['Authorization'] = Authorization
        }
        if (PermitAuthorization) {
            config.headers['Permit-Authorization'] = PermitAuthorization
        }
        return config
    },
    error => {
        return Promise.reject(new Error(error).message)
    }
)

noLoadingrequest.interceptors.response.use(
    response => {
        if (response.data.status != 200) {
            Message({
                message: response.data.msg,
                type: 'error'
            })
        }
        if (response.data.status == 401) {
            window.location.href = window.location.origin + '/pweb/m/login?is_screen=1'
        }
        return response.data
    },
    error => {
        Message({
            message: '服务器错误',
            type: 'error'
        })
        console.log(error)
        return Promise.reject(new Error(error).message)
    }
)

export default noLoadingrequest
