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

const guard = (router: Router) => {
	router.beforeEach(async (to, from, next) => {
		if (true) {
			console.log(location);
		}

		//监听到登陆事件
		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) {
				toast.message = `登陆失败`;
				setTimeout(() => {
					Toast.clear();
				}, 1000);
			}
		}

		//检测token状态,token为空直接跳转至登陆链接,token存在则请求某个接口验证token有效性
		if (store.getters.getToken === "") {
			if (to.path === "/marked") {
				next();
				return;
			}
			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`);
		} else {
			userInfo();
		}

		try {
			const userTime = dayjs(store.getters.getUserData.expireTime).valueOf();
			const currentTime = dayjs().valueOf();
			switch (to.path) {
				case "/exercise":
					if (userTime - currentTime > 0) {
						next();
					} else {
						Toast.fail("会员到期");
					}
					break;
				case "/mockTest":
					if (userTime - currentTime > 0) {
						next();
					} else {
						Toast.fail("会员到期");
					}
					break;
				default:
					next();
					break;
			}
		} catch (error) {}
	});
};
export default guard;
