import { router } from '../router'
import qs from 'qs';
import {rootUrl} from '@/config'
let apiPrefix = process.env.NODE_ENV === 'production' ? '/' : '/api';
let AxiosIns = axios.create({
	baseURL: rootUrl,
	timeout: 50000,
	transformRequest: [data => {
	if(data instanceof FormData){
		return data
	}else{
		return qs.stringify(data)
	}
	}],
	headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' },
	withCredentials: true
})

let timer = [];
let delay = 300;
let loading = null;
let options = {
	// lock: true,
	text: '拼命加载中',
	background: 'rgba(0, 0, 0, 0.2)',
	// target: "#app",
}
let isLoginOut=false

AxiosIns.interceptors.request.use((config) => {
	if (loading == null) {
		loading = ELEMENT.Loading.service(options);
	}
	// loading = ELEMENT.Loading.service(options);
	timer.push(setTimeout(() => {
	}, delay))
	return config;
})

AxiosIns.interceptors.response.use((response) => {
	for (let t of timer) {
		clearTimeout(t);
	}
	if (loading != null) {
		loading.close();
		loading = null;
	}
	// loading.close()
	try {
		if (response.data && response.data.success !== true) {
			let msg = Array.isArray(response.data.errorMsg) ? response.data.errorMsg[0] : (response.data.errorMsg?response.data.errorMsg:response.data.errMsg);
			if ((msg == "LOGIN_CHECK_ERROR"||msg=="LOGIN_TIME_OUT") && (!isLoginOut)) {
				isLoginOut=true
				ELEMENT.Message({
					message: '登录信息过期，请重新登录',
					type: 'warning',
					showClose: true,
				});
				setTimeout(() => {
					isLoginOut=false
					window.localStorage.removeItem("user")
					router.push({path: '/login'})
				}, 1000)
				loading.close();
				loading = null;
			}
			if(!isLoginOut){
				ELEMENT.Message({
					message: msg || '接口调用失败',
					type: 'warning',
					showClose: true,
				})
				loading.close();
				loading = null;
			}
		}
	} catch (e) {

	}
	return response.data;
}, (error) => {
	for (let t of timer) {
		clearTimeout(t);
	}
	// loading.close();
	try {
		if (error.response.data.status!= 404&&error.response.data.status!= 400) {
			loading.close();
			loading = null;
			ELEMENT.Message({
				message:'接口调用失败',
				type: 'warning',
				showClose: true,
			});
		}else{
			loading.close();
			loading = null;
			ELEMENT.Message({
				message:'接口调用失败',
				type: 'warning',
				showClose: true,
			});
		}
	} catch (e) {
		loading.close();
		loading = null;
		ELEMENT.Message({
			message:'接口调用失败',
			type: 'warning',
			showClose: true,
		});
	}
	return Promise.reject(error);
})
Vue.prototype.axios = AxiosIns;
