import axios from 'axios'
import { Message } from 'element-ui';


function urlTool(url) {
    //将url用“?”和“&”分割;
    const array = url.split("?").pop().split("&");

    //声明一个空对象用来储存分割后的参数；
    const data = {};

    array.forEach((ele) => {

        //将获得到的每个元素用 "="进行分割
        let dataArr = ele.split("=");

        //将数组的每一个元素遍历到对象中;
        data[dataArr[0]] = dataArr[1];

    });
    return data;

}

const getResponseRequest = axios.create({
    withCredentials: false,
    responseType: 'blob',
})

getResponseRequest.interceptors.request.use(
    config => {
        const ticket = urlTool(window.location.href).ticket
        if (ticket) {
            config.headers['ticket'] = ticket
        }
        config.headers['X-Requested-With'] = 'XMLHttpRequest'
        return config
    },
    error => {
        return Promise.reject(new Error(error).message)
    }
)

getResponseRequest.interceptors.response.use(
    response => {
        return response
    },
    error => {
        Message({
            message: '服务器错误',
            type: 'error'
        })
        return Promise.reject(new Error(error).message)
    }
)

export default getResponseRequest
