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

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


const whiteList = ['/autoLogin','/login','/login/2','/notfound','/regist','/','/forgot','/newpass','/notsupported','/denyAccess']
const managerMenu = ['/market','/editor_admin']

let loadingInstance:any = null 
router.beforeEach((to:any, from:any, next:any) => {

  const md = new MobileDetect(window.navigator.userAgent);
  const isMobile = md.mobile() !== null || md.tablet() !== null;
  if (isMobile && !to.path.includes('/notsupported')) {
    // 如果是移动设备，并且访问的不是重定向页面，则重定向到 /mobile-redirect
    next('/notsupported');
  }

  const user = useUserStore()
  if(!loadingInstance){
    loadingInstance = ElLoading.service({
      fullscreen:true,
      lock:true
    })
  }
  
  const path = `/${to.path.split('/')[1]}`
  if(useUserStore().getDenied && path!='/denyAccess') next('/denyAccess')
  else if(!useUserStore().getDenied && path=='/denyAccess') next('/space')
  else if ((whiteList.includes(path) || user.getUserToken!='' || to.path.includes('/j/')) && !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