<template>
  <div class="home g-flex">
    <keep-alive>
      <component class="g-flex__body" :is="components[componentId]"></component>
    </keep-alive>
    <app-tabbar class="home-tabbar" :data-list="tabList" :dataIndex="tabIndex" @click="onTabClick" />
  </div>
</template>

<script lang="ts" setup>
import { shallowRef, onActivated } from 'vue'
import { dialog } from '@/utils/vant'
import { Tabbar } from '@mobile/components/base/tabbar/interface'
import { GetAppUpdateInfo } from '@/services/api/common'
import { useNavigation } from '@/hooks/navigation'
import { loginStore } from '@/stores'
import plus from '@/utils/h5plus'
import AppTabbar from '@mobile/components/base/tabbar/index.vue'
import Home from './components/main/index.vue'
import Purchase from '@mobile/views/purchase/list/index.vue'
import SupplyDemand from '@mobile/views/supply-demand/list/index.vue'
import Mine from '@mobile/views/mine/main/index.vue'

const components = {
  home: Home,
  purchase: Purchase,
  supplyDemand: SupplyDemand,
  mine: Mine,
}

const { token } = loginStore.$mapGetters()
const { routerTo, getGlobalUrlParams } = useNavigation()
const componentId = shallowRef('home')
const tabIndex = shallowRef(0)

const tabList: Tabbar[] = [
  {
    name: 'home',
    label: '首页',
    icon: 'icon-home',
    activeIcon: 'icon-home-active',
  },
  {
    name: 'purchase',
    label: '采购',
    icon: 'icon-purchase',
    activeIcon: 'icon-purchase-active',
  },
  // {
  //   name: 'supplyDemand',
  //   label: '供求',
  //   icon: 'icon-supply-demand',
  //   activeIcon: 'icon-supply-demand-active',
  // },
  {
    name: 'mine',
    label: '我的',
    icon: 'icon-mine',
    activeIcon: 'icon-mine-active',
  }
]

const onTabClick = ({ name }: Tabbar, index: number) => {
  if (name === 'home' || token.value) {
    tabIndex.value = index
    componentId.value = name
  } else {
    routerTo('UserLogin')
  }
}

onActivated(() => {
  const { tabName, showLogin } = getGlobalUrlParams()
  const index = tabList.findIndex((e) => e.name === tabName)
  if (index > -1) {
    tabIndex.value = index
    componentId.value = tabList[index].name
  }
  if (showLogin) {
    routerTo('UserLogin')
  }
})

if (plus.getSystemInfo('os') === 'Android') {
  const currentVersionCode = plus.getSystemInfo('versionCode')
  // 获取应用更新信息
  GetAppUpdateInfo().then((res) => {
    const data = JSON.parse(res)
    if (data) {
      const { LastVersionCode, ApkUrl } = data[0] as Model.AppUpdateInfo
      if (Number(LastVersionCode) > Number(currentVersionCode)) {
        dialog({
          message: '发现新版本，是否更新？',
          showCancelButton: true,
          confirmButtonText: '更新'
        }).then(() => {
          plus.updateApp(ApkUrl)
        })
      }
    }
  })
}
</script>

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