import axios from 'axios'
import Vue from 'vue'
import { Message, Loading } from 'element-ui';
// loading框设置局部刷新，且所有请求完成后关闭loading框
let loadingInstance; //loading 实例
let needLoadingRequestCount = 0; //当前正在请求的数量
function showLoading() {
    let main = document.querySelector('#app')        //获取dom节点
    if (main) {
        if (needLoadingRequestCount === 0 && !loadingInstance) {
            loadingInstance = Loading.service({
                target: main, text: '正在加载...', background: 'rgba(0,0,0,0.6)', spinner: 'el-icon-loading'
            });
        }
        needLoadingRequestCount++;
    }
}
function closeLoading() {
    Vue.nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
        needLoadingRequestCount--;
        needLoadingRequestCount = Math.max(needLoadingRequestCount, 0); // 保证大于等于0
        if (needLoadingRequestCount === 0) {
            if (loadingInstance) {
                hideLoading()
            }
        }
    });
}

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;

}


//防抖
var hideLoading = () => {
    loadingInstance.close();
    loadingInstance = null;
}


const request = axios.create({
    withCredentials: false,
    baseURL: "https://zjwaterfile.cnjsjd.net:8099/"
    // baseURL: "https://watertestapi.vnet1000.net/",
})

request.interceptors.request.use(
    config => {
        const Authorization = localStorage.getItem('Authorization')
        if (Authorization) {
            config.headers['Authorization'] = Authorization
        }

        showLoading()
        return config
    },
    error => {
        closeLoading()
        return Promise.reject(new Error(error).message)
    }
)

request.interceptors.response.use(
    response => {
        closeLoading()
        if (response.data.status != 200) {
            Message({
                message: response.data.msg,
                type: 'error'
            })
        }
        return response.data
    },
    error => {
        Message({
            message: '服务器错误',
            type: 'error'
        })
        closeLoading()
        setTimeout(() => {
            window.history.back()
        }, 1000)
        return Promise.reject(new Error(error).message)
    }
)

export default request
