import { useAuthData } from "any-hooks/auth/useAuthData";
import { HttpIntercept, HttpResponse, HTTP_INTERCEPT, RequestOptions, useInjector } from "vue-vulcan";
import { showToast } from "@tarojs/taro";

export function useHttpIntercept(): HttpIntercept {

	const { authData } = useInjector(useAuthData);
	
	const requestIntercept = (reqs: RequestOptions) => {
		console.log(reqs)
		const token = authData.value?.token || '';		
		const company_id = authData.value?.company_id || '';
		reqs.data.token = token;
		reqs.data.company_id = company_id;
		return new Promise( (resolve, reject) => {			
			if(token || reqs.path.includes('login') || reqs.path.includes('CallStatus')) {
				resolve(reqs)
			}	else {
				reject(`the http request ${reqs.path} need token`)
			}			
		})
	}
	
	const responseIntercept = (res: HttpResponse) => {
		switch(res.status) {
			case 404:
				showToast({title:'网络错误,请稍后再试'});
			break;
			case 504:
				showToast({title:'服务器响应超时,请稍后重试'});
			break;
		}
		return new Promise( resolve => {			
			if(checkResData(res.data)) {
				resolve(res.data.data)
			}			
		})
	}

	const checkResData = (data: any) => {
		if(data.success) return true;
		showToast({title: data.msg, icon: 'none'});
		return false;
	}

	
	return {
		requestIntercept,
		responseIntercept
	}
}

useHttpIntercept.token = HTTP_INTERCEPT;