import { createRouter, createWebHistory } from 'vue-router'
import routes from './router'
import { useUserStore } from '@/store/user';
import { ElLoading } from 'element-plus';

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})


const whiteList = ['/autoLogin','/login','/notfound','/regist','/']
const managerMenu = ['/market','/editor_admin']

let loadingInstance:any = null 
router.beforeEach((to:any, from:any, next:any) => {
  const user = useUserStore()
  if(!loadingInstance){
    loadingInstance = ElLoading.service({
      fullscreen:true,
      lock:true
    })
  }
  if ((whiteList.includes(to.path) || user.getUserToken!='') && !to.query.uid) {
    if(managerMenu.includes(to.path) && user.getUser.isTemplate!=1){
      next('/notfound');
    }
    if(to.path.includes('/regist') && user.getUserToken!=''){
      next('/login');
    }
    if (to.meta.title) {
      document.title = to.meta.title
    }
    next();
  } else {
    
    if(to.query && to.query.uid){
      next(`/autoLogin?forword=${encodeURIComponent(to.fullPath)}`)
    } else if(user.getUserToken=='') {
      next(`/login`)
    }
    next('/notfound');
  }
});

router.afterEach(() => {
  if (loadingInstance) {
    loadingInstance.close()
    loadingInstance = null
  }
});

export default router