<template>
  <router-view></router-view>
  <van-tabbar route>
    <van-tabbar-item replace to="/hospitalService" icon="home-o"> 医疗服务 </van-tabbar-item>
    <van-tabbar-item replace to="/mine" icon="user-o"> 个人中心 </van-tabbar-item>
    <van-tabbar-item replace to="/hospitalIntroduction" icon="hotel-o"> 医院信息 </van-tabbar-item>
  </van-tabbar>
</template>

<script setup>
import { getToken, getPatientIdByOpenid } from '@/api/patient-id-cards'
import store from '@/store'
import { useRouter } from 'vue-router'
import { onMounted } from 'vue'

const router = useRouter()
const executeNavigate = () => {
  let to = router.currentRoute.value.params.to
  if (!to) {
    to = 'hospitalService'
  }
  if (router.currentRoute.value.path.startsWith('/wxService')) {
    let pathInfo = to.split('_')
    if (pathInfo.length === 1) {
      router.push('/' + to)
    } else if (pathInfo.length === 2) {
      router.push('/' + pathInfo[0] + '/' + pathInfo[1])
    } else {
      router.push('/' + pathInfo[0] + '/' + pathInfo[1] + '/' + pathInfo[2])
    }
  }
}

const onAppStart = () => {
  return new Promise((resolve, reject) => {
    if (localStorage.getItem('token')) {
      resolve()
    } else {
      const code = router.currentRoute.value.params.code
      getToken(code).then((r) => {
        localStorage.setItem('token', r)
        resolve()
      }).catch((e) => {
        reject(e)
      })
    }
  })
}

function getPatientCards() {
  getPatientIdByOpenid().then((cards) => {
    store.dispatch({
      type: 'storePatientCards',
      cards,
    }).then(() => {
      executeNavigate()
    })
  })
}

onMounted(() => {
  onAppStart().then(() => {
    getPatientCards()
  })
})
</script>
