<template>
  <van-tabbar v-model="activeTab" :fixed="fixed" :placeholder="placeholder" :safe-area-inset-bottom="safeArea" route>
    <van-tabbar-item
      v-for="item in tabList"
      :key="item.path"
      :to="item.path"
      :icon="item.icon"
      :badge="item.badge"
      :dot="item.dot"
    >
      {{ $t(item.title) }}
    </van-tabbar-item>
  </van-tabbar>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import { useRoute } from 'vue-router'
import { useAppStore } from '@/store/modules/app'

const props = defineProps({
  fixed: {
    type: Boolean,
    default: true
  },
  placeholder: {
    type: Boolean,
    default: true
  },
  safeArea: {
    type: Boolean,
    default: true
  }
})

const route = useRoute()
const appStore = useAppStore()
const activeTab = ref(0)

// Tab列表配置
const tabList = computed(() => {
  // 基础 Tab 配置
  const tabs = [
    {
      path: '/index',
      icon: 'home-o',
      title: 'index.home'
    },
    {
      path: '/menu',
      icon: 'apps-o',
      title: 'menu.title'
    },
    {
      path: '/order',
      icon: 'orders-o',
      title: 'order.title'
    },
    {
      path: '/mine',
      icon: 'user-o',
      title: 'mine.title'
    }
  ]

  // 如果在店铺模式或桌台模式下，首页图标应指向该店铺的菜单页/首页
  if (!appStore.isPlatformMode && appStore.currentShop?.id) {
    // 构造带有查询参数的路径
    let shopHomePath = `/menu?shopId=${appStore.currentShop.id}`
    
    // 如果有桌台信息，也带上
    if (appStore.currentTable?.code) {
      shopHomePath += `&tableCode=${appStore.currentTable.code}`
    }

    // 替换第一个 Tab (首页) 的路径
    tabs[0].path = shopHomePath
    
    // 可选：如果希望"菜单" Tab 也指向同一个地方（或者隐藏它），
    // 这里保持原状，因为 /menu 本身会读取 store 中的 shopId
  }

  return tabs
})

// 监听路由变化更新active
watch(
  () => route.path,
  (newPath) => {
    // 简单匹配 path，忽略 query
    const index = tabList.value.findIndex((item) => {
      // 处理带参数的 path 比较
      const itemPathBase = item.path.split('?')[0]
      return itemPathBase === newPath
    })
    
    if (index !== -1) {
      activeTab.value = index
    }
  },
  { immediate: true }
)
</script>

<style scoped>
/* 自定义样式可在这里添加 */
</style>
