import { createRouter, createWebHashHistory } from 'vue-router'
import LoginView from '@/views/login'
import ViewLayout from '@/view/layout'
import Shop from '@/views/shop'
import Category from '@/views/category'
import Brand from '@/views/brand'
import Scene from '@/views/scene'
import Log from '@/views/log'
import Openvideo from '@/views/openvideo'
import Framework from '@/views/framework'
import User from '@/views/user'
import Hotspot from '@/views/hotspot'
import navs from '@/state/navs'
// import FirmwareView from '@/view/firmware'

const routes = [
  {
    name: 'login',
    path: '/login',
    component: LoginView,
    meta: { title: '登錄' }
  },
  {
    name: 'viewLayout',
    path: '/',
    component: ViewLayout,
    meta: { title: 'VR看店管理' },
    children: [
      {
        name: 'scene',
        path: 'scene',
        meta: { title: '場景管理', checkAuth: true },
        component: Scene,
      },
      {
        name: 'shop',
        path: 'shop',
        meta: { title: '店鋪管理', checkAuth: true },
        component: Shop,
      },
      {
        name: 'category',
        path: 'category',
        meta: { title: '店鋪分類', checkAuth: true },
        component: Category,
      },
      {
        name: 'brand',
        path: 'brand',
        meta: { title: '品牌信息', checkAuth: true },
        component: Brand,
      },
      {
        name: 'hotspot',
        path: 'hotspot',
        meta: { title: '热点设置', checkAuth: true },
        component: Hotspot,
      },
      {
        name: 'openvideo',
        path: 'openvideo',
        meta: { title: '開場視頻', checkAuth: true },
        component: Openvideo,
      },
      {
        name: 'framework',
        path: 'framework',
        meta: { title: '組織架構', checkAuth: true },
        component: Framework,
      },
      {
        name: 'user',
        path: 'user',
        meta: { title: '用戶管理', checkAuth: true },
        component: User,
      },
      {
        name: 'log',
        path: 'log',
        meta: { title: '操作日誌', checkAuth: true },
        component: Log,
      }
      
    ]
  }
]

const router = createRouter({ 
  history: createWebHashHistory(),
  routes,
})

const isVisual = (navs, name) => 
  {
    return navs.some(item => 
      item.name === name || 
      (item.children && isVisual(item.children, name))
    )
  }

router.beforeEach(async (to, from, next) => {
  console.log(navs,'navs');
  if (!to.name || to.name === 'viewLayout') {
    router.replace({name: 'scene'})
    return;
  }

  if (to.meta && to.meta.checkAuth) {
    console.log(!navs.value);
    while(!navs.value || navs.value.length === 0) {
      await new Promise(r => setTimeout(r, 100))
    }
    
    if (!isVisual(navs.value, to.name)) {
      isVisual(navs.value, 'scene') ? router.replace({name: 'scene'}): router.replace({name: 'login'})
      return;
    }
  }
  next()
})

export const config = routes
export default router
