import axios from 'axios';
import store from '$project/store';
import router from '@/router';
import Vue from 'vue';
import Qs from 'qs';

import {
	getToken,
	getOpenId
} from '$project/utils/storage'

axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded'

// 创建axios实例
const service = axios.create({
	baseURL: process.env.VUE_APP_BACKEND_URL,
	timeout: 20000,
	// 请求头信息
	headers: {
		'Content-Type': 'application/x-www-form-urlencoded',
		'X-Requested-With': 'XMLHttpRequest',
	},
});

//request拦截器
service.interceptors.request.use(config => {
	let Authorization = getToken() ? getToken() : '';
	config.headers['Authorization'] = Authorization;
	return config;
}, error => {
	//对请求错误处理
	return Promise.reject(error);
});

// response拦截器
service.interceptors.response.use(
	response => {
		if (response.data.code === 200) {
			if (response.data.result) {
				return Promise.resolve(response.data.data);
			} else {
				return Promise.reject(response.data.message);
			}
		} else if (response.data.code === 415) {
			//这里不执行，token过期
		} else {
			//无code的情况
			if (response.data.result) {
				return Promise.resolve(response.data.data);
			} else {
				return Promise.reject(response.data.message);
			}

			// todo 根据返回值判定去向，比如token过期，未登录等等

			// 403 接口需要登录
			/* if (response.data.code === 403) {
				store.dispatch('clearToken');
				router.replace({
					name: 'Login',
					query: {
						redirect: router.currentRoute.fullPath
					}
				});
			} */

			return Promise.reject(response.data.message);
		}
	},
	error => {
		// alert('网络超时!请重新加载!');
		//console.error(error);
		// 判断请求异常信息中是否含有超时timeout字符串
		if (error.message.includes('timeout')) {
			return Promise.reject('请求超时,请稍后再试');
		} else if (error.message.includes('NetworkError')) {
			return Promise.reject('网络错误,请稍后再试');
		}
		return Promise.reject(error);
	}
);

export default service;
