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
})

request.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
        }
        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.NODE_ENV == 'production' ? window.location.origin + '/pweb/m/login?is_screen=1' : process.env.VUE_APP_API_URL + '/pweb/m/login?is_screen=1'
        }
        return response.data
    },
    error => {
        Message({
            message: '服务器错误',
            type: 'error'
        })
        closeLoading()
        return Promise.reject(new Error(error).message)
    }
)

export default request
