import { browser } from '@/helpers/utils'
import { state } from '@/state'
import { Dialog } from 'vant'
import { createRouter, createWebHashHistory, Router } from 'vue-router'
import { postMessage } from '@/helpers/native-message'
import routes from './routes-tenant'
const router: Router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior() {
    return { left: 0, top: 0 }
  }
})

router.beforeEach((to, from, next) => {
  const title = to.meta.title
  document.title = (title || '酷乐秀') as any
  next()
  // if (browser().iPhone && !state.version) {
  // try {
  //   postMessage(
  //     {
  //       api: 'getVersion'
  //     },
  //     (res: any) => {
  //       state.version = res.version
  //       console.log(res, 'version')
  //       setTimeout(() => {
  //         next()
  //       }, 50)
  //     }
  //   )
  // } catch {}
  // // 为了处理上面方法的没有返回
  // setTimeout(() => {
  // if (!state.version) {
  //       next()
  //     // }
  //   // }, 5000)
  // } else {
  //   console.log(222)
  //   next()
  // }
})

let isOpen = false
router.onError(error => {
  if (error instanceof Error) {
    const isChunkLoadFailed = error.name.indexOf('chunk')
    const targetPath = router.currentRoute.value.fullPath
    if (isChunkLoadFailed && !isOpen) {
      isOpen = true
      Dialog.alert({
        title: '更新提示',
        message: 'APP有更新请点击确定刷新页面?',
        confirmButtonColor: 'var(--van-primary)'
      }).then(() => {
        // on close
        if (browser().isApp) {
          postMessage({ api: 'back' })
        } else {
          location.hash = targetPath
          window.location.reload()
        }
      })
    }
  }
})

export default router
