<template>
  <div class="common-layout">
    <el-container>
      <el-header v-if="state.showMenu">INNcom 清单生成器</el-header>
      <el-main><router-view /></el-main>
    </el-container>
  </div>
</template>
<script>
import { onUnmounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { pathMap, localGet } from '@/utils';
export default {
  name: 'App',
  setup() {
    const noMenu = ['/login']
    const router = useRouter();
    const state = reactive({
      showMenu: true,
      currentPath: '/dashboard'
    })
    // 监听浏览器原生回退事件
    if (window.history && window.history.pushState) {
      history.pushState(null, null, document.URL);
      window.addEventListener('popstate', () => {
        if (!localGet('token')) {
          state.showMenu = false
        }
      }, false);
    }
    const unwatch = router.beforeEach((to, from, next) => {
      if (to.path == '/login') {
        // 如果路径是 /login 则正常执行
        next()
      } else {
        // 如果不是 /login，判断是否有 token
        if (!localGet('token')) {
          // 如果没有，则跳至登录页面
          next({ path: '/login' })
        } else {
          // 否则继续执行
          next()
        }
      }
      state.showMenu = !noMenu.includes(to.path)
      state.currentPath = to.path
      document.title = pathMap[to.name]
    })

    onUnmounted(() => {
      unwatch();
    })

    return {
      state
    }
  }
}
</script>

<style scoped>
.logo {
  height: 6em;
  padding: 1.5em;
  will-change: filter;
  transition: filter 300ms;
}

.logo:hover {
  filter: drop-shadow(0 0 2em #646cffaa);
}

.logo.vue:hover {
  filter: drop-shadow(0 0 2em #42b883aa);
}
</style>
