/**
 * 迅睿后台简化模式
 */
(function (window, $) {
    'use strict';
    if (!$ || !$.fn) {
        return;
    }

    function headerH() {
        var n = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--min-header-h'), 10);
        return isNaN(n) ? 50 : n;
    }

    function resizeIframe() {
        var h = (window.innerHeight || document.documentElement.clientHeight) - headerH();
        if (h < 200) {
            h = 200;
        }
        $('#right_page').css('height', h + 'px');
    }

    function closeSidebar() {
        $('body').removeClass('sidebar-open');
        $('.page-admin-min .page-sidebar').removeClass('in show');
    }

    function openSidebar() {
        $('body').addClass('sidebar-open');
        $('.page-admin-min .page-sidebar').addClass('in show');
    }

    $(function () {
        if (!$('body').hasClass('page-admin-min')) {
            return;
        }

        // 给菜单补 slide 参数，保证 app.js 手风琴正常
        var $menu = $('.page-admin-min .page-sidebar-menu');
        if (!$menu.attr('data-slide-speed')) {
            $menu.attr('data-slide-speed', '200');
        }

        // 默认展开第一个分组（并清掉可能残留的行内 display）
        var $open = $menu.children('li.nav-item.open');
        if (!$open.length) {
            $open = $menu.children('li.nav-item').first().addClass('open active');
        }
        $menu.find('> li.nav-item > .sub-menu').each(function () {
            var $sub = $(this);
            if ($sub.parent().hasClass('open')) {
                $sub.show();
            } else {
                $sub.hide();
            }
        });

        // 移动端抽屉
        $(document).on('click', '.page-admin-min .menu-toggler.responsive-toggler', function (e) {
            e.preventDefault();
            e.stopImmediatePropagation();
            if ($('body').hasClass('sidebar-open')) {
                closeSidebar();
            } else {
                openSidebar();
            }
        });
        $('#min_sidebar_overlay').on('click', closeSidebar);
        $(document).on('click', '.page-admin-min .page-sidebar-menu .sub-menu a', function () {
            if (window.matchMedia('(max-width: 991px)').matches) {
                closeSidebar();
            }
        });

        // iframe 高度
        var prev = window.wSize;
        window.wSize = function () {
            if (typeof prev === 'function') {
                try { prev(); } catch (e) {}
            }
            resizeIframe();
        };
        resizeIframe();
        $(window).on('resize.minAdmin', resizeIframe);
    });
})(window, window.jQuery);
