<template>
  <div class="home g-flex">
    <router-view v-slot="{ Component }">
      <RouterTransition :css="cssTransition">
        <!-- 缓存所有组件 -->
        <keep-alive>
          <component class="g-flex__body" :is="Component" />
        </keep-alive>
      </RouterTransition>
    </router-view>
    <app-tabbar class="home-tabbar" :data-list="tabList" :data-index="currentTab" @change="onTabClick" fixed />
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed, nextTick, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Tabbar } from '@mobile/components/base/tabbar/types'
import AppTabbar from '@mobile/components/base/tabbar/index.vue'
import RouterTransition from '@mobile/components/base/router-transition/index.vue'

const router = useRouter()
const route = useRoute()
const cssTransition = ref(true) // 是否使用css动画
const currentTab = ref(0)

const tabIndex = computed(() => tabList.findIndex((e) => e.name === route.name))

const tabList: Tabbar[] = [
  {
    name: 'HomeIndex',
    label: '首页',
    icon: {
      active: require('@mobile/assets/icon/wap-home.svg'),
      inactive: require('@mobile/assets/icon/wap-home-o.svg'),
    }
  },
  {
    name: 'HomeMall',
    label: '市场',
    icon: 'g-icon--mall'
  },
  {
    name: 'HomeCart',
    label: '购物车',
    icon: 'g-icon--cart'
  },
  {
    name: 'HomeMine',
    label: '我的',
    icon: 'g-icon--mine'
  }
]

const onTabClick = (index: number) => {
  cssTransition.value = false
  router.replace({ name: tabList[index].name })
}

watch(() => route.name, () => {
  if (tabIndex.value > -1) {
    cssTransition.value = false
    currentTab.value = tabIndex.value
  }
  nextTick(() => {
    cssTransition.value = true
  })
})

onMounted(() => {
  currentTab.value = tabIndex.value
})
</script>

<style lang="less">
@import './index.less';
</style>