import axios from 'axios'
import store from '../store'
import Vue from 'vue'
//import {Dialog} from 'vant'
import router from '../router'
import  cookie from 'js-cookie'

Vue.use(cookie);
let _this=new Vue({
	el: '#app',
	router,
	store
  })

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/json;charset=utf-8'},
	timeout: 20000 // request timeout
})

// request interceptor
service.interceptors.request.use(
	config => {
		//var self=this;
		console.info('interceptors',_this);
		//console.info('interceptors',_this.$util);
		_this.$util.persistLogin(_this);
		// do something before request is sent
		//console.info("axioshelper request");
		//console.info(mget.getters);
		//console.info(store);
	    if (_this.$store.state.result) {
			// let each request carry token
			// ['X-Token'] is a custom headers key
			// please modify it according to the actual situation
			let tokenstr='';
			if(!_this.$store.state.token){
				_this.$router.push('/');
				return;
			}
			else{
				tokenstr=_this.$store.state.token.tokenStr;
			}
			config.headers['Authorization'] = tokenstr;
		}
		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 => {
		 //var self=this;
		console.info('axioshelper应答原始数据', response);

		var res = response.data;
		if (res.code == 500) {
			//console.info('dialog 系统错误',self.$dialog)
			_this.$dialog.alert({
				title: '系统错误',
				message: res.errMsg,
			  }).then(() => {
				// on close
			  });
			return;
		}
		if(res.isSuccess==false&&(res.code==201||res.code==202||res.code==205)){
            //console.info('dialog 警告',self.$dialog)
			_this.$dialog.alert({
				title: '警告',
				message: res.errMsg,
			  }).then(() => {
				// on close
				_this.$router.push('/');
			  });
			  
			return;
		}
		return res;
		
		 
	},
	error => {
		console.log('axioshelper 应答error' + error) // for debug
		

		return Promise.reject(error)
	}
)

export default service
