import axios from 'axios'
import router from '../router.js'
// import {
// 	MessageBox,
// 	Toast
// } from 'mint-ui'
import {
	Message
} from 'element-ui'
import store from '../store.js'
// create an axios instance
const service = axios.create({
	baseURL: store.state.www, // url = base url + request url
	// withCredentials: true, // send cookies when cross-domain requests
	timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
	config => {
		// do something before request is sent
		// let each request carry token
		// ['X-Token'] is a custom headers key
		// please modify it according to the actual situation
		// config.headers['X-Token'] = getToken()
		// if(config.method=='get'){
		// 	if(!config.params){
		// 		config.params={};
		// 	}
		// 	config.params.token = getToken();
		// }
		// if(config.method=='post'){
		// 	config.data.token = getToken();
		// }
		return config
	},
	error => {
		// do something with request error
		console.log(error) // for debug
		return Promise.reject(error)
	}
)

service.interceptors.response.use(
	response => {
		const res = response.data
		// 解析字符串为数字
		res.errcode = parseInt(res.status);
		res.message = res.msg;
		// console.log(typeof res.errcode);
		if (res.errcode !== 200) {
			if (res.errcode === 1001) {
				if (res.message.includes('您已经登录') || res.message.includes('您已经注册')) {
					router.push('/');
				}
			};
			if (res.errcode === 2000) {
					let url = res.data.wxurl + '?url=' + encodeURIComponent(window.location.href);
					window.location.href = url;
			} else if (res.errcode === 2002) {
					router.push("/login");
			} else {
				// Toast({
				// 	message: res.message || 'Error',
				// 	duration: 1 * 1000
				// })
				// this.$message.error('错了哦，这是一条错误消息');
				Message.error(res.message || 'Error')
			}
			return Promise.reject(new Error(res.message || 'Error'))
		} else {
			// console.log(res);
			return res
		}
	},
	error => {
		console.log('err' + error) // for debug
		// Toast({
		// 	message: '加载错误请刷新重试！',
		// 	duration: 1 * 1000
		// })
		Message.error('加载错误请刷新重试')
		return Promise.reject(error)
	}
)
export default service