<template>
	<view class="placeholder safe-area" v-if="placeholder && fixed"></view>
	<view class="tab-bar-wrap safe-area" :style="[getTabBarWrapStyle]">
		<view class="tab-bar">
			<!-- 左侧：首页 -->
			<view class="menu" @click="go(menus[0].link)">
				<image v-if="getPath === menus[0].link" :src="getFileUrl(menus[0].img)" mode="aspectFill"></image>
				<image v-else :src="getFileUrl(menus[0].imgon)" mode="aspectFill"></image>
				<view class="text" :class="{ sele: getPath === menus[0].link }">{{ menus[0].title }}</view>
			</view>

			<!-- 中间：扫码点餐 - 点击先调起微信扫一扫 -->
			<view class="menu-center" @click="handleScanOrder">
				<view class="scan-btn">
					<image :src="getFileUrl(menus[1].img)" mode="aspectFill"></image>
				</view>
				<image :src="getFileUrl(menus[1].imgon)" mode="heightFix" class="qrT-img"></image>
			</view>

			<!-- 右侧：我的 -->
			<view class="menu" @click="go(menus[2].link)">
				<image v-if="getPath === menus[2].link" :src="getFileUrl(menus[2].img)" mode="aspectFill"></image>
				<image v-else :src="getFileUrl(menus[2].imgon)" mode="aspectFill"></image>
				<view class="text" :class="{ sele: getPath === menus[2].link }">{{ menus[2].title }}</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { computed, unref } from 'vue';
import { getFileUrl } from '@/utils/file.js';
import { SCAN_QR_CACHE } from '@/settings/enums.js';
import { useUserStore } from '@/store/user.js';
import { TOKEN } from '@/settings/enums.js';

const menus = [
	{ title: '首页', link: '/pages/index/index', img: 'img/tabbar/index1.png', imgon: 'img/tabbar/index2.png' },
	{ title: '扫码点餐', link: '/pages/numberOfDiners/index', img: 'img/tabbar/qr2.png', imgon: 'img/tabbar/qr.png' },
	{ title: '我的', link: '/pages/personal/index', img: 'img/tabbar/personal1.png', imgon: 'img/tabbar/personal2.png' }
];

const props = defineProps({
	placeholder: { type: Boolean, default: false }, // 是否显示占位
	fixed: { type: Boolean, default: true } // 是否定位
});
const getTabBarWrapStyle = computed(() => ({
	position: props.fixed ? 'fixed' : 'relative'
}));

