import axios from 'axios'
import Vue from 'vue'
import { Message, Loading } from 'element-ui';
import _ from 'lodash';
// 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()
            }
        }
    });
}
//防抖
var hideLoading = _.debounce(() => {
    loadingInstance.close();
    loadingInstance = null;
}, 10);


const request = axios.create({
    withCredentials: false,
    baseURL: process.env.VUE_APP_BASE_API,
})

request.interceptors.request.use(
    config => {
        const token = localStorage.getItem('token')
        if (token) {
            config.headers['token'] = token
        }
        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'
            })
        }
        if (response.data.status == 401) {
            // window.location.href = process.env.VUE_APP_RESOURCE_URL + 'pweb/m/login'
        }
        return response.data
    },
    error => {
        console.log(error)
        closeLoading()
        return Promise.reject(new Error(error).message)
    }
)

export default request
