<template>
  <div class="home g-flex">
    <keep-alive>
      <component class="g-flex__body" :is="components[componentId]"></component>
    </keep-alive>
    <app-tabbar class="home-tabbar" v-model:dataIndex="tabIndex" :data-list="tabList" @change="onChange" fixed />
  </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 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 { getGlobalUrlParams } = useNavigation()
const componentId = shallowRef('home')
const tabIndex = shallowRef(0)

const tabList: Tabbar[] = [
  {
    name: 'home',
    label: '首页',
    icon: 'icon-thj-logo-un',
    activeIcon: 'icon-thj-logo'
  },
  {
    name: 'purchase',
    label: '采购',
    icon: 'icon-caigou-1',
    activeIcon: 'icon-caigou'
  },
  {
    name: 'supplyDemand',
    label: '供求',
    icon: 'icon-gongqiu-1',
    activeIcon: 'icon-gongqiu'
  },
  {
    name: 'mine',
    label: '我的',
    icon: 'icon-wode-1',
    activeIcon: 'icon-wode'
  }
]

const onChange = (item: Tabbar) => {
  componentId.value = item.name
}

onActivated(() => {
  const { tabName } = getGlobalUrlParams()
  if (tabName) {
    tabIndex.value = tabList.findIndex((e) => e.name === tabName)
  }
})

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

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