import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'

// 1. 引入页面组件
import Login from '../views/Login.vue'
import Dashboard from '../views/Dashboard.vue'
// 新增：引入用户管理页面 (确保你在 views 目录下创建了 UserManagement.vue)
import UserManagement from '../views/UserManagement.vue'

const routes = [
    {
        path: '/',
        name: 'Login',
        component: Login,
        meta: { title: '系统登录' }
    },
    {
        path: '/dashboard',
        name: 'Dashboard',
        component: Dashboard,
        meta: { title: '设备监控总览', requiresAuth: true }
    },
    // 新增：用户管理路由
    {
        path: '/user-management',
        name: 'UserManagement',
        component: UserManagement,
        meta: { title: '客户权限管理', requiresAuth: true }
    },
    {
        path: '/data-monitor',
        name: 'CrawledData',
        // 路由懒加载
        component: () => import('../views/DataMonitor.vue'),
        meta: { title: '数据爬取监控', requiresAuth: true }
    },
    {
        path: '/logs',
        name: 'MaintenanceLogs',
        component: () => import('../views/MaintenanceLogs.vue'),
        meta: { title: '维修日志中心', requiresAuth: true }
    },
    // 捕获所有未定义的路径，跳转回登录页
    {
        path: '/:pathMatch(.*)*',
        redirect: '/'
    }
]

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

// =======================
// 核心：全局路由守卫
// =======================
router.beforeEach((to, from, next) => {
    // 1. 设置页面标题
    if (to.meta.title) {
        document.title = to.meta.title
    }

    // 2. 检查登录状态 (从本地存储获取)
    const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'

    // 3. 鉴权逻辑
    if (to.meta.requiresAuth && !isLoggedIn) {
        // 如果页面需要登录但用户未登录，强行拦截并跳转到登录页
        ElMessage.error('请先登录系统')
        next({ name: 'Login' })
    } else if (to.name === 'Login' && isLoggedIn) {
        // 如果用户已登录却尝试访问登录页，直接送他去首页
        next({ name: 'Dashboard' })
    } else {
        // 否则正常放行
        next()
    }
})

export default router