// 解析扫码内容：支持小程序码 path、scene，以及 s=店铺id&t=桌号id、URL、JSON 等格式
function parseScanResult(str) {
	const trim = (v) => (v == null ? '' : String(v).trim());
	let storeId = '';
	let tableId = '';
	if (!str) return { storeId, tableId };
	let s = trim(str);
	const parseKv = (text) => {
		const out = { storeId: '', tableId: '' };
		const keys = {
			store: ['s', 'storeid', 'store_id'],
			table: ['t', 'tableid', 'table_id', 'tableno', 'table']
		};
		text.split('&').forEach((pair) => {
			const eq = pair.indexOf('=');
			if (eq > 0) {
				const k = pair.substring(0, eq).trim().toLowerCase();
				let v = pair.substring(eq + 1).trim();
				try {
					v = decodeURIComponent(v);
				} catch (_) {}
				v = trim(v);
				if (keys.store.includes(k)) out.storeId = v;
				if (keys.table.includes(k)) out.tableId = v;
			}
		});
		return out;
	};
	const parseScene = (sceneStr) => {
		let decoded = sceneStr;
		try {
			decoded = decodeURIComponent(decoded);
		} catch (_) {}
		decoded = trim(decoded);
		// scene 为 base64 编码的 JSON（小程序码常见）
		if (/^[A-Za-z0-9+/=]+$/.test(decoded) && decoded.length > 20) {
			try {
				const jsonStr = typeof atob === 'function' ? atob(decoded) : '';
				if (jsonStr && jsonStr.startsWith('{')) {
					const obj = JSON.parse(jsonStr);
					return {
						storeId: trim(obj?.storeId ?? obj?.store_id ?? obj?.s ?? ''),
						tableId: trim(obj?.tableId ?? obj?.table_id ?? obj?.tableid ?? obj?.t ?? obj?.tableNo ?? obj?.table ?? '')
					};
				}
			} catch (_) {}
		}
		// scene 为 JSON 字符串
		if (decoded.startsWith('{') && decoded.endsWith('}')) {
			try {
				const obj = JSON.parse(decoded);
				return {
					storeId: trim(obj?.storeId ?? obj?.store_id ?? obj?.s ?? ''),
					tableId: trim(obj?.tableId ?? obj?.table_id ?? obj?.tableid ?? obj?.t ?? obj?.tableNo ?? obj?.table ?? '')
				};
			} catch (_) {}
		}
		// scene 为 storeId_tableId 下划线分隔（常见小程序码格式）
		if (/^\d+_\d+$/.test(decoded)) {
			const [sid, tid] = decoded.split('_');
			return { storeId: trim(sid), tableId: trim(tid) };
		}
		// scene 仅为数字，视为桌号
		if (/^\d+$/.test(decoded)) {
			return { storeId: '', tableId: decoded };
		}
		const fromKv = parseKv(decoded);
		if (!fromKv.tableId && /^\d+$/.test(decoded)) fromKv.tableId = decoded;
		return fromKv;
	};
	try {
		// 1. 小程序码 path 格式：pages/xxx?scene=xxx
		const qIdx = s.indexOf('?');
		const hIdx = s.indexOf('#');
		if (qIdx >= 0) {
			const queryPart = hIdx >= 0 ? s.substring(qIdx + 1, hIdx) : s.substring(qIdx + 1);
			const params = new Map();
			queryPart.split('&').forEach((pair) => {
				const eq = pair.indexOf('=');
				if (eq > 0) {
					const k = pair.substring(0, eq).trim();
					let v = pair.substring(eq + 1).trim();
					try {
						v = decodeURIComponent(v);
					} catch (_) {}
					params.set(k, v);
				}
			});
			const scene = params.get('scene') || params.get('Scene');
			if (scene) {
				return parseScene(scene);
			}
			return parseKv(queryPart);
		}
		// 2. JSON 格式
		if ((s.startsWith('{') && s.endsWith('}')) || (s.startsWith('[') && s.endsWith(']'))) {
			const obj = JSON.parse(s);
			return {
				storeId: trim(obj?.storeId ?? obj?.store_id ?? obj?.s ?? ''),
				tableId: trim(obj?.tableId ?? obj?.table_id ?? obj?.tableid ?? obj?.t ?? obj?.tableNo ?? obj?.table ?? '')
			};
		}
		// 3. key=value 格式
		return parseKv(s);
	} catch (err) {
		console.warn('parseScanResult', err);
	}
	return { storeId, tableId };
}

