import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/store/user'

// 路由配置
const routes = [
  {
    path: '/',
    redirect: '/dashboard'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: {
      title: '登录',
      requiresAuth: false
    }
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('@/views/Dashboard.vue'),
    meta: {
      title: '仪表板',
      requiresAuth: true
    }
  },
  {
    path: '/users',
    name: 'Users',
    component: () => import('@/views/Users.vue'),
    meta: {
      title: '用户管理',
      requiresAuth: true
    }
  },
  {
    path: '/roles',
    name: 'Roles',
    component: () => import('@/views/Roles.vue'),
    meta: {
      title: '角色管理',
      requiresAuth: true
    }
  },
  {
    path: '/organizations',
    name: 'Organizations',
    component: () => import('@/views/Organizations.vue'),
    meta: {
      title: '组织管理',
      requiresAuth: true
    }
  },
  {
    path: '/dictionaries',
    name: 'Dictionaries',
    component: () => import('@/views/Dictionaries.vue'),
    meta: {
      title: '字典管理',
      requiresAuth: true
    }
  },
  {
    path: '/FormCreateDesigner',
    name: 'FormCreateDesigner',
    component: () => import('@/views/FormCreateDesigner.vue'),
    meta: {
      title: '字典管理',
      requiresAuth: true
    }
  },
  {
    path: '/:pathMatch(.*)*',
    name: '404',
    component: () => import('@/views/error-page/404.vue'),
    meta: {
      title: '页面未找到',
      requiresAuth: false
    }
  }
]

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

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - StdProject` : 'StdProject'
  
  // 检查是否需要认证
  if (to.meta.requiresAuth) {
    if (userStore.isAuthenticated) {
      next()
    } else {
      next('/login')
    }
  } else {
    // 如果已登录且访问登录页，重定向到仪表板
    if (to.path === '/login' && userStore.isAuthenticated) {
      next('/dashboard')
    } else {
      next()
    }
  }
})

export default router