import { createRouter, createWebHistory } from 'vue-router'
import Main from '../views/Main.vue'
import BasicMessage from '../views/BasicMessage.vue'
import Login from '../views/Login.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'login',
      component: Login
    },
    {
      path: '/main',
      name: 'main',
      redirect: '/basic-message',
      component: Main,
      children: [
        {
          path: '/basic-message',
          name: 'basic',
          component: BasicMessage
        }
      ]
    }
  ]
})

router.beforeEach((to, from, next) => {
  if (to.name !== 'login') {
    let loginAck = localStorage.getItem(window.location.host)
    if (loginAck) {
      let ack = JSON.parse(loginAck)
      let {code, msg} = ack || {}
      if (code == 0) {
        next()
      } else {
        Message.error(msg)
        next({
          name: 'login'
        })
      }
    } else {
      next({
        name: 'login'
      })
    }
  } else {
    next()
  }
})

export default router
