import { computed, unref } from 'vue';
import { useUserStore } from '@/store/user.js';
import { REDIRECT_KEY } from '@/settings/enums.js';

// 登录后可进入页面（弹窗提示）
const loginList = [];

// 未登录时直接跳转首页的页面
const redirectToIndexPaths = ['/pages/orderFood/index'];

const navigateToInterceptor = {
	invoke({ url }) {
		const userStore = useUserStore();
		const getToken = computed(() => userStore.getToken);
		const path = url.split('?')[0];
		if (unref(getToken)) return true;

		if (redirectToIndexPaths.some((p) => path === p || path.endsWith(p))) {
			uni.reLaunch({ url: '/pages/index/index' });
			return false;
		}
		if (loginList.includes(path)) {
			uni.showModal({
				title: '提示',
				content: '未登录请先登录',
				success: function (res) {
					if (res.confirm) {
						uni.setStorageSync(REDIRECT_KEY, url);
					}
				}
			});
			return false;
		}
		return true;
	},
	success(args) {
		console.log('成功', args);
	},
	fail(err) {
		console.log('失败', err);
	}
};

export const routeInterceptor = {
	install() {
		uni.addInterceptor('navigateTo', navigateToInterceptor);
		uni.addInterceptor('reLaunch', navigateToInterceptor);
		uni.addInterceptor('redirectTo', navigateToInterceptor);
	}
};
