 import {apiURL,cffpURL} from "../environments/environment";
 import api from "@/api/api";
// 白名单，不需要携带token就允许被访问的接口
const whiteApiList = [`${apiURL}/authorize/obtainToken`, `${apiURL}/authorize/checkToken`, `${cffpURL}/user/loginVerification`,`${apiURL}/appVersion/checkIsUpdate`,
						`${cffpURL}/accessLog/accessLogSave`,`${cffpURL}/user/powerQuery`,`${cffpURL}/user/wxLogin`,`${cffpURL}/certificate/officialWebsiteDetail`];
export const interceptor = () => {
	uni.addInterceptor('request', {
		// 请求拦截器
		invoke(args) {
			// 当本地没有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();
						}
					}
				})
			}
			//设置请求头及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,
			}
		},
		// 响应拦截器，可以对数据进行预处理
		success(args) {
			if(args && args.data && args.data.errorCode && "T001"==args.data.errorCode){
				 uni.removeStorageSync('isLogin');
				 uni.switchTab({
					url:'/pages/index/index'
				})
			}
		},
		fail() {
			// console.log('interceptor-fail', err)
		},
		complete() {
			// uni.hideLoading()
		}
	})
}
