import Vue from 'vue'
import store from "@/store"
import Cookie from '../util/cookie'
import common from '../util/common'
import Router from 'vue-router'
import index from '@/components/index'
import buyDetail from '@/components/buy/index'
import buy from '@/components/buy/buy'
import success from '@/components/buy/success'
import author from'@/components/author'

Vue.use(Router);

const router =new Router({
  routes: [
    {
      path: '/',
      name: 'index',
      component: index
    }, {
      path: '/author',
      name: 'author',
      component: author
    },{
      path: '/buyDetail',
      name: 'buyDetail',
      component: buyDetail,
      meta:{
        skip_login:true
      }
    }, {
      path: '/buy',
      name: 'buy',
      component: buy
    }, {
      path: '/success',
      name: 'success',
      component: success
    }
  ]
});


router.beforeEach((to,from,next)=> {
  let goOn=function(){
    if(localStorage.getItem('retUrl') && localStorage.getItem('retUrl') !== null && localStorage.getItem('retUrl') !== ''){
      let retUrl = localStorage.getItem('retUrl').toString();
      localStorage.removeItem('retUrl');
      next(retUrl);
    }else{
      next()
    }
  };
  if(to.name === 'author'){
    next()
  }else if(window.location.href.indexOf('token')>-1){
    let token = common.getUrlParam().token;
    store.dispatch('setToken',token);
    goOn()
    // 通过cookie获取token
  }else if(localStorage.getItem('cc_token')) {
    store.dispatch('setToken', localStorage.getItem('cc_token'));
    goOn()
    // 无需token登录页面
  }else if(to.meta.skip_login){
    goOn()
  }else{
    next({name:'author',query:{retUrl:to.fullPath}})
  }

  // if(to.meta.skip_login){
  //   next();
  // }
});

export default router;