// 点击扫码点餐：未登录提示请登录；已登录扫码后跳转点餐页
function handleScanOrder() {
	const userStore = useUserStore();
	const token = userStore.getToken || uni.getStorageSync(TOKEN) || '';
	if (!token) {
		uni.showToast({ title: '请登录', icon: 'none' });
		return;
	}
	uni.scanCode({
		scanType: ['wxCode', 'qrCode', 'barCode'],
		success: (res) => {
			const result = (res?.path || res?.result || '').trim();
			const { storeId, tableId } = parseScanResult(result);
			const payload = { raw: result, storeId, tableId };
			uni.setStorageSync(SCAN_QR_CACHE, JSON.stringify(payload));
			if (storeId) uni.setStorageSync('currentStoreId', storeId);
			if (tableId) uni.setStorageSync('currentTableId', tableId);
			const diners = uni.getStorageSync('currentDiners') || '1';
			uni.setStorageSync('currentDiners', diners);
			if (!tableId) {
				uni.showToast({ title: '未识别到桌号，请扫描正确的桌号二维码', icon: 'none' });
				return;
			}
			uni.reLaunch({
				url: `/pages/orderFood/index?tableid=${encodeURIComponent(tableId)}&diners=${encodeURIComponent(diners)}`
			});
		},
		fail: (err) => {
			const msg = err?.errMsg || '';
			if (msg && !msg.includes('cancel')) {
				if (msg.includes('auth') || msg.includes('camera') || msg.includes('scope')) {
					uni.showModal({
						title: '提示',
						content: '需要相机权限才能扫码，请在设置中开启',
						confirmText: '去设置',
						success: (res) => {
							if (res.confirm) uni.openSetting();
						}
					});
				} else {
					uni.showToast({ title: msg || '扫码失败', icon: 'none' });
				}
			}
		}
	});
}

// 底部 tabBar 跳转（需在 pages.json 中配置 tabBar.list）
function go(url) {
	if (url === unref(getPath)) return;
	uni.switchTab({ url });
}

const getPath = computed(() => {
	const pages = getCurrentPages(); // 获取路由栈
	console.log('/' + pages[pages.length - 1].route);
	return '/' + pages[pages.length - 1].route;
});
</script>

<style lang="scss" scoped>
.placeholder {
	height: 140rpx;
	box-sizing: content-box;
}

.tab-bar-wrap {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	z-index: 99;
	background-color: #ffffff;
	box-shadow: 0 -2rpx 16rpx 0 rgba(0, 0, 0, 0.08);

	.tab-bar {
		// padding: 16rpx 0;
		// padding-bottom: calc(16rpx + env(safe-area-inset-bottom));
		display: flex;
		align-items: flex-end;
		justify-content: space-around;
		position: relative;
		padding-top: 20rpx;

		.menu {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			flex: 1;
			padding: 0 40rpx;
			padding-bottom: 0;
			transition: all 0.3s ease;

			image {
				width: 48rpx;
				height: 48rpx;
				transition: transform 0.3s ease;
			}

			.text {
				font-size: 22rpx;
				color: #999999;
				margin-top: 8rpx;
				transition: all 0.3s ease;
				font-weight: 400;
			}

			.text.sele {
				color: #333333;
				font-weight: 500;
			}

			&:active {
				opacity: 0.7;
				transform: scale(0.95);
			}
		}

		.menu-center {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			position: absolute;
			bottom: -20rpx;
			margin: 0 40rpx;
			// transform: translateY(-35rpx);
			transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
			background-color: #fff;
			border-radius: 50%;
			padding: 20rpx;

			.scan-btn {
				width: 110rpx;
				height: 110rpx;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				margin-bottom: 6rpx;
				position: relative;
				transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
				background: linear-gradient(35deg, #FCB73F 0%, #FC733D 100%);
				box-shadow: 0rpx 0rpx 11rpx 0rpx rgba(0, 0, 0, 0.16);

				image {
					width: 42rpx;
					height: 42rpx;
					filter: brightness(0) invert(1);
					transition: transform 0.3s ease;
					margin-bottom: 20rpx;
				}
			}

			.qrT-img {
				width: 85rpx;
				height: 22rpx;
				position: absolute;
				bottom: 36rpx;
				left: 50%;
				transform: translateX(-50%);
			}

			.text-center {
				font-size: 22rpx;
				color: #ff8844;
				margin-top: 4rpx;
				font-weight: 500;
				transition: all 0.3s ease;
			}

			&:active {
				transform: translateY(-35rpx) scale(0.92);

				.scan-btn {
					box-shadow: 0 4rpx 16rpx 0 rgba(255, 136, 68, 0.3),
						0 1rpx 4rpx 0 rgba(255, 136, 68, 0.15);

					image {
						transform: scale(0.9);
					}
				}
			}
		}
	}
}
</style>
