<template>
	<view class="custom-tabbar">
		<view class="tabbar-border"></view>
		<view class="tabbar-list">
			<view 
				v-for="(item, index) in tabList" 
				:key="index" 
				class="tabbar-item"
				@click="handleNavigate(item.path)"
			>
				<image 
					class="tab-icon" 
					:src="isPathActive(item.path) ? item.activeIcon : item.icon" 
					mode="aspectFit"
				></image>
				<view 
					class="tab-text" 
					:class="{ 'tab-text-active': isPathActive(item.path) }"
				>
					{{ item.text }}
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import tabListData from '@/json/tabbar.json'

// 底部列表数据
const tabList = ref(tabListData || [])
// 当前页面路径
const currentRoute = ref('')

/**
 * 组件挂载时自动识别当前所在路径
 */
onMounted(() => {
	const pages = getCurrentPages()
	if (pages.length > 0) {
		const route = pages[pages.length - 1].route
		// 统一补齐前缀斜杠，方便与 tabbar.json 匹配
		currentRoute.value = route.startsWith('/') ? route : '/' + route
	}
})

/**
 * 判断路径是否匹配（高亮逻辑）
 */
const isPathActive = (path) => {
	if (!path || !currentRoute.value) return false
	// 格式化对比路径
	const targetPath = path.startsWith('/') ? path : '/' + path
	const currentPath = currentRoute.value.startsWith('/') ? currentRoute.value : '/' + currentRoute.value
	return currentPath === targetPath
}

/**
 * 页面跳转逻辑
 */
const handleNavigate = (path) => {
	const targetUrl = path.startsWith('/') ? path : '/' + path
	// 如果已经是当前页，则不重复跳转
	if (isPathActive(targetUrl)) return
	
	// 由于 pages.json 中没有 tabBar 配置，
	// 使用 reLaunch 跳转能保证页面栈清空，模拟 TabBar 行为
	uni.reLaunch({
		url: targetUrl,
		fail: (err) => {
			console.error('跳转失败：', err)
		}
	})
}
</script>

<style lang="scss" scoped>
.custom-tabbar {
	position: fixed;
	bottom: 0;
	left: 0;
	width: 100%;
	height: calc(110rpx + env(safe-area-inset-bottom));
	background-color: #ffffff;
	display: flex;
	flex-direction: column;
	z-index: 999;
	padding-bottom: env(safe-area-inset-bottom);
	box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.tabbar-border {
	height: 1px;
	background-color: rgba(0, 0, 0, 0.06);
	transform: scaleY(0.5);
}

.tabbar-list {
	display: flex;
	flex: 1;
	align-items: center;
	justify-content: space-around;
	padding: 0 10rpx;
}

.tabbar-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	flex: 1;
	height: 100%;
	
	&:active {
		opacity: 0.7;
	}
}

.tab-icon {
	width: 48rpx;
	height: 48rpx;
	margin-bottom: 4rpx;
}

.tab-text {
	font-size: 20rpx;
	color: #999999;
	transition: all 0.2s;
	
	&.tab-text-active {
		color: #f7ca3e;
		font-weight: bold;
	}
}
</style>
