import Vue from 'vue'
import store from "@/store"
import Router from 'vue-router'
import Cookie from '../util/cookie'

import index from '@/components/framework'
import main from '@/components/main'
import login from '@/components/login'
import resources from '@/components/resources'
import system from '@/components/system/index'
import admin from '@/components/system/admin'
import role from '@/components/system/role'
import user from '@/components/user'
import teacher from '@/components/teacher'
Vue.use(Router)

const router =new Router({
  routes: [
    {
      path:'/login',
      name:'login',
      component:login,
      meta:{
        skip_auth:true,
      }
    },
    {
      path: '/',
      name: 'index',
      component: index,
      redirect:{name:'first'},
      children:[
        {
          path: '',
          name:'first',
          component: main
        },{
          path: '/resources',
          name:'resources',
          component: resources
        },{
          path: '/user',
          name:'user',
          component: user
        },{
          path: '/teacher',
          name:'teacher',
          component: teacher
        },{
          path:'/system',
          name:'system',
          component:system ,
          redirect:{name:'admin'},
          children:[
            {
              path: '',
              redirect:{name:'admin'}
            },
            {
              path: 'admin',
              name:'admin',
              component: admin
            },
            {
              path: 'role',
              name:'role',
              component: role
            },
          ]
        }
      ]
    }
  ]
});
router.beforeEach((to,from,next)=> {
  //在已登录状态下不允许退回登录页面去
  // if (to.name === 'login' && store.state.token) {
  //   next(false);
  //   return;
  // }
  //获取cookie里的token
  if(Cookie.get('cc_token')){
    store.dispatch('setToken',Cookie.get('cc_token'));
    if(Cookie.get('cc_user_name') !== null){
      store.dispatch('setUserName',Cookie.get('cc_user_name'))
    }else{
    }
  }
  if(to.name !== 'first'){
  let thisMenu = store.state.menuList.find((i)=>{return i.routerName === to.name});
  if(to.name === 'role'){
    store.state.nowTab = 'admin'
  }else{
    store.state.nowTab = to.name
  }
  if(store.state.openedTab.indexOf(thisMenu) < 0){
    store.state.openedTab.push(thisMenu);
  }
  }
  // 登录拦截
  if (to.matched.some(record => record.meta.skip_auth !== true) && !store.state.token) {
    next({
      path: '/login'
    })
  } else {
    next()
  }
});

  export default router;
