<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="#077e43" 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: 'Agriculture',
          Label: '助农区',
          Icon_Active: '/img/Agriculture_Active.png',
          Icon_Inactive: '/img/Agriculture_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',
        },
      ],
      lastClickedTab: null,
      clickTimer: null,
    }
  },
  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.lastClickedTab === name) {
        // 重复点击，刷新当前页面
        window.location.reload()
        // this.$router.replace({ name })
      } else {
        // 正常切换 tab
        this.$router.push({ name })
      }
      this.lastClickedTab = name
    }
  }
}
</script>