<script setup lang="ts">
import home from '@/static/image/tab-bar/home.png'
import homeSelect from '@/static/image/tab-bar/home-select.png'
import manual from '@/static/image/tab-bar/manual.png'
import manualSelect from '@/static/image/tab-bar/manual-select.png'
import my from '@/static/image/tab-bar/me.png'
import mySelect from '@/static/image/tab-bar/me-select.png'
import plan from '@/static/image/tab-bar/plan.png'
import planSelect from '@/static/image/tab-bar/plan-select.png'

interface BottomItem {
  name: string
  icon: string
  iconSelect: string
  url: string
}

const tabList: Ref<BottomItem[]> = ref([
  { name: '首页', icon: home, iconSelect: homeSelect, url: 'pages/home/index' },
  { name: '喂养计划', icon: plan, iconSelect: planSelect, url: 'pages/feed-plan/index' },
  { name: '养宠手册', icon: manual, iconSelect: manualSelect, url: 'pages/pet-manual/index' },
  { name: '我的', icon: my, iconSelect: mySelect, url: 'pages/me/index' },
])

function handleTap(item: BottomItem) {
  uni.reLaunch({ url: `/${item.url}` })
}

function getCurrentPageUrl() {
  const pages = getCurrentPages() // Get the current pages stack
  const currentPage = pages[pages.length - 1] // Get the current page
  return currentPage.route // Return the route of the current page
}

const selectedIndex = computed(() => {
  return tabList.value.findIndex(item => item.url === getCurrentPageUrl())
})

const height = ref<number>(0)

const instance = getCurrentInstance()

if (instance) {
  const query = uni.createSelectorQuery().in(instance.proxy)
  query.select('#tabBar').boundingClientRect((data) => {
    if (data && !(Array.isArray(data))) {
      height.value = data.height as number
    }
  }).exec()
}
</script>

<template>
  <view
    class="w-full"
    :style="{
      height: `${height}px`,
    }" t
  />
  <view id="tabBar" class="w-full p-1 fixed bottom-0 left-0 safe-area  border-t-[0.5px] border-[#E7E7E7] bg-[#fff]">
    <view class="w-full flex gap-2">
      <view v-for="(item, index) in tabList" :key="index" class="flex flex-col items-center justify-center w-1/4" @tap="handleTap(item)">
        <image :src="selectedIndex === index ? item.iconSelect : item.icon" class="w-8 h-8" />
        <text
          class="text-3 mt-1"
          :class="selectedIndex === index ? 'text-primary' : 'text-default'"
        >
          {{ item.name }}
        </text>
      </view>
    </view>
  </view>
</template>

<style scoped>
.safe-area{
  padding-bottom: env(safe-area-inset-bottom);
}
</style>
