import axios from 'axios'
import {
	getToken
} from '@/common/auth.js'
import store from '@/store/index.js'

// create an axios instance
const service = axios.create({
	baseURL: '/api', // url = base url + request url
	// withCredentials: true, // send cookies when cross-domain requests
	//crossDomain=true,
	//headers: {'Content-Type': 'application/x-www-form-urlencoded'},
	timeout: 20000 // request timeout
})

// request interceptor
service.interceptors.request.use(
	config => {
		// do something before request is sent
		console.info("axioshelper request");
		//console.info(mget.getters);
		//console.info(store);
		if (store.state.isLogin) {
			// let each request carry token
			// ['X-Token'] is a custom headers key
			// please modify it according to the actual situation
			config.headers['X-Token'] = store.state.token;
		}
		console.info(config);
		return config;
	},
	error => {
		// do something with request error
		console.log(error) // for debug
		return Promise.reject(error)
	}
)

// response interceptor
service.interceptors.response.use(
	/**
	 * If you want to get http information such as headers or status
	 * Please return  response => response
	 */

	/**
	 * Determine the request status by custom code
	 * Here is just an example
	 * You can also judge the status by HTTP Status Code
	 */
	response => {
		console.info("axioshelper.js response");
		console.info('axioshelper', response);

		const res = response.data;
		if (res.code == 500) {
			uni.showModal({
				title: '系统错误',
				content: res.message,
				showCancel: false
			});
			return;
		}
		//console.info(res);
		return res;
		
		// if the custom code is not 20000, it is judged as an error.
		// if (!res) {
		// 	uni.showModal({
		// 		content: "登录超时，请重新登录",
		// 		showCancel: false
		// 	});

		// 	// 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;

		// 	console.info("message:" + res.message);
		// 	return Promise.reject(new Error(res.message || 'Error'))
		// } else {
		// 	console.info("正常登录");
		// 	return res;
		// }
	},
	error => {
		console.log('error' + error) // for debug
		uni.showModal({
			title: '错误',
			content: error.message,
			showCancel: false
		});

		return Promise.reject(error)
	}
)

export default service
