import { Router } from "vue-router";
import store from "@/store";
import dayjs from "dayjs";
import { Toast } from "vant";
import { useLogin, useUpdateUserInfo } from "@/hooks";
import { userInfo } from "@/api";

const guard = (router: Router) => {
	router.beforeEach(async (to, from, next) => {
		//如果是marked页面,不需要任何判断,直接进入
		if (to.path === "/marked") {
			next();
			return;
		}
		//监听到登陆事件
		if (to.query.state === "LOGIN") {
			// const toast = Toast.loading({
			// 	duration: 0, // 持续展示 toast
			// 	forbidClick: true,
			// 	message: "登陆中",
			// });
			await useLogin(to.query);
			// Toast("登录成功")
			next("./")
			// try {
			// 	await useLogin(to.query);
			// 	toast.message = `登陆成功`;
			// 	setTimeout(() => {
			// 		Toast.clear();
			// 	}, 500);
			// } catch (error) {
			// 	toast.message = `登陆失败`;
			// 	setTimeout(() => {
			// 		Toast.clear();
			// 		location.replace(`https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx67ca1b8c9816ef28&redirect_uri=https://jpcj-h5.zzxcx.net/home/test&response_type=code&scope=snsapi_userinfo&state=LOGIN#wechat_redirect`);
			// 	}, 1000);
			// }
		}
		//更新用户的信息
		useUpdateUserInfo();
		//检测token状态,token失效直接跳转至登陆链接
		// try {
		// 	useUpdateUserInfo();
		// 	const authTest = await userInfo();
		// 	if (authTest.data.code !== 200) {
		// 		throw authTest.data.msg;
		// 	}
		// } 
		// catch (error) {
		// 	//监听到登陆事件
		// 	if (to.query.state === "LOGIN") {
		// 		const toast = Toast.loading({
		// 			duration: 0, // 持续展示 toast
		// 			forbidClick: true,
		// 			message: "登陆中",
		// 		});
		// 		try {
		// 			await useLogin(to.query);
		// 			toast.message = `登陆成功`;
		// 			setTimeout(() => {
		// 				Toast.clear();
		// 			}, 500);
		// 		} catch (error) {
		// 			console.log(error)
		// 			toast.message = `登陆失败`;
		// 			setTimeout(() => {
		// 				Toast.clear();
		// 				location.replace(`https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx67ca1b8c9816ef28&redirect_uri=https://jpcj-h5.zzxcx.net/home/test&response_type=code&scope=snsapi_userinfo&state=LOGIN#wechat_redirect`);
		// 			}, 1000);
		// 		}
		// 	} else {
		// 		location.replace(`https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx67ca1b8c9816ef28&redirect_uri=${location.href}&response_type=code&scope=snsapi_userinfo&state=LOGIN#wechat_redirect`);
		// 	}
		// }
		console.log("会员")
		try {
			const userTime: number = dayjs(store.getters.getUserData.expireTime).valueOf();
			const currentTime: number = dayjs().valueOf();
			const vipPathSet = new Set(["/exercise", "/mockTest"]);
			if (vipPathSet.has(to.path)) {
				if (to.query.title === '顺序练习') {
					next();
				}
				else if (to.query.title === '分类练习') {
					next();
				}
				else if (to.query.title === '模拟考试') {
					next();
				}  
				else if (userTime - currentTime > 0) {
					next()

				}
				else {
					Toast.fail("会员到期");
					next("/buyVip");
				}
			} else {
				next();
			}
		} catch (error) {
	
		 }
	});
};
export default guard;
