<script setup lang="ts">
import { ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const router = useRouter();
const route = useRoute();

const navigation = ref([
  {
    title: '主页',
    link: {
      name: 'home',
      path: '/home'
    },
    icon: '/tabbar/home.png'
  },
  {
    title: '伊调研',
    link: {
      name: 'home',
      path: '/home'
    },
    icon: '/tabbar/yl.png'
  },
  {
    title: '我的',
    link: {
      name: '',
      path: '/survey'
    },
    icon: '/tabbar/mine.png'
  }
]);
// 当前的 nav
const currentNav = navigation.value.find((item) => item.link.path === route.fullPath);
const activeTab = ref(currentNav?.title);

/**
 * Handle changing of navigation
 * @param {object} nav - the navigation item selected
 */
function handleChangeNav(title: string) {
  const nav = navigation.value.find((item) => item.title === title);
  const params: { [key: string]: string } = {};
  //  如果有 name 表示，优先取 name 参数
  nav && nav.link.name.length !== 0
    ? (params.name = nav.link.name as string)
    : (params.path = nav?.link.path as string);
  router.push(params);
}

watch(activeTab, (value: string) => {
  handleChangeNav(value);
});
</script>

<template>
  <div class="navigation">
    <van-tabbar v-model="activeTab">
      <van-tabbar-item v-for="item in navigation" :key="item.title" :name="item.title">
        <template #icon>
          <img :src="item.icon" />
        </template>
        {{ item.title }}
      </van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<style scoped lang="scss">
.navigation {
  width: 100vw;
  background-color: white;
  display: flex;
  flex-flow: row;
  justify-content: space-around;
  position: fixed;
  bottom: 0px;
  z-index: 10;
}

.navigation-item {
  display: flex;
  flex-flow: column nowrap;
  align-items: center;
}
</style>
