/**
 * 工具函数模块
 */
const Utils = {
    // 生成唯一 ID
    generateId() {
        return 'tab_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    },

    // 判断元素是否可见（包括祖先）
    isVisible(el) {
        if (!el) return false;
        let elem = el;
        while (elem) {
            if (window.getComputedStyle(elem).display === 'none') {
                return false;
            }
            elem = elem.parentElement;
        }
        return true;
    },

    // 日志输出（带类型）
    log(...args) {
        args.forEach(arg => {
            console.log(`[type => ${typeof arg}, content =>`, arg, ']');
        });
    },

    // 删除节点（安全）
    removeNode(...nodes) {
        nodes.forEach(node => {
            if (node && typeof node.remove === 'function') {
                node.remove();
            }
        });
    },

    // 阻止事件冒泡（现代浏览器）
    stopPropagation(e) {
        e.stopPropagation();
    }
};

/**
 * 消息提示模块
 */
const Message = {
    // layer.tips 封装
    tips(target, str) {
        layer.tips(str, $(target), {
            tips: [1, '#3595CC'],
            time: 0
        });
    },

    // layer.msg 封装（修复参数错误）
    msg(str, icon, offset) {
        const options = {
            offset: offset || '20px'
        };
        if (icon !== undefined && icon !== null && icon !== '') {
            options.icon = icon;
        }
        return layer.msg(str || '没有内容', options);
    }
};

/**
 * 显示控制模块
 */
const Display = {
    toggle(selector, displayValue = 'block') {
        const el = typeof selector === 'string' ? document.querySelector(selector) : selector;
        if (!el) return;
        const isVisible = window.getComputedStyle(el).display !== 'none';
        el.style.display = isVisible ? 'none' : displayValue;
    },
    adjustIframeHeight(iframe) {
        try {
            // 获取内嵌文档的实际高度
            const width = iframe.contentWindow.document.body.scrollWidth;
            iframe.style.width = `${width}px`;
        } catch (e) {
            console.warn("跨域限制无法自动调整高度");
        }
    }
};

/**
 * 全屏控制模块
 */
const Fullscreen = {
    isFullscreen() {
        return !!(document.fullscreenElement ||
            document.webkitFullscreenElement ||
            document.mozFullScreenElement ||
            document.msFullscreenElement);
    },

    request(id) {
        const el = document.documentElement;
        if (el.requestFullscreen) {
            el.requestFullscreen();
        } else if (el.webkitRequestFullscreen) {
            el.webkitRequestFullscreen();
        } else if (el.mozRequestFullScreen) {
            el.mozRequestFullScreen();
        } else if (el.msRequestFullscreen) {
            el.msRequestFullscreen();
        } else {
            Message.msg('浏览器不支持全屏，请按 F11 键手动全屏！');
            return;
        }

        // 更新按钮状态
        const $btn = $(`#${id}`);
        $btn.attr('onclick', `Fullscreen.exit('${id}')`)
            .attr('onmouseenter', `Message.tips(this, '退出全屏')`)
            .find('i').attr('class', 'fa fa-arrows');
    },

    exit(id) {
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        }

        // 更新按钮状态
        const $btn = $(`#${id}`);
        $btn.attr('onclick', `Fullscreen.request('${id}')`)
            .attr('onmouseenter', `Message.tips(this, '全屏')`)
            .find('i').attr('class', 'fa fa-arrows-alt');
    }
};

/**
 * 标签页管理模块
 */
const TabsManager = {
    currentMenuId: null,
    currentContentId: null,

    add(id, title, icons, url) {
        const safeId = id || Utils.generateId();
        const menuId = `tabs-menu-${safeId}`;
        const contentId = `tabs-content-${safeId}`;

        // 如果已存在，激活即可
        if ($('#' + menuId).length) {
            this.activate(menuId, contentId);
            return;
        }

        // 创建菜单项
        const $menu = $(`
            <li id="${menuId}" data-target="${contentId}">
                <div class="hover-box"></div>
                <span>${icons ? `<i class="${icons}"></i>` : ''}${title}<i class="layui-icon layui-icon-close icon-close-padd"></i></span>
                
            </li>
        `);

        // 创建内容区
        const $content = $(`
            <div id="${contentId}" class="tab-content">
                <iframe src="${url}" class="x-iframe" style="width:100%;height:100%"></iframe>
            </div>
        `);

        // 激活新 tab
        $('.canvas-tabs-menu li').removeClass('active');
        $('.canvas-tabs-content > div').removeClass('active');

        $menu.addClass('active');
        $content.addClass('active');

        $('.canvas-tabs-menu').append($menu);
        $('.canvas-tabs-content').append($content);

        this.currentMenuId = menuId;
        this.currentContentId = contentId;
    },

    activate(menuId, contentId) {
        $('.canvas-tabs-menu li').removeClass('active');
        $('.canvas-tabs-content > div').removeClass('active');

        $(`#${menuId}`).addClass('active');
        $(`#${contentId}`).addClass('active');

        this.currentMenuId = menuId;
        this.currentContentId = contentId;
    },

    close(menuId) {
        const $menu = $(`#${menuId}`);
        const contentId = $menu.data('target');

        // 销毁 iframe（关键！）
        const $iframe = $(`#${contentId} iframe`);
        if ($iframe.length) {
            $iframe[0].src = 'about:blank'; // 强制卸载资源
            $iframe.remove();
        }

        // 移除 DOM
        $menu.remove();
        $(`#${contentId}`).remove();

        // 激活相邻 tab
        const $prev = $menu.prev('li');
        const $next = $menu.next('li');
        if ($prev.length) {
            this.activate($prev.attr('id'), $prev.data('target'));
        } else if ($next.length) {
            this.activate($next.attr('id'), $next.data('target'));
        } else {
            // 回退到首页（假设 tabs-menu-0 存在）
            if ($('#tabs-menu-0').length) {
                this.activate('tabs-menu-0', 'tabs-content-0');
            }
        }
    },

    closeCurrent() {
        if (this.currentMenuId && this.currentMenuId !== 'tabs-menu-0') {
            this.close(this.currentMenuId);
        }
    },

    closeOthers() {
        if (this.currentMenuId === 'tabs-menu-0') {
            $('.canvas-tabs-menu li:not(#tabs-menu-0)').remove();
            $('.canvas-tabs-content div:not(#tabs-content-0)').remove();
            this.activate('tabs-menu-0', 'tabs-content-0');
        } else {
            // 保留当前和首页
            $('.canvas-tabs-menu li').each((_, el) => {
                const id = el.id;
                if (id !== this.currentMenuId && id !== 'tabs-menu-0') {
                    $(el).remove();
                }
            });
            $('.canvas-tabs-content div').each((_, el) => {
                const id = el.id;
                if (id !== this.currentContentId && id !== 'tabs-content-0') {
                    $(el).remove();
                }
            });
            this.activate(this.currentMenuId, this.currentContentId);
        }
    },

    closeAll() {
        $('.canvas-tabs-menu li:not(#tabs-menu-0)').remove();
        $('.canvas-tabs-content div:not(#tabs-content-0)').remove();
        this.activate('tabs-menu-0', 'tabs-content-0');
    }
};

/**
 * 主初始化逻辑
 */
