import { config } from '@/common/config.js';
import store  from '../store/index.js'
// vm，就是我们在vue文件里面的this，所以我们能在这里获取vuex的变量，比如存放在里面的token
const install = (Vue, vm) => {
	Vue.prototype.$u.http.setConfig({
		baseUrl: config.baseUrl
	});
	// 请求拦截，配置Token等参数
	Vue.prototype.$u.http.interceptor.request = (config) => {
		if(vm.vuex_token){
			config.header.Authorization = `Bearer ${vm.vuex_token}`;
		}
		// 请求地址加时间戳
		config.url = config.url + '?t=' + Date.now()
		let noTokenList = ['/client/wechat/h5/code/', '/client/auth/sendSmsCodeV2', '/client/auth/verifyCodeV2'];
		if(noTokenList.includes(config.url)) config.header.noToken = true;
		return config; 
	}
	// 响应拦截，判断状态码是否通过
	Vue.prototype.$u.http.interceptor.response = (res) => {
		if(res.code == 200) {
			return res;  
		} else if(res.code == 401 || res.code == 400) {
			const backUrl = location.href
			// 判断浏览器
			const ua = window.navigator.userAgent.toLowerCase();
			if (ua.match(/MicroMessenger/i) == 'micromessenger') {
				// 微信中打开
				vm.$u.route('pages/wechatLogin/wechatLogin', { backUrl })
			} else {
				// 普通浏览器中打开
				localStorage.setItem('backUrl', backUrl)
				localStorage.removeItem('lifeData')
				uni.showModal({
					title: '提示',
					content: '未查询到登录信息或信息已失效, 请重新登录',
					showCancel: false,
					success: function(res) {
						if (res.confirm) {
							uni.navigateTo({
								url: "/pages/center/phoneLogin/phoneLogin"
							})
						}
					}
				});
			}
		} else {
			uni.showToast({
				title: res.msg || '程序错误!',
				duration: 2000,
				icon: 'none'
			})
		};
	}
}

export default {
	install
}