<template>
  <router-view v-slot="{ Component, route }">
    <keep-alive>
      <component :is="Component" :key="route.name" v-if="route.meta.cache" />
    </keep-alive>
    <component :is="Component" :key="route.name" v-if="!route.meta.cache" />
  </router-view>
  <van-tabbar v-model="DefaultActive" placeholder @change="changeActive" active-color="#841e36" inactive-color="#1b1b1b"
    fixed>
    <van-tabbar-item v-for="item in Tabbars" :key="item.Name" :name="item.Name" :badge="getBadge(item)" :dot="item.Dot"
      @click="onTabClick(item.Name)">
      <span>{{ item.Label }}</span>
      <template #icon="props">
        <img :src="props.active ? item.Icon_Active : item.Icon_Inactive" />
      </template>
    </van-tabbar-item>
  </van-tabbar>
</template>

<script>
export default {
  name: 'Index',
  data() {
    return {
      DefaultActive: 'Home',
      Tabbars: [
        {
          Name: 'Home',
          Label: '主页',
          Icon_Active: '/img/Home_Active.png',
          Icon_Inactive: '/img/Home_Inactive.png',
        },
        {
          Name: 'Gift',
          Label: '商品区',
          Icon_Active: '/img/Gift_Active.png',
          Icon_Inactive: '/img/Gift_Inactive.png',
        },
        {
          Name: 'Mall',
          Label: '商城',
          Icon_Active: '/img/Mall_Active.png',
          Icon_Inactive: '/img/Mall_Inactive.png',
        },
        {
          Name: 'My',
          Label: '我的',
          Icon_Active: '/img/My_Active.png',
          Icon_Inactive: '/img/My_Inactive.png',
        },
      ],
          }
  },
  watch: {
    '$route.path': {
      handler() {
        this.updateActive()
      },
      immediate: true
    }
  },
  created() {
    this.updateActive();
  },
  methods: {
    updateActive() {
      const routeName = this.$route.name
      const tabbar = this.Tabbars.find(item => item.Name === routeName)
      if (tabbar) {
        this.DefaultActive = tabbar.Name
      }
    },
    changeActive(name) {
      this.$router.push({ name })
    },
    getBadge(item) {
      return item.Badge || ''
    },
    onTabClick(name) {
      if (this.$route.name === name) {
        // 当前路由，双击刷新
        this.$router.replace({ name })
      } else {
        this.$router.push({ name })
      }
    }
  }
}
</script>