import Vue from 'vue'
import VueRouter from 'vue-router'
import {menu} from '@/configue/menu'
import { LoginDetector } from "@/util/listener";


Vue.use(VueRouter);
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};

LoginDetector.register(
  detector => new Promise(resolve => detector.resolve(resolve))
);

Vue.use(VueRouter)

let routes = [
  {
    path: "/",
    name: "Layout",
    component: () => import( "../pages/layout/index.vue"),
    children:[{
      path:'/',
      redirect:'/museum/detail'
    }]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import( "../pages/login/")
  }
]

menu.forEach(item => {
  item.routes.forEach(sub=>{
    routes[0].children.push({
        name: sub.key,
        path: `/${sub.key}${sub.param?`/:${sub.param.map(tt=>tt.key).join('/:')}`:''}`,
        meta: {
          index: sub.key,
          belong: item.id,
          name:sub.name,
          type:sub.type
        },
        component: () => import(`../pages/${item.key}/${sub.key}/index.vue`)
    })

    //编辑页路由
    if (!sub.noEdit) {
      routes[0].children.push({
        name: `edit-${sub.key}`,
        path: `/edit-${sub.key}${sub.editParam?`/:${sub.editParam.map(tt=>tt.key).join('/:')}`:''}`,
        meta: {
          index: sub.key,
          belong: item.id,
          name:sub.name,
          type:sub.type
        },
        component: () => import(`../pages/${item.key}/${sub.key}/edit.vue`)
    })
    }
  })
})


if (localStorage.token) {
  LoginDetector.valid();
}



const router = new VueRouter({
  routes
})

router.beforeEach(async (to, from, next) => {
  if (to.path === '/login') {
    next();
  } else {
    let token = localStorage.getItem('token');
 
    if (token === null || token === '') {
      next('/login');
    } else {
      next();
    }
  }
})
export default router
