<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" @click="onTabClick" />
    <app-updater ios-update-url="https://itunes.apple.com/lookup?id=1661067556" />
  </div>
</template>

<script lang="ts" setup>
import { shallowRef, nextTick, watch, onMounted, computed } from 'vue'
import { fullloading } from '@/utils/vant'
import { Tabbar } from '@mobile/components/base/tabbar/interface'
import { useNavigation } from '@/hooks/navigation'
import { useLogin } from '@/business/login'
import { useLoginStore } from '@/stores'
import AppTabbar from '@mobile/components/base/tabbar/index.vue'
import AppUpdater from '@mobile/components/base/updater/index.vue'
import RouterTransition from '@mobile/components/base/router-transition/index.vue'

const { route, routerTo } = useNavigation()
const { userLogin } = useLogin()
const loginStore = useLoginStore()
const cssTransition = shallowRef(true) // 是否使用css动画
const currentTab = shallowRef(0)

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

const tabList: Tabbar[] = [
  {
    name: 'home-index',
    label: '首页',
    icon: 'icon-home',
    activeIcon: 'icon-home-active',
  },
  {
    name: 'home-purchase',
    label: '采购',
    icon: 'icon-purchase',
    activeIcon: 'icon-purchase-active',
  },
  {
    name: 'home-mine',
    label: '我的',
    icon: 'icon-mine',
    activeIcon: 'icon-mine-active',
  }
]

const onTabClick = (index: number) => {
  const { name } = tabList[index]
  if (index === 0 || loginStore.token) {
    routerTo(name, true)
  } else {
    fullloading((hideLoading) => {
      userLogin(true).then(() => {
        routerTo(name, true)
      }).catch(() => {
        routerTo('UserLogin')
      }).finally(() => {
        hideLoading()
      })
    }, '加载中...')
  }
}

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>