 import {baseURL,apiURL,cffpURL} from "../environments/environment";
// 白名单，不需要携带token就允许被访问的接口
const whiteApiList = [`${apiURL}/authorize/obtainToken`, `${apiURL}/authorize/checkToken`, `${cffpURL}/user/loginVerification`,`${apiURL}/appVersion/checkIsUpdate`,
						`${cffpURL}/accessLog/accessLogSave`,`${cffpURL}/user/powerQuery`,`${cffpURL}/user/wxLogin`];
export const interceptor = () => {
	uni.addInterceptor('request', {

		// 请求拦截器
		invoke(args) {
			// console.log('请求拦截器',args.url);
			// 加载loading
			// uni.showLoading({
			//   title: '加载中...'
			// });
			
			// 当本地没有token，并且接口地址没在白名单内，需要重新获取token
			if (!uni.getStorageSync('uni-token') && !whiteApiList.includes(args.url)) {
				
				const params = {
					ticket:'uni-app',
					loginId:null
				}
				let h5userId = uni.getStorageSync('cffp_userId');
				if (h5userId) {
					params.loginId = h5userId;
				}
				uni.request({
					url: `${apiURL}/authorize/obtainToken`,
					method: 'POST',
					data: params,
					success: (res) => {
						
						if (res.statusCode === 200) {
							uni.setStorageSync('uni-token', res.data['data']['token']);
							let isHas = window.location.href.indexOf('?')==-1?'?':'&';
							window.location.href = window.location.href + isHas + 't_reload=' + new Date().getTime();
						}
					}
				})
			}
			// request 触发前拼接 url

			//设置请求头及token
			args.header = {
				'content-type': args.method === 'POST' ? 'application/json' : 'application/x-www-form-urlencoded',
				'X-Authorization': uni.getStorageSync('uni-token') ? uni.getStorageSync('uni-token') : '',
				// 'Access-Control-Allow-Headers': 'appId',
				// 'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
				// 'Access-Control-Max-Age': 86400,
			}
			// console.log(args.header)
		},

		// 响应拦截器，可以对数据进行预处理
		success(args) {
			// uni.hideLoading()
			 //console.log(args);
			if(args && args.data && args.data.errorCode && "T001"==args.data.errorCode){
				// uni.redirectTo({
				// 	url:'/components/login/login'
				// })
				 uni.removeStorageSync('isLogin');
				 uni.switchTab({
					url:'/pages/index/index'
				})
			}
		},
		fail() {
			// console.log('interceptor-fail', err)
			// console.log('请求失败')
			// uni.hideLoading()
		},
		complete() {
			
			// uni.hideLoading()
		}
	})
}
