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

let url='';
 // uEnvDev
 if (process.env.NODE_ENV === 'development') {
     // TODO
	 url='/api';
 }
 // uEnvProd
 if (process.env.NODE_ENV === 'production') {
     // TODO
	 url='/api';
 }
// create an axios instance
const service = axios.create({
	baseURL: url, // 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) {
			if(store.state.token)
			{
				// 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.tokenStr;
			}
			else{
				if(store.state.user.userCode==-undefined){
					uni.navigateTo({
						url:"/pages/LoginSupplier/LoginSupplier"
					});
				}
				else{
					uni.navigateTo({
						url:"/"
					});
				}
				
				return config;
			}
		}
		console.info('axioshelper request config',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应答原始数据', response);

		const res = response.data;
		//console.info('axioshelper应答response.data', res);
		if (res.code == 500) {
			uni.showModal({
				title: '系统错误',
				content: res.errMsg,
				showCancel: false
			});
			return res;
		}
		if(res.isSuccess==false&&(res.code==201||res.code==202||res.code==205)){
			uni.showModal({
				title: '警告',
				content: res.errMsg,
				showCancel: false,
				success:function(ret){
					if(ret.confirm){
						if(store.state.user.userCode==-undefined){
							uni.navigateTo({
								url:"/pages/LoginSupplier/LoginSupplier"
							});
						}
						else{
							uni.navigateTo({
								url:"/"
							});
						}						
					}
				}
			});
			return res;
		}
		//console.info(res);
		return res;
		
		
	},
	error => {
		console.log('axioshelper 应答error' + error) // for debug
		uni.showModal({
			title: '错误',
			content: error.message,
			showCancel: false
		});

		return Promise.reject(error)
	}
)

export default service
