import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

// 解决ElementUi导航栏中的vue-router在3.0版本以上重复点菜单报错问题
const originalPush = Router.prototype.push

Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const router = new Router({
  routes: [
    {
      path: '/',
      // name: 'home',
      component: () => import('../views/home.vue'),
      title: '一键发单',
      icon: '/static/image/order-icon.png',
      children: [
        {
          path: '/',
          name: 'HomeIndex',
          title: '订单列表',
          component: () => import('../components/Home.vue')
        },
        {
          path: '/orderSearch',
          name: 'orderSearch',
          title: '订单查询',
          component: () => import('../components/orderSearch.vue')
        },
        {
          path: '/setUp/set',
          name: 'set',
          title: '外卖设置',
          component: () => import('../components/set.vue')
        },
        {
          path: '/setUp/addressManagement',
          name: 'addressManagement',
          title: '常用地址',
          component: () => import('../components/addressManagement.vue')
        },
        {
          path: '/setUp/pictureManagement',
          name: 'pictureManagement',
          title: '图片管理',
          component: () => import('../components/pictureManagement.vue')
        },
        {
          path: '/shopInfo/shopInfos',
          name: 'shopInfos',
          title: '门店管理',
          component: () => import('../components/shopInfo.vue')
        },
        {
          path: '/shopInfo/shopAccount',
          name: 'shopAccount',
          title: '我的账户',
          component: () => import('../components/shopAccount.vue')
        },
        {
          path: '/manualCreate',
          name: 'manualCreate',
          title: '手动发单',
          component: () => import('../components/manualCreate.vue')
        },
        {
          path: '/help',
          name: 'help',
          title: '帮助中心',
          component: () => import('../components/help.vue')
        },
        {
          path: '/about',
          name: 'about',
          title: '关于我们',
          component: () => import('../components/about.vue')
        },

      ]
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/login.vue'),
      title: '登录',
      authority: false
    },
    {
      path: '/resetPassword',
      name: 'resetPassword',
      component: () => import('../views/resetPassword.vue'),
      title: '重置密码',
      authority: false
    }
  ]
})

router.beforeEach((to, from, next) => {
  if (to.path === '/login') {
    localStorage.clear()
    next()
  } else {
    const token = localStorage.getItem('token') || null;
    console.log('这是一个token:',token);
    if (token) {
      next()
    } else if (to.path !== '/resetPassword') {
      router.push('/login')
    } else {
      next()
    }
  }
})

export default router
