<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" @change="onChange" fixed />
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { dialog } from '@/utils/vant'
import { Tabbar } from '@mobile/components/base/tabbar/interface'
import { GetAppUpdateInfo } from '@/services/api/common'
import plus from '@/utils/h5plus'
import AppTabbar from '@mobile/components/base/tabbar/index.vue'
import Home from './components/main/index.vue'
import Purchase from './components/purchase/index.vue'
import SupplyDemand from './components/supply-demand/index.vue'
import Market from './components/market/index.vue'
import Mine from './components/mine/index.vue'
import axios from 'axios'

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

const componentId = ref('home')

const tabList: Tabbar[] = [
  {
    name: 'home',
    label: '首页',
    icon: 'icon-shouye-1',
    activeIcon: 'icon-shouye'
  },
  {
    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 = (index: number) => {
  if (![2].includes(index)) {
    componentId.value = tabList[index].name
  }
}

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

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