import axios from 'axios'
import VueAxios from 'vue-axios'
import Vue from 'vue'
import router from '../router'
import store from '../store'
import ElementUI, {
    Loading
} from 'element-ui';

let loading //定义loading变量

function startLoading() { //使用Element loading-start 方法
    loading = Loading.service({
        text: '请稍等...',
        background: 'rgba(0, 0, 0, 0.2)'
    })
}

function endLoading() { //使用Element loading-close 方法
    loading.close()
}

let needLoadingRequestCount = 0
export function showFullScreenLoading() {
    if (needLoadingRequestCount === 0) {
        startLoading()
    }
    needLoadingRequestCount++
}

export function tryHideFullScreenLoading() {
    if (needLoadingRequestCount <= 0) return
    needLoadingRequestCount--
    if (needLoadingRequestCount === 0) {
        endLoading()
    }
}

const urlMap = {

}


//axios配置和处理
Vue.use(VueAxios, axios);
axios.defaults.baseURL = ''; //项目的的基础url
axios.defaults.headers.common['Authorization'] = ""; //请求token信息配置
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; //请求type设置
axios.defaults.timeout = 1000 * 1000; //在超时前，所有请求都会等待相应秒数
axios.defaults.withCredentials = true;
let isInvalid1 = false //用于控制登录信息过期后弹窗时间的截流，截流时间为5s
let isInvalid2 = false

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前处理
    // 判断token在前台session中是否存在
    config.headers.common['Authorization'] = localStorage.getItem('Authorization');

    // 解决同一个浏览器中登录多个账户时，账户页面刷新后，页面数据更新为最后一个登录的账户。
    // console.log(store.state.username);
    // console.log(localStorage.getItem('username'));
    if (store.state.username &&
        localStorage.getItem('username') &&
        store.state.username != localStorage.getItem('username')) {
        window.location.reload();
    }

    if (config.noLoading === true) { //如果noLoading为true，不加载loading画面
        console.log("noLoading");
    } else {
        showFullScreenLoading();
    }
    return config;
}, function (error) {
    // 对请求错误做处理
    return Promise.reject(error);
});
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
	// if(response.config.url.includes("/simulation/resource/server/menu/getMyMenuTree")){
	// 	response.data.info[3].children.push({
	// 		"id": "d75a9d044eec4dc7b9133256c7e976af",
	// 		"name": "多模式仿真",
	// 		"router": "/multimodeSimulation",
	// 		"icon": null,
	// 		"sort": 3,
	// 		"parentId": "268190b28633425da0744966976c4e22",
	// 		"visible": "1",
	// 		"children": null
	// 	})
	// }
    // 对响应数据处理
    tryHideFullScreenLoading();
    if (response && (response.status == 200)) {
        if (response.data.exceptionMes) {
            ElementUI.MessageBox({
                type: 'info',
                title: response.data.exceptionMes,
                message: '网络错误，请稍后再试！'
            });
        }
        return response.data;
    }
    return response;
}, function (error) {
    tryHideFullScreenLoading();
    if (error.response.status == 401) { //token失效，弹框提示确认返回login
        //ElementUI.Message.error("用户信息过期，请重新登录");
        if (isInvalid1 == false) {
            isInvalid1 = true
            ElementUI.MessageBox.alert('用户信息过期，请重新登陆', '提示', {
                confirmButtonText: '确定',
                callback: action => {
                    // let loginUrl = window.location.origin + '/login'
                    // window.location.href = loginUrl
                    router.push({
                        path: "/login"
                    })
                }
            })
            setTimeout(() => {
                isInvalid1 = false
            }, 5000)
        }
        return Promise.reject(error);
    } else {
        ElementUI.Message.error("网络异常");
        return Promise.reject(error);
    }
});

Vue.prototype.$axios = axios; //定义调用方式




// 针对上传大文件
const instance = axios.create({
    baseURL: '',
});

instance.defaults.headers.common['Authorization'] = ""; //请求token信息配置
instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; //请求type设置
instance.defaults.timeout = 1000 * 60 * 6; //在超时前，所有请求都会等待
instance.defaults.withCredentials = true;

instance.interceptors.request.use(function (config) {
    // 在发送请求之前处理
    // 判断token在前台session中是否存在
    config.headers.common['Authorization'] = localStorage.getItem('Authorization');
    if (config.noLoading === true) { //如果noLoading为true，不加载loading画面
        console.log("noLoading");
    } else {
        showFullScreenLoading();
    }
    return config;
}, function (error) {
    // 对请求错误做处理
    return Promise.reject(error);
});
// 添加响应拦截器
instance.interceptors.response.use(function (response) {
    // 对响应数据处理
    tryHideFullScreenLoading();
    if (response && (response.status == 200)) {
        if (response.data.exceptionMes) {
            ElementUI.MessageBox({
                type: 'info',
                title: response.data.exceptionMes,
                message: '网络错误，请稍后再试！'
            });
        }
        return response.data;
    }
    return response;
}, function (error) {
    tryHideFullScreenLoading();
    if (error.response.status == 401) { //token失效，弹框提示确认返回login
        if (isInvalid2 == false) {
            isInvalid2 = true
            ElementUI.MessageBox.alert('用户信息过期，请重新登陆', '提示', {
                confirmButtonText: '确定',
                callback: action => {
                    // let loginUrl = window.location.origin + '/login'
                    // window.location.href = loginUrl
                    router.push({
                        path: "/login"
                    })
                }
            })
            setTimeout(() => {
                isInvalid2 = false
            }, 5000)
        }
        return Promise.reject(error);
    } else {
        ElementUI.Message.error("网络异常");
        return Promise.reject(error);
    }
});

Vue.use(VueAxios, instance);
Vue.prototype.$instance = instance; //定义调用方式

//针对不需要loading画面的实例