<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>后台管理系统</title>

    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">

    <link rel="stylesheet" href="/assets/css/main.css">
</head>
<body>
<div id="app">
    <!-- 侧边栏 -->
    <nav class="sidebar">
        <div class="sidebar-header">
            <h4>
                <i class="bi bi-shield-lock-fill"></i>
                CoreWing
            </h4>
        </div>

        <div class="sidebar-menu">
            <ul class="nav flex-column">
                <li class="nav-item">
                    <a :class="['nav-link', currentUrl === '/admin/dashboard' ? 'active' : '']"
                       href="#"
                       @click.prevent="changeMenu('/admin/dashboard')">
                        <i class="bi bi-speedometer2"></i>
                        仪表盘
                    </a>
                </li>
                <li class="nav-item" v-for="(item, index) in menus" :key="index">
                    <a :class="['nav-link', currentUrl === item.menuUrl ? 'active' : '']"
                       href="#"
                       @click.prevent="changeMenu(item.menuUrl)">
                        <i :class="item.menuIcon"></i>
                        {{ item.menuName }}
                    </a>
                </li>
            </ul>
        </div>

        <div class="sidebar-footer">
            <button class="btn-logout"  data-bs-toggle="modal" data-bs-target="#exitModal">
                <i class="bi bi-box-arrow-right me-2"></i>
                退出登录
            </button>
        </div>
    </nav>

    <!-- 主内容区 -->
    <main class="main-content">
        <!-- 顶部导航栏 -->
        <nav class="navbar navbar-expand-lg navbar-light">
            <div class="container-fluid">
                <span class="navbar-brand">欢迎回来</span>
                <div class="user-info" style="cursor: pointer">
                    <i class="bi bi-person-circle"></i>
                    <span>{{ userInfo.realName || userInfo.username }}</span>
                </div>
            </div>
        </nav>

        <!-- 内容区域 -->
        <div class="content-wrapper">
            <!-- iframe容器 - 用于加载菜单对应的URL页面 -->
            <iframe
                    v-if="currentUrl"
                    class="page-iframe"
                    :src="currentUrl"
                    @load="handleIframeLoad"
                    title="页面内容"
            ></iframe>
        </div>
    </main>


    <div class="modal fade" id="exitModal" tabindex="-1" aria-labelledby="exitModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h1 class="modal-title fs-5" id="exampleModalLabel">系统提示</h1>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    您确认退出系统吗？
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" @click="handleLogout">退出</button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Vue 3 -->
<script src="https://cdn.jsdelivr.net/npm/vue@3.3.4/dist/vue.global.prod.js"></script>

<!-- Axios -->
<script src="https://cdn.jsdelivr.net/npm/axios@1.4.0/dist/axios.min.js"></script>

<!-- Bootstrap 5 JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<!-- 引入封装的 axiosRequest.js -->
<script src="/assets/js/axiosRequest.js"></script>


<script>
    const {createApp} = Vue;

    createApp({
        data() {
            return {
                userInfo: {
                    username: '',
                    realName: '',
                    userId: ''
                },
                menus: [],
                currentUrl: '/admin/dashboard',  // 当前加载的URL
                isLoading: false // 加载状态
            }
        },
        methods: {
            async loadUserInfo() {
                // 从 localStorage 获取用户信息
                this.userInfo.username = localStorage.getItem('username') || '';
                this.userInfo.realName = localStorage.getItem('realName') || '';
                this.userInfo.userId = localStorage.getItem('userId') || '';
                const token = localStorage.getItem("token");
                if (token) {
                    try {
                        const response = await request.get('/sys/user/info');
                        if (response.code === 200) {
                            const user = response.data;
                            this.userInfo.username = user.username;
                            this.userInfo.realName = user.realName || user.username;
                            this.userInfo.userId = user.id;
                        }
                    } catch (error) {
                        console.error('获取用户信息失败:', error);
                    }
                }
            },

            async handleLogout() {
                try {
                    await request.get('/sys/user/logout');
                } catch (error) {
                    console.error('退出登录失败:', error);
                } finally {
                    // 清除本地存储
                    localStorage.clear();
                    // 跳转到登录页
                    window.location.href = '/admin/login.html';
                }
            },

            checkLogin() {
                const token = localStorage.getItem('token');
                if (!token) {
                    // 未登录，跳转到登录页
                    window.location.href = '/admin/login.html';
                }
            },

            async initMenu() {
                const response = await request.get('/sys/menu/initSysMenu');
                if (response.code === 200) {
                    this.menus = response.data;
                }
                this.initCurrentUrlFromHash();
            },
            // 从浏览器hash初始化当前URL
            initCurrentUrlFromHash() {
                const hash = window.location.hash.slice(1); // 获取 # 后的内容（如 #/admin/user 取 /admin/user）
                // 如果hash存在且是有效菜单URL，用hash；否则用默认的仪表盘
                const validMenuUrls = this.menus.map(item => item.menuUrl);
                if (hash && (validMenuUrls.includes(hash) || hash === '/admin/dashboard')) {
                    this.currentUrl = hash;
                } else {
                    this.currentUrl = '/admin/dashboard';
                    // 同步默认值到地址栏
                    window.location.hash = this.currentUrl;
                }
            },

            // 切换菜单时更新URL和状态
            changeMenu(menuUrl) {
                this.currentUrl = menuUrl;
                this.isLoading = true;
                window.location.hash = menuUrl;
            },
            handleIframeLoad() {
                console.log('加载完成');
                this.isLoading = false;
            }
        },
        mounted() {
            // 检查登录状态
            this.checkLogin();
            // 加载系统菜单
            this.initMenu();
            // 加载用户信息
            this.loadUserInfo();
            this.isLoading = true;
            // 监听浏览器hash变化（刷新/前进后退时触发）
            window.addEventListener('hashchange', () => {
                this.initCurrentUrlFromHash();
            });
        }
    }).mount('#app');
</script>
</body>
</html>
