import axios from 'axios';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import store from '@/store/index';
import router from '@/router/index';
import { href } from '@/utils/index';
import qs from 'qs';
import { Message } from 'element-ui';

axios.defaults.timeout = 600000;
// axios.defaults.withCredentials = true;

axios.defaults.validateStatus = function(status) {
	return status >= 200 && status <= 500;
};

NProgress.configure({
	showSpinner: false
});

axios.interceptors.request.use(
	config => {
		NProgress.start();

		if (store.state.user.token) config.headers['token'] = store.state.user.token || '';

		config.headers['source'] = localStorage.getItem('source') || '';
		config.headers['account'] = localStorage.getItem('account') || '';

		config.data = qs.stringify(config.data) || {};
		return config;
	},
	error => {
		return Promise.reject(error);
	}
);

const onerror = async code => {
	if (code == 401) {
		await store.dispatch('userLogout');

		if (!location.href.includes('/login')) {
			href('/login');
		}
	}

	// if (code == 403) {
	// 	router.$plugin.to('/403');
	// }

	// if (code == 500) {
	// 	router.$plugin.to('/500');
	// }

	return Promise.reject();
};

// response
axios.interceptors.response.use(
	res => {
		NProgress.done();

		if (res.status == 401) {
			return onerror(401);
		}

		if (res.status == 403) {
			return onerror(403);
		}

		if (res.status == 404) {
			return Promise.reject();
		}

		if (res.status == 500) {
			return onerror(500);
		}

		const { code, data, msg } = res.data;
		switch (code) {
			case 1:
				return data;
			default:
				Message.error(msg);
				return Promise.reject(msg);
		}
	},
	error => {
		NProgress.done();
		return Promise.reject(error.toString());
	}
);

export default axios;
