import { createRouter, createWebHashHistory } from 'vue-router';
import layout from '@/layout/index.vue';
import { useUserStore } from '@/store/user.js';


const routes = [
  {
    path: '/',
    name: 'layout',
    component: layout,
    redirect: '/saleHome',
    meta: { title: '里海收银系统' },
    children: [
      {
        path: '/home',
        name: 'home',
        meta: { title: '收银' },
        component: () => import('@/views/home/index.vue'),
      },
      {
        path: '/order',
        name: 'order',
        meta: { title: '收银订单' },
        component: () => import('@/views/order/index.vue'),
      },
      {
        path: '/orderSystem',
        name: 'orderSystem',
        meta: { title: '平台订单' },
        component: () => import('@/views/order/indexSystem.vue'),
      },
      {
        path: '/saleHome',
        name: 'saleHome',
        meta: { title: '批发' },
        component: () => import('@/views/saleHome/index.vue'),
      },
      {
        path: '/saleOrder',
        name: 'saleOrder',
        meta: { title: '批发订单' },
        component: () => import('@/views/saleOrder/index.vue'),
      },
      {
        path: '/orderList',
        name: 'orderList',
        meta: { title: '统计' },
        component: () => import('@/views/order/indexList.vue'),
      },
      {
        path: '/orderCount',
        name: 'orderCount',
        meta: { title: '统计' },
        component: () => import('@/views/order/indexCount.vue'),
      },
      {
        path: '/shop',
        name: 'shop',
        component: () => import('@/views/shop/index.vue'),
      },
      {
        path: '/convert',
        name: 'convert',
        component: () => import('@/views/convert/index.vue'),
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index.vue'),
  },
  // 注意：通配符路由要放在最后
  {
    path: '/:catchAll(.*)',
    name: 'notFound',
    component: () => import('@/views/notFound/index.vue') // 使用 404 页面组件
  }
];

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

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore();

  // 如果用户访问的不是登录页面，并且未登录，则重定向到登录页面
  if (to.name !== 'login' && !userStore.Token) {
    next({ name: 'login' });
  } else {
    next(); // 放行
  }
});

export default router;