<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" />
  </div>
</template>

<script lang="ts" setup>
import { shallowRef, nextTick, watch, onMounted,computed } from 'vue'
import { fullloading, dialog } from '@/utils/vant'
import { versionToNumber } from '@/filters'
import { Tabbar } from '@mobile/components/base/tabbar/types'
import { getAppUpdateInfo } from '@/services/api/common'
import { useNavigation } from '@mobile/router/navigation'
import { useLogin } from '@/business/login'
import { useLoginStore } from '@/stores'
import plus from '@/utils/h5plus'
import AppTabbar from '@mobile/components/base/tabbar/index.vue'
import RouterTransition from '@mobile/components/base/router-transition/index.vue'

const { route, routerTo, getGlobalUrlParams, setGlobalUrlParams } = 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: 'g-icon-home--line',
    activeIcon: 'g-icon-home--fill',
  },
  {
    name: 'home-50101',
    label: '订单挂牌',
    icon: 'g-icon-listing--line',
    activeIcon: 'g-icon-listing--fill',
  },
  {
    name: 'home-mine',
    label: '我的',
    icon: 'g-icon-mine--line',
    activeIcon: 'g-icon-mine--fill',
  }
]

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

  if (name === 'home-index' || loginStore.token) {
    currentTab.value = index
    routerTo(name, true)
  } else {
    fullloading((hideLoading) => {
      userLogin(true).then(() => {
        currentTab.value = index
        routerTo(name, true)
      }).catch(() => {
        routerTo('user-login')
      }).finally(() => {
        hideLoading()
      })
    }, '加载中...')
  }
}

onMounted(() => {
  currentTab.value = tabIndex.value
  const os = plus.getSystemInfo('os')
  const currentVersion = plus.getSystemInfo('version')
  const currentVersionCode = plus.getSystemInfo('versionCode')

  if (os === 'Android') {
    // 监听下载进度
    const ondownload = plus.onDownload((filename, progress) => {
      if (progress === 100) {
        dialog({
          message: '新版本下载完成，是否安装？',
          showCancelButton: true,
          confirmButtonText: '安装'
        }).then(() => {
          plus.installApp(filename)
        }).catch(() => {
          plus.deleteFile(filename)
        })
      }
    })

    // 获取应用更新信息
    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.createDownload(ApkUrl)
          }).catch(() => {
            ondownload.cancel()
          })
        }
      }
    })
  }

  if (os === 'iOS') {
    // plus.httpRequest({
    //   url: 'https://itunes.apple.com/lookup?id=1661067556'
    // }).then((res) => {
    //   const results = res.data.results
    //   if (results?.length) {
    //     const { version, trackViewUrl } = results[0]
    //     if (versionToNumber(version) > versionToNumber(currentVersion)) {
    //       dialog({
    //         message: '发现新版本，是否更新？',
    //         showCancelButton: true,
    //         confirmButtonText: '更新'
    //       }).then(() => {
    //         plus.openURL(trackViewUrl)
    //       })
    //     }
    //   }
    // })
  }
})

watch(() => route.name, () => {
  const params = getGlobalUrlParams()
  if (params.tabIndex > -1) {
    onTabClick(params.tabIndex)
  } else if (tabIndex.value > -1) {
    onTabClick(tabIndex.value)
  } else {
    // 如果参数不是 tabIndex，需要保留到下一个路由
    setGlobalUrlParams(params)
  }
  nextTick(() => {
    cssTransition.value = true
  })
})
</script>

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