import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/home'
    },
    {
      path: '/home',
      name: 'Home',
      component: () => import('@/views/Home.vue')
    },
    {
      path: '/automate',
      name: 'Automate',
      component: () => import('@/views/Automate.vue')
    },
    {
      path: '/project-info/:id',
      name: 'ProjectInfo',
      component: () => import('@/views/ProjectInfo.vue')
    },
    {
      path: '/command-info/:pid/:id',
      name: 'CommandInfo',
      component: () => import('@/views/CommandInfo.vue')
    }
  ]
})

const getWxConfig = (url: string) => {
  fetch('https://plceditor.worldflying.cn/api/build/getjsconfig', {
    method: 'POST',
    body: JSON.stringify({ url })
  })
    .then((res) => res.json())
    .then((res) => {
      if (res.errcode === 0) {
        localStorage.setItem(url, JSON.stringify(res.data))
        // wx.config(res.data)
        // wx.ready(function () {
        //   console.log('微信初始化成功')
        // })
        // wx.error(function (res: any) {
        //   console.log('微信初始化失败', res)
        // })
      } else {
        showFailToast('获取配置信息失败!')
      }
    })
}

router.beforeEach((to, from, next) => {
  if (!window.isInWx) {
    next()
    return
  }
  const url = location.origin + location.pathname + location.search
  // console.log(url)
  const wxConfigStr = localStorage.getItem(url)
  if (!wxConfigStr) getWxConfig(url)
  else {
    const wxConfig = JSON.parse(wxConfigStr)
    const crtTimestamp = Date.now() / 1000 - 10 * 60
    if (crtTimestamp > wxConfig.timestamp) getWxConfig(url)
  }

  next()
})

export default router