$(function () {
    // 初始化首页（确保 tabs-menu-0 存在）
    if (!$('#tabs-menu-0').length) {
        $('.canvas-tabs-menu').append(`
            <li id="tabs-menu-0" data-target="tabs-content-0" class="active">
                <div class="hover-box"></div>
                <span>首页</span>
            </li>
        `);
        $('.canvas-tabs-content').append(`
            <div id="tabs-content-0" class="tab-content active">
                <iframe src="./welcome.html" class="x-iframe" style="width:100%;height:100%"></iframe>
            </div>
        `);
        TabsManager.currentMenuId = 'tabs-menu-0';
        TabsManager.currentContentId = 'tabs-content-0';
    }

    // 点击链接添加 tab
    $('.tabs').on('click', function (e) {
        e.preventDefault();
        const $this = $(this);
        const url = $this.attr('href');
        const title = $.trim($this.text());
        const id = $this.attr('id') || Utils.generateId();
        const icons = $this.attr('icons');
        if (url && url !== 'javascript:;') {
            TabsManager.add(id, title, icons, url);
        }
    });

    // 切换 tab（点击菜单项）
    $(document).on('click', '.canvas-tabs-menu > li', function (e) {
        const id = $(this).closest('li').attr('id');
        if (id === 'tabs-menu-0') {
            return;
        }
        if ($(e.target).hasClass('icon-close-padd')) return;
        const menuId = this.id;
        const contentId = $(this).data('target');
        TabsManager.activate(menuId, contentId);
    });

    // 关闭 tab
    $(document).on('click', '.icon-close-padd', function (e) {
        Utils.stopPropagation(e);
        const menuId = $(this).closest('li').attr('id');
        TabsManager.close(menuId);
    });

    // 关闭当前页
    $(document).on('click', '.closeNowPage', function (e) {
        Utils.stopPropagation(e);
        TabsManager.closeCurrent();
    });

    // 关闭其他页
    $(document).on('click', '.closeOtherPage', function (e) {
        Utils.stopPropagation(e);
        TabsManager.closeOthers();
    });

    // 关闭所有页
    $(document).on('click', '.closeAllPage', function (e) {
        Utils.stopPropagation(e);
        TabsManager.closeAll();
    });
    // 刷新页面
    $('.refresh').on('click', () => window.location.reload());

    // 手风琴导航
    $('.canvas-nav-item > a').on('click', function () {
        if ($('.canvas-nav-item').hasClass('canvas-nav-small')) return;

        const $parent = $(this).parent('li');
        const $submenu = $(this).next('ul');

        if ($submenu.is(':hidden')) {
            $('.canvas-nav-item ul').slideUp(300);
            $submenu.slideDown(300);
            $parent.addClass('canvas-nav-show').siblings().removeClass('canvas-nav-show');
        } else {
            $submenu.slideUp(300);
            $parent.removeClass('canvas-nav-show');
        }
    });

    // 收放导航
    $('.switch-list').on('click', function () {
        const $icon = $(this).children('i');
        if ($icon.hasClass('layui-icon-shrink-right')) {
            $icon.removeClass('layui-icon-shrink-right').addClass('layui-icon-spread-left');
        } else {
            $icon.removeClass('layui-icon-spread-left').addClass('layui-icon-shrink-right');
        }

        $('.layout-body').toggleClass('canvas-nav-small');
        if ($('.layout-body').hasClass('canvas-nav-small')) {
            $('.canvas-nav-item').removeClass('canvas-nav-show').children('ul').removeAttr('style');
        }
    });

    // 右侧抽屉栏
    $(document).on('click', '.dashboard, .user-info', function (e) {
        const barClass = $(this).attr('tag');
        if (!barClass) {
            Message.msg('配置的 tag 目标为空');
            return;
        }

        const $bar = $('.' + barClass);
        if ($bar.length === 0) {
            Message.msg('未找到对应右侧栏元素');
            return;
        }

        Utils.stopPropagation(e);
        if ($bar.css('right') === '-1500px') {
            $('.right-bar').css('right', '-1500px');
            $bar.css('right', 0);
            $('.tpl-body').css('overflow', 'hidden');
        } else {
            $bar.css('right', '-1500px');
            $('.tpl-body').css('overflow', 'auto');
        }
    });

    // 点击遮罩关闭右侧栏
    $(document).on('click', function () {
        $('.right-bar').css('right', '-1500px');
        $('.tpl-body').css('overflow', 'auto');
    });

    // 阻止右侧栏内部点击关闭
    $(document).on('click', '.right-bar', function (e) {
        Utils.stopPropagation(e);
    });

    // 主题切换
    $('#style-list').on('click', 'li', function (e) {
        const style = $(this).attr('canvas-theme-style');
        if (!style) return;

        const $theme = $('.canvas-theme-style');
        const oldStyle = $theme.attr('style-name') || '';
        $theme.removeClass(oldStyle).addClass(style).attr('style-name', style);

        Utils.stopPropagation(e);
    });

    // 全局提示绑定（示例）
    $('[data-tips]').each(function () {
        const text = $(this).data('tips');
        $(this).on('mouseenter', () => Message.tips(this, text));
    });
});

// 暴露全局接口（如需在 HTML 中调用）
window.fullScreen = Fullscreen.request;
window.exitScreen = Fullscreen.exit;
window.msg = Message.msg;
window.getTips = Message.tips;
window.toggleDisplay = Display.toggle;
window.log = Utils.log;
window.remove_node = Utils.removeNode;
window.tabsManager = TabsManager