<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>CMSPRO v{{ system_version() }}</title>
    <link rel="stylesheet" href="{{ asset('CmsProUi/component/pear/css/pear.css') }}">
    <link rel="stylesheet" href="{{ asset('CmsProUi/font-awesome/4.7.0/css/font-awesome.min.css') }}">
    <link rel="stylesheet" href="{{ asset('Admin/css/admin.dark.css') }}">
    <link rel="stylesheet" href="{{ asset('Admin/css/admin.css') }}">
    <link rel="stylesheet" href="{{ asset('Admin/css/variables.css') }}">
    <link rel="stylesheet" href="{{ asset('Admin/css/reset.css') }}">
    @stack('page_styles')
    <style>
        .pear-admin .layui-footer {
            text-align: center;
            display: block;
        }
        .layui-footer a:not(.layui-btn) {
            color: #16b777;
            padding: 0px 2px 0px 2px;
        }
        .layui-tab .layui-tab-title {
            border-bottom-style: inset;
        }

        #sideMenu .pear-nav-tree .layui-nav-child {
            display: none;
        }
        #sideMenu .pear-nav-tree .layui-nav-itemed > .layui-nav-child,
        #sideMenu .pear-nav-tree dd.layui-nav-itemed > .layui-nav-child {
            display: block !important;
            height: auto !important;
            overflow: visible !important;
        }
        .layui-body {
            overflow-y: auto;
        }
        .layui-body .pear-container {
            padding: 20px;
        }
        /* 系统升级提示 — 右下角浮动按钮 */
        .upgrade-float-btn {
            position: fixed;
            right: 24px;
            bottom: 24px;
            z-index: 9999;
            display: none;
            align-items: center;
            padding: 10px 18px;
            padding-right: 34px;
            background: linear-gradient(135deg, #ff6b6b, #ee5a24);
            color: #fff;
            font-size: 13px;
            border-radius: 24px;
            cursor: pointer;
            text-decoration: none;
            box-shadow: 0 4px 12px rgba(238, 90, 36, 0.35);
            animation: upgradePulse 2s ease-in-out infinite;
            transition: transform 0.2s, opacity 0.2s;
        }
        .upgrade-float-btn:hover {
            transform: scale(1.05);
            opacity: 0.9;
        }
        .upgrade-float-btn .layui-icon {
            font-size: 16px;
            margin-right: 5px;
        }
        .upgrade-float-close {
            position: absolute;
            right: 8px;
            top: 50%;
            transform: translateY(-50%);
            width: 18px;
            height: 18px;
            line-height: 18px;
            text-align: center;
            font-size: 12px;
            border-radius: 50%;
            background: rgba(255,255,255,0.3);
            color: #fff;
            cursor: pointer;
            transition: background 0.2s;
        }
        .upgrade-float-close:hover {
            background: rgba(255,255,255,0.6);
        }
        @keyframes upgradePulse {
            0%, 100% { box-shadow: 0 4px 12px rgba(238, 90, 36, 0.35); }
            50% { box-shadow: 0 4px 20px rgba(238, 90, 36, 0.6); }
        }
    </style>
</head>
<body class="layui-layout-body pear-admin">
    <div class="layui-layout layui-layout-admin">
        <div class="layui-header">
            <div class="layui-logo">
                <img class="logo">
                <span class="title"></span>
            </div>
            <ul class="layui-nav layui-layout-left">
                <li class="collapse layui-nav-item"><a href="#" class="layui-icon layui-icon-shrink-right"></a></li>
                <li class="refresh layui-nav-item"><a href="#" class="layui-icon layui-icon-refresh-1" loading=600></a></li>
            </ul>
            <div id="control" class="layui-layout-control"></div>
            <ul class="layui-nav layui-layout-right">
                <li class="layui-nav-item layui-hide-xs"><a href="{{ url('/') }}" class="layui-icon layui-icon-website" target="_blank"></a></li>
                @auth
                <li class="layui-nav-item user">
                    <a class="layui-icon layui-icon-username" href="javascript:;"> {{ auth()->user()->name }}</a>
                    <dl class="layui-nav-child" style="width: 160px;">
                        <dd style="height: 90px; padding: 5px;">
                            <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);">
                                <a user-menu-type="_iframe" user-menu-url="{{ url('/admin/account') }}" user-menu-id="10006" user-menu-title="我的账号">
                                    <img src="{{ auth()->user()->avatar ?? asset('Admin/images/avatar.png') }}" style="max-height: 80px; border-radius: 50%;">
                                </a>
                            </div>
                        </dd>
                        <dd><hr></dd>
                        <dd><a user-menu-type="_iframe" user-menu-url="{{ url('/admin/account') }}" user-menu-id="10006" user-menu-title="账号管理">账号管理</a></dd>
                        <dd><a href="javascript:void(0);" class="SetPassword">修改密码</a></dd>
                        <dd><a href="javascript:void(0);" class="ClearFrontendCache">清理前端缓存</a></dd>
                        <dd><a href="javascript:void(0);" class="ClearBackendCache">清理后端缓存</a></dd>
                        <dd><a href="javascript:void(0);" class="logout">注销登录</a></dd>
                    </dl>
                </li>
                @endauth
                <li class="layui-nav-item layui-hide-xs"><a href="#" class="fullScreen layui-icon layui-icon-screen-full"></a></li>
                <li class="layui-nav-item setting"><a href="#" class="layui-icon layui-icon-more-vertical"></a></li>
            </ul>
        </div>
        <div class="layui-side layui-bg-black">
            <div class="layui-logo">
                <img class="logo">
                <span class="title"></span>
            </div>
            <div class="layui-side-scroll">
                <div id="sideMenu"></div>
            </div>
        </div>
        <div class="layui-body">
            <div id="content">@yield('content')</div>
        </div>
        <div class="layui-footer">
            <a href="http://www.cmspro.cn" target="_blank">CMSPRO</a> v{{ system_version() }} &copy; 2015-{{ date('Y') }} Copyright by <a href="http://www.renhuali.cn" target="_blank">Holley</a>
        </div>
        <div class="pear-cover"></div>
        <div class="loader-wrapper">
            <div class="loader"></div>
        </div>
    </div>
    <div class="pear-collapsed-pe collapse">
        <a href="#" class="layui-icon layui-icon-shrink-right"></a>
    </div>
    <a href="javascript:void(0);" class="upgrade-float-btn" id="upgradeFloatBtn" title="前往版本管理">
        <i class="layui-icon layui-icon-upgrade"></i>
        <span id="upgradeFloatText">新版本可用</span>
        <span class="upgrade-float-close" id="upgradeFloatClose">&times;</span>
    </a>
    <script src="{{ asset('CmsProUi/component/layui/layui.js') }}"></script>
    <script src="{{ asset('CmsProUi/component/pear/pear.js') }}"></script>
    <script>
    // 当前用户权限列表（超管为 ['*']），供子页面按钮权限控制
    window.CMSPRO_PERMISSIONS = @json(auth('admin')->user() ? (auth('admin')->user()->isSuperAdmin() ? ['*'] : auth('admin')->user()->getAllPermissions()) : []);
    window.hasPermission = function(code) {
        if (!code) return true;
        if (window.CMSPRO_PERMISSIONS.indexOf('*') !== -1) return true;
        return window.CMSPRO_PERMISSIONS.indexOf(code) !== -1;
    };
    </script>
    <script>
    layui.use(['element', 'toast', 'admin', 'form', 'jquery', 'button', 'popup'], function() {
        var toast = layui.toast;
        var $ = layui.jquery;
        var form = layui.form;
        var button = layui.button;
        var admin = layui.admin;
        var popup = layui.popup;
        var element = layui.element;

        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            }
        });

        $(document).on('click', '.refresh', function(e) {
            e.stopImmediatePropagation();
            if (window.PearAdmin) {
                PearAdmin.refresh();
            } else {
                window.location.reload();
            }
        });

        $(document).on('click', '#sideMenu .site-demo-active', function(e) {
            e.stopImmediatePropagation();
            setTimeout(function() {
                if (window.PearAdmin) {
                    PearAdmin.refresh();
                }
            }, 100);
        });

        $(document).on('click', '[user-menu-id]', function(e) {
            var menuType = $(this).attr('user-menu-type') || $(this).attr('menu-type');
            if (menuType === '0' || menuType === 0) {
                return;
            }
            e.stopImmediatePropagation();
            var menuId = $(this).attr('user-menu-id');
            var type = $(this).attr('user-menu-type');
            var url = $(this).attr('user-menu-url');
            var title = $(this).attr('user-menu-title');
            if (type === '_layer' && url) {
                layer.open({ type: 2, title: title, content: url, area: ['80%', '80%'], maxmin: true });
            } else if (url && window.PearAdmin) {
                PearAdmin.changePage({ id: menuId, title: title, url: url, type: type || '_iframe', close: true });
            } else if (url) {
                window.location.href = url;
            }
        });

        admin.setConfigurationPath("{{ url('/api/admin/config.json') }}");
        localStorage.removeItem('muilt-tab');
        admin.render();

        function highlightCurrentMenu() {
            var currentPath = window.location.pathname;
            if (currentPath === '/admin' || currentPath === '/admin/') {
                currentPath = '/admin/dashboard';
            }
            var $menuLinks = $('#sideMenu .site-demo-active');
            $menuLinks.each(function() {
                var menuUrl = $(this).attr('menu-url');
                if (menuUrl === currentPath) {
                    $(this).closest('li, dd').addClass('layui-this');
                    $(this).parents('.layui-nav-child').each(function() {
                        $(this).css({ display: 'block', height: 'auto', overflow: '' });
                        $(this).parent('li, dd').addClass('layui-nav-itemed');
                    });
                    var $parentUl = $(this).closest('ul[pear-id]');
                    if ($parentUl.length) {
                        var pearId = $parentUl.attr('pear-id');
                        $('#sideMenu .pear-nav-tree').css({ display: 'none' });
                        $parentUl.css({ display: 'block' });
                        $('#control .pear-nav-control').find('.layui-this').removeClass('layui-this');
                        $('#control .pear-nav-control').find('[pear-id="' + pearId + '"]').addClass('layui-this');
                    }
                    return false;
                }
            });
        }

        var menuObserver = new MutationObserver(function(mutations) {
            if ($('#sideMenu .pear-nav-tree').length) {
                menuObserver.disconnect();
                highlightCurrentMenu();
            }
        });
        menuObserver.observe(document.getElementById('sideMenu'), { childList: true, subtree: true });

        setTimeout(function() {
            if ($('#sideMenu .pear-nav-tree').length) {
                highlightCurrentMenu();
            }
        }, 3000);

        admin.logout(function() {
            doLogout();
            popup.success("注销成功", function() {
                location.href = "{{ url('/admin/login') }}";
            });
            return new Promise(function(resolve) { resolve(true); });
        });

        $(".SetPassword").click(function() {
            layer.open({
                type: 2,
                maxmin: false,
                title: "修改密码",
                shade: 0.1,
                area: ['400px', '268px'],
                content: "{{ url('/admin/account/password') }}"
            });
        });

        // 清理前端缓存（浏览器本地缓存，清理后刷新页面）
        $(".ClearFrontendCache").click(function() {
            layui.cache = {};
            sessionStorage.clear();
            localStorage.clear();
            popup.success("前端缓存已清理", function() {
                location.reload();
            });
            return true;
        });

        // 清理后端缓存（服务器端缓存，不刷新页面）
        $(".ClearBackendCache").click(function() {
            $.ajax({
                url: "{{ url('/api/admin/cache/clear') }}",
                type: 'GET',
                dataType: 'json',
                success: function(res) {
                    if (res.code === 0) {
                        popup.success("后端缓存已清理");
                    } else {
                        popup.error(res.message || "清理失败");
                    }
                }
            });
            return true;
        });

        function doLogout() {
            $.ajax({
                url: "{{ url('/api/admin/auth/logout') }}",
                type: 'POST',
                dataType: 'json',
                headers: {
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                }
            });
        }

        // 全局静默检查应用更新（24h 一次，使用 localStorage 节流）
        // 触发场景：用户使用应用时（进入任意后台页面）
        (function() {
            var lastCheck = localStorage.getItem('cmspro_app_update_check_global');
            var now = Date.now();
            if (lastCheck && (now - parseInt(lastCheck)) < 24 * 3600 * 1000) {
                return;
            }
            localStorage.setItem('cmspro_app_update_check_global', now.toString());

            // 静默调用，不弹窗、不显示 loading
            $.ajax({
                url: '/api/admin/apps/check-updates?lazy=1',
                type: 'POST',
                dataType: 'json'
            });
        })();

        // 全局检查系统版本更新（每次进入后台都检测，服务端有缓存不会重复请求远程）
        // 检测到新版本：先弹对话框提示，关闭后右下角常驻升级按钮
        $.ajax({
            url: '{{ url("/admin/versionmgr/api/check") }}',
            type: 'GET',
            dataType: 'json',
            success: function(res) {
                if (res.code === 0 && res.data && res.data.has_update && !res.data.is_skipped) {
                    showUpgradeDialog(res.data);
                }
            },
            error: function() {
                // 应用未安装或接口不可用时静默忽略，不影响后台正常使用
            }
        });

        function showUpgradeDialog(data) {
            var version = data.latest_version || '';
            var current = data.current_version || '';
            layer.open({
                type: 1,
                title: '<i class="layui-icon layui-icon-upgrade" style="color:#ee5a24;margin-right:5px;"></i>发现新版本',
                area: ['420px', 'auto'],
                shade: [0.5, '#000'],
                shadeClose: 0,
                closeBtn: 1,
                content: '<div style="padding:20px;line-height:1.8;">' +
                    '<p style="font-size:15px;">系统检测到新版本 <strong style="color:#ee5a24;">v' + version + '</strong></p>' +
                    '<p style="color:#999;margin-top:6px;">当前版本：v' + current + '</p>' +
                    '</div>',
                btn: ['前往升级', '稍后再说'],
                yes: function(idx) {
                    layer.close(idx);
                    openVersionmgrTab();
                },
                btn2: function() {
                    // 点击"稍后再说"关闭对话框，然后显示右下角常驻按钮
                },
                end: function() {
                    // 对话框关闭后（无论是点按钮还是点X），都显示右下角按钮
                    showUpgradeFloatBtn(version);
                }
            });
        }

        function showUpgradeFloatBtn(version) {
            $('#upgradeFloatText').text('v' + version + ' 可升级');
            $('#upgradeFloatBtn').css('display', 'flex');
        }

        // 在多选项卡中打开版本管理页（与左侧菜单点击效果一致）
        function openVersionmgrTab() {
            var url = '{{ url("/admin/versionmgr") }}';
            if (window.PearAdmin) {
                PearAdmin.changePage({ id: 'versionmgr_upgrade', title: '版本总览', url: url, type: '_iframe', close: true });
            } else {
                window.location.href = url;
            }
        }

        // 关闭右下角浮动按钮
        $('#upgradeFloatClose').on('click', function(e) {
            e.stopPropagation();
            e.preventDefault();
            $('#upgradeFloatBtn').hide();
        });

        // 右下角浮动按钮点击打开多选项卡
        $('#upgradeFloatBtn').on('click', function(e) {
            e.preventDefault();
            openVersionmgrTab();
        });
    });
    </script>
    @yield('script')
    @stack('page_scripts')
</body>
</html>
