import store from "@/store"
import Router from 'vue-router'
import Cookie from '../util/cookie'
const router =new Router({
  routes: [
    {
      path: '/',
      name: 'index',
      component: e=>require(['@/components/framework'],e),
      redirect:{name:'first'},
      children:[
        {
          path: '',
          name:'first',
          component: e=>require(['@/components/main'],e),
        },

      ]
    },
    {
      path:'/login',
      name:'login',
      component: e=>require(['@/components/login'],e),
      meta:{
        skip_auth:true,
      }
    },
    {
      path:'/outManager',
      name:'outManager',
      component: e=>require(['@/components/promotion'],e),
      meta:{
        skip_auth:true,
      }
    },
    {
      path:'/preview/:id',
      name:'preview',
      component: e=>require(['@/components/preview'],e),
      meta:{
      }
    },
    {
      path:'/upload',
      name:'upload',
      component: e=>require(['@/components/framework/upload'],e),
      meta:{
        skip_auth:true,
      }
    }
  ]
});
router.beforeEach((to,from,next)=> {
  store.commit('mainCanShow');
  if(Cookie.get('cc_token')){
    store.dispatch('setToken',Cookie.get('cc_token'));
    store.dispatch('setPermission',JSON.parse(localStorage.getItem('permission')));
    if(Cookie.get('cc_user_name') !== null){
      store.dispatch('setUserName',Cookie.get('cc_user_name'))
    }else{
    }
  }
  store.state.nowTab = to.name;
  if(to.matched.length > 1 && to.name !== 'first'){
    let thisMenu;
    for (let i = 0 ; i < store.state.menuList.length ; i ++ ){
      let _this = store.state.menuList[i];
      for (let j = 0 ; j < _this.list.length ; j++){
        let _that = _this.list[j];
        if (_that.path === to.path){
          thisMenu = _that
        }
      }
    }
    if(store.state.openedTab.indexOf(thisMenu) < 0){
      store.state.openedTab.push(thisMenu);
    }
  }

  if(to.meta.readonly){
    store.dispatch('readonly',true)
  }else{
    store.dispatch('readonly',false)
  }

  if(to.name==='userDetail'){
    let list = JSON.parse(localStorage.getItem('permission'))
    let readonly = list.find(i=>{
      return i.cover === '3-2'
    }).readonly;
    store.dispatch('readonly',readonly)
  }
  if(to.meta.delete){
    store.dispatch('deletePermission',true)
  }else {
    store.dispatch('deletePermission',false)
  }
  // 登录拦截
  if (to.matched.some(record => record.meta.skip_auth !== true) && !store.state.token) {
    next({
      path: '/login'
    })
  } else {
    next()
  }
});
router.onError((error) => {
  const pattern = /Loading chunk (\d)+ failed/g;
  const isChunkLoadFailed = error.message.match(pattern);
  const targetPath = router.history.pending.fullPath;
  if (isChunkLoadFailed) {
    router.replace(targetPath);
  }
});
export default router;
