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; //当前正在请求的数量
// import { getAccess } from "@/api/index"
// import md5 from "js-md5"

axios.defaults.maxRedirects = 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,
    maxRedirects: 0
    // baseURL: process.env.VUE_APP_API_URL
})


request.interceptors.request.use(
    config => {

        const Authorization = localStorage.getItem('Authorization')
        if (Authorization) {
            config.headers['Authorization'] = Authorization
        }
        if (!config.noloading) {
            showLoading()
        }

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

request.interceptors.response.use(
    response => {
        console.log(response)
        closeLoading()

        if (response.data.status != 200) {
            Message({
                message: response.data.msg,
                type: 'error'
            })
        }

        return response.data
    },
    async (error) => {
        console.log(error)
        if (error.request.status == 401) {
            // closeLoading()
            // localStorage.setItem('Authorization', '')
            // var config = error.config
            // var data = {
            //     api_key: 10012,
            //     timestamp: new Date().getTime(),
            //     sign: md5(
            //         `api_key${10012}timestamp${new Date().getTime()}${"757D0789-8971-4E6E-872E-1C471A672102"}`
            //     ),
            // };
            // getAccess(data).then((res) => {
            //     if (res.status == 200) {
            //         localStorage.setItem("Authorization", `${res.data.token_type} ${res.data.access_token}`);
            //     }
            // });

            // var backoff = new Promise((resolve) => {
            //     setTimeout(() => {
            //         resolve();
            //     }, 1);
            // });

            // // 再次发送请求
            // return backoff.then(() => {
            //     return request(config);
            // });
        }
        Message({
            message: '服务器错误',
            type: 'error'
        })

        return Promise.reject(new Error(error).message)
    }
)

export default request
