// 断点配置
let whirBreakpoints = { mobile: 750, tablet: 1024, desktopContent: 1600, desktop: 1920 };
// 移动端适配配置 默认关闭
let whirMobileConfig = {
    enabled: false, // 是否启用移动端适配
    designWidth: 375, // 基准设计稿宽度
    designFontSize: 100, // 基准fontSize
    breakpoints: [ // 断点配置数组
        { width: 375 },
        { width: 414 },
        { width: 639 },
        { width: 749 }
    ]
};

// Mac设备字体大小适配
function initMacFontSize() {
    function isMac() {
        return /Macintosh|MacIntel|MacPPC|Mac68K/.test(navigator.userAgent);
    }

    if (isMac()) {
        $('html').addClass('isMac');
        function updateFontSize() {
            // 获取视口宽度
            var viewportWidth = window.innerWidth;
            if (viewportWidth < whirBreakpoints.desktopContent) {
                // 根据公式计算字体大小
                var fontSize = (100 / whirBreakpoints.desktopContent) * viewportWidth;
                // 设置给 html 元素
                $('html').css('font-size', fontSize + 'px');
            } else {
                $('html').removeAttr("style")
            }
        }

        // 初始化字体大小
        updateFontSize();

        // 监听窗口大小变化，包括缩放
        window.addEventListener('resize', updateFontSize);
    }
}

// 移动端适配
(function (win, doc) {
    // 如果未启用移动端适配，执行Mac设备字体大小适配
    if (!whirMobileConfig.enabled) {
        initMacFontSize();
        return;
    }

    var docEl = doc.documentElement;

    // 使用配置中的值
    var designWidth = whirMobileConfig.designWidth;
    var designFontSize = whirMobileConfig.designFontSize;
    var breakpoints = whirMobileConfig.breakpoints;

    // 断点配置数组，只需要配置宽度，base值会自动计算
    var breakpoints = [
        { width: 375 },
        { width: 414 },
        { width: 639 },
        { width: 749 }
    ];

    // 计算每个断点的基准值
    function calculateBaseValues() {
        for (var i = 0; i < breakpoints.length; i++) {
            // 基准值计算公式：(断点宽度/设计稿宽度) * 设计稿基准fontSize * 设计系数
            // 设计系数可以根据需要调整，这里使用0.9~1.1的系数使得不同断点有细微差别
            var factor = 0.9 + (i / (breakpoints.length - 1)) * 0.2;
            breakpoints[i].base = (breakpoints[i].width / designWidth) * designFontSize * factor;
        }
    }

    // 初始化计算基准值
    calculateBaseValues();

    function setRemUnit() {
        var clientWidth = docEl.clientWidth;
        var clientHeight = docEl.clientHeight;
        var rem = designFontSize; // 默认基准值

        // 只在移动端（小于750px）时进行比例计算
        if (clientWidth < whirBreakpoints.mobile) {
            // 处理屏幕旋转的情况
            if (clientWidth > clientHeight) {
                // 横屏模式
                // 使用设备高度和宽度的比例来计算基准值
                var ratio = clientHeight / clientWidth;
                // 根据比例动态调整缩放系数
                var scaleFactor = ratio > 0.5 ? 0.8 : 1;
                // 使用较小的值作为基准，避免字体过大
                var baseWidth = Math.min(clientWidth, whirBreakpoints.mobile);
                rem = (baseWidth / designWidth) * designFontSize * scaleFactor;
            } else {
                // 竖屏模式
                // 查找合适的断点
                for (var i = 0; i < breakpoints.length; i++) {
                    if (clientWidth <= breakpoints[i].width) {
                        rem = (clientWidth / breakpoints[i].width) * breakpoints[i].base;
                        break;
                    }
                }
            }
        } else {
            // 桌面端考虑分辨率缩放
            if (clientWidth > whirBreakpoints.desktopContent && clientWidth <= whirBreakpoints.desktop) {
                rem = 100;
            } else if (clientWidth > whirBreakpoints.desktop) {
                // 超过1920px时，继续按比例增长
                rem = (clientWidth / whirBreakpoints.desktop) * 100;
            } else {
                rem = designFontSize / whirBreakpoints.desktopContent * clientWidth;
            }
        }

        // 限制最大和最小字体大小
        rem = Math.min(Math.max(rem, 50), 400); // 调整最大字体限制为200
        docEl.style.fontSize = rem + 'px';
    }

    // 监听窗口大小变化
    win.addEventListener('resize', setRemUnit);
    // 监听页面显示事件
    win.addEventListener('pageshow', function (e) {
        if (e.persisted) {
            setRemUnit();
        }
    });
    // 监听缩放变化
    win.addEventListener('zoom', setRemUnit);

    // 监听屏幕旋转事件（兼容性处理）
    var orientation = 'portrait';
    var orientationTimer = null;

    // 检测设备方向变化
    function handleOrientation() {
        var currentOrientation = window.innerWidth > window.innerHeight ? 'landscape' : 'portrait';
        if (currentOrientation !== orientation) {
            orientation = currentOrientation;
            // 清除之前的定时器
            if (orientationTimer) {
                clearTimeout(orientationTimer);
            }
            // 设置新的定时器，确保旋转完成后再计算
            orientationTimer = setTimeout(setRemUnit, 300); // 增加延时确保旋转完成
        }
    }

    // 使用多种方式监听屏幕旋转
    if (window.orientation !== undefined) {
        // iOS设备
        win.addEventListener('orientationchange', handleOrientation);
    }

    // 监听resize事件来处理屏幕旋转
    var resizeTimer = null;
    win.addEventListener('resize', function () {
        if (resizeTimer) {
            clearTimeout(resizeTimer);
        }
        resizeTimer = setTimeout(handleOrientation, 300); // 增加延时确保旋转完成
    });

    // 初始化
    setRemUnit();
})(window, document);
//移动端适配  END
/**
 * 整站调用方法
 */
let whirPublic = {};
var isDark = false;

whirPublic.config = {
    backTop: function () {
        //返回顶部
        var offset = 200,
		offset_opacity = 1200,
		scroll_top_duration = 1000,
		$back_to_top = $('.fix-right');
        $(window).scroll(function(){
            ( $(this).scrollTop() > offset ) ? $back_to_top.addClass('up') : $back_to_top.removeClass('up');
                var win_top = $(this).scrollTop();

        });
        $('.back-top').click(function(){$('html,body').animate({ scrollTop: 0 }, 800);}); 
    },
    headerUp:function(){
       // header样式切换
        function setHeaderStyle(isScroll, isHover) {
            if (isDark) {
                $("header").removeClass('light-style').addClass('dark-style');
            } else if (isHover || isScroll) {
                $("header").removeClass('light-style').addClass('dark-style');
            } else {
                $("header").removeClass('dark-style').addClass('light-style');
            }
        }

        // 初始化
        setHeaderStyle(false, false);

        // 滚动方向检测变量
        var lastScrollTop = 0;
        var scrollThreshold = 5; // 滚动阈值，避免微小滚动触发

        $(window).scroll(function () {
            var docScroll = $(document).scrollTop();

            // 检测滚动方向
            if (Math.abs(docScroll - lastScrollTop) > scrollThreshold) {
                if (docScroll > lastScrollTop) {
                    // 向下滚动
                    scrollDirection = 'down';
                    $("header").addClass('up');
                } else {
                    // 向上滚动
                    scrollDirection = 'up';
                    $("header").removeClass('up');
                }
                lastScrollTop = docScroll;
            }

            setHeaderStyle(docScroll > 0, false);
        });

        $("header").hover(
            function () {
                if (isDark) return; // isDark时不执行hover效果
                setHeaderStyle(false, true);
            },
            function () {
                if (isDark) return; // isDark时不执行hover效果
                var docScroll = $(document).scrollTop();
                setHeaderStyle(docScroll > 0, false);
            }
        );
    },
    top: function () {
        $("#m" + m).addClass('aon');
         
        //打开搜索
        whirPublic.open.clickOpen('.open-search', 'body', 'search-show', '.top-search');
        //移动端菜单
        whirPublic.open.clickOpen('.open-menu', 'body', 'menu-show', '.main-nav');


        //打开下拉
        $(".main-nav li").each(function () {
            var num = $(this).find(".sub").find("dd").length;
            if (num > 0) {
                $(this).addClass("has-sub");
                $(this).find("span").append('<i class="wap-op"></i>');
            }
            $(this).hover(function () {
                var $this = $(this);
                $this.addClass('aon').siblings().removeClass('aon');
                clearTimeout($this.data('hoverTimer'));
                $this.data('hoverTimer', setTimeout(function () {
                    $this.addClass("show").siblings().removeClass("show");
                }, 300));
            }, function () {
                var $this = $(this);
                $this.removeClass('aon');
                $("#m" + m).addClass('aon')
                clearTimeout($this.data('hoverTimer'));
                $this.data('hoverTimer', setTimeout(function () {
                    $this.removeClass("show");
                }, 300));
            });

            //二级图切换
            var _sub = $(this).find(".sub")
            var _handle = _sub.find(".mid").find("dd")
            var _img = _sub.find(".right").find("figure")
            _handle.hover(function () {
                var _this = $(this)
                var _imgSrc = _this.data("img")
                _img.css("background-image", "url(" + _imgSrc + ")");
                _this.addClass("active").siblings().removeClass("active");
            });
            _sub.find(".mid").find("dl").each(function () {
                var _this = $(this).find("dd")
                _this.each(function (i) {
                    $(this).css("--s", i * 0.1 + "s")
                })
            })
            //二级分类显示
            var _left = _sub.find(".left")
            var _mid = _sub.find(".mid")
            var _left_dd = _left.find("dd")
            _left_dd.hover(function () {
                var id = $(this).data("id")
                _mid.find("dl[data-id='" + id + "']").addClass("active").siblings().removeClass("active");
                $(this).addClass("active").siblings().removeClass("active");
                //默认选择
                var _first = _mid.find("dl[data-id='" + id + "']").find("dd").eq(0)
                var _first_img = _first.data("img")
                _img.css("background-image", "url(" + _first_img + ")");
                _first.addClass("active").siblings().removeClass("active");
            });
            _left_dd.eq(0).addClass("active");
            _mid.find("dl").eq(0).addClass("active").siblings().removeClass("active");
            _mid.find("dl").eq(0).find("dd").eq(0).addClass("active").siblings().removeClass("active");
            _img.css("background-image", "url(" + _mid.find("dl").eq(0).find("dd").eq(0).data("img") + ")");

        });
        const $activeLi = $('.main-nav li.aon');
        if ($activeLi.length > 0) {
            $activeLi.addClass('wap-show');
            $activeLi.find('.sub').slideDown();
        }
        $(".wap-op").click(function () {
			$(this).parents("li").toggleClass("wap-show");
			$(this).parent("span").next(".sub").slideToggle();
			$(this).parents("li").siblings().removeClass("wap-show");
			$(this).parents("li").siblings().find(".sub").slideUp();
		});
        $(".main-nav").mouseleave(function () {
            $(this).find("li").removeClass("show");
        });
        // ============ 点击下拉菜单后，设置active状态 s ============
        function setActiveStates($activeLink) {
            var $currentDd = $activeLink.parent('dd');
            var $subContainer = $activeLink.closest('.sub');
            // 先清空当前下拉里所有的active，防止残留
            $subContainer.find('dd, dl').removeClass('active');
            // 判断是二级菜单还是三级菜单
            if ($currentDd.closest('.left').length > 0) {
                // 点击的是【左侧二级dd】
                var targetId = $currentDd.data('id');
                $currentDd.addClass('active');
                $subContainer.find('.mid dl[data-id="' + targetId + '"]').addClass('active');
                var $first3dd = $subContainer.find('.mid dl[data-id="' + targetId + '"] dd').eq(0);
                $first3dd.addClass('active');
                // 同步右侧背景图
                var imgSrc = $first3dd.data('img');
                if(imgSrc) $subContainer.find('.right figure').css("background-image", "url(" + imgSrc + ")");
            } else {
                // 点击的是【中间三级dd】
                $currentDd.addClass('active');
                var targetId = $currentDd.parent('dl').data('id');
                $subContainer.find('.left dd[data-id="' + targetId + '"]').addClass('active');
                $subContainer.find('.mid dl[data-id="' + targetId + '"]').addClass('active');
                // 同步右侧背景图
                var imgSrc = $currentDd.data('img');
                if(imgSrc) $subContainer.find('.right figure').css("background-image", "url(" + imgSrc + ")");
            }
        }

        function updateActiveMenu() {
            var currentUrl = window.location.href;
            $('.main-nav a').each(function () {
                var $this = $(this);
                var linkHref = $this.attr('href');
                if (!linkHref) return true;
                // 兼容 普通链接 / 锚点链接 / 带域名的完整链接
                var linkUrl = new URL(linkHref, window.location.origin);
                // 匹配规则：锚点包含匹配 || 路径开头匹配
                if (linkUrl.hash && currentUrl.includes(linkUrl.hash) || currentUrl.startsWith(linkUrl.href)) {
                    setActiveStates($this);
                    return false; // 找到匹配项立即停止遍历
                }
            });
        }
        // 页面加载时执行一次
        updateActiveMenu();
        // 锚点变化时执行（页面不刷新的锚点跳转核心）
        $(window).on('hashchange', updateActiveMenu);
        // 额外：解决点击a标签时的瞬时active同步
        $('.main-nav a').click(function(){
            if($(this).attr('href').indexOf('#')>-1){
                setActiveStates($(this));
            }
        });
        // ============ 点击下拉菜单后，设置active状态 end ============

        //滑过显示阴影效果
		$(".itemhover").hover(function(){
            $(this).addClass("activehover");
                },function(){
                        $(this).removeClass("activehover");
            });
            $(".itemhover2").hover(function(){
                $(this).addClass("activehover2");
        },function(){
                $(this).removeClass("activehover2");
        });

    },
    bottom: function () {

        //滑动效果
        scrollxf.init({wrapper:'#bloc',targets:'.scr-el',wrapperSpeed:0.1});

        //顶部
        whirPublic.config.top();

        //判断无图
        $.each($("img"), function (i, n) {
            $(n).on('error', function () {
                n.src = noPicPath + 'no-pic.svg';
                // 检查父元素是否有is-bgImg__类
                const parent = $(n).closest('[class*="is-bgImg__"]');
                if (parent.length) {
                    parent.css('background-image', `url(${noPicPath}no-pic.svg)`);
                } else {
                    n.classList.add('no-pic');
                }
            });
            n.src = n.src;
        });
        //返回顶部
        whirPublic.config.backTop();

        //社交媒体
        whirPublic.open.hoverCss('.follow-us li', 'show');

        //自定义下拉
        $(".select-txt").each(function () {
            var _this = $(this);
            var selectedText = _this.find(".selected").text().trim(); // 获取默认选中的文本
            var $options = _this.find(".hover li");
            var firstOptionText = $options.first().text().trim(); // 获取第一个选项的文本
            
            // 初始化：为匹配的li添加选中状态
            $options.each(function() {
                if ($(this).text().trim() === selectedText) {
                    $(this).addClass("cur").siblings().removeClass("cur");
                    
                    // 如果默认选中的是第一个选项，添加on样式
                    if (selectedText === firstOptionText) {
                        _this.addClass("on");
                    }
                    
                    return false; // 找到匹配项后退出循环
                }
            });

            _this.click(function (e) {
                _this.toggleClass("show").siblings().removeClass("show");
            });

            // 处理单选（hover类）
            _this.find(".hover li").click(function () {
                $(this).addClass("cur").siblings().removeClass("cur");
                var text = $(this).text();
                _this.find(".selected").text(text);
                _this.addClass("on"); // 选择时始终添加on样式
            });
        });
        $("body").on('click', function (e) {
        if (!$(e.target).closest('.select-txt').length) {
            $('.select-txt').removeClass('show');
            }
        });

        $('.subTit').each(function() {
            if ($(this).find('h2').length) {
             $(this).find('.tit').addClass('has');
            }
        });

        //底部栏目菜单
        $("footer .sub-item").each(function () {
            var _p = $(this).find(".parent")
            var _list = $(this).find(".list")
            _list.find("dl").each(function () {
                $(this).find("dd").each(function (i) {
                    $(this).css("--s", i * 0.1 + 's')
                });
            });
            _p.find("dd").hover(function () {
                $(this).addClass("active").siblings().removeClass("active");
                var id = $(this).data("id");
                _list.find("dl[data-id='" + id + "']").addClass("active").siblings().removeClass("active");
            });
            //默认选择
            _p.find("dd").eq(0).addClass("active");
            _list.find("dl").eq(0).addClass("active");
        });

        //详情页
        $(".news-details .edit-info p").each(function() {
            if ($(this).has("img").length > 0) {
                            $(this).addClass("tc").css("text-indent","0em");
            }
        });
        //判断 p 里面有 &nbsp时给去掉
        document.addEventListener ('DOMContentLoaded', function () {
                    const targetParagraph = document.querySelector ('p.tc');
                    if (targetParagraph) {
                    Array.from (targetParagraph.childNodes).forEach (node => {
                    if (node.nodeType === Node.TEXT_NODE) {
                    const cleanedText = node.textContent
                    .replace (/\u00A0/g, ' ') // 将所有 转为普通空格
                    .replace (/\s+/g, ' '); // 合并多个连续空格为一个
                    node.textContent = cleanedText.trim (); // 去除首尾空格
                    }
                    });
                    }
                });

        //判断 p 为空时
        const paragraphs = document.querySelectorAll('p');
            paragraphs.forEach(paragraph => {
            const text = paragraph.textContent.replace(/\s+/g, '').replace(/\u00A0/g, '');
            const hasImage = paragraph.querySelector('img') !== null;
            if (text === '' && !hasImage) {
                paragraph.style.display = 'none';
            }
        }); 

        //禁止移动端Safari浏览器缩放
        var userAgent = navigator.userAgent;
        if (userAgent.indexOf("Safari") > -1) {
            document.addEventListener('gesturestart', function (event) {
                event.preventDefault()
            })
        }
        //滚动动画&数字滚动
        $(function () {
            setTimeout(function () {
                new ScrollAnimate();
            }, 200);
        });

        //右侧快捷导航点击表单弹窗
        $(".fix-right .formbtn").click(function(){
            $(".pop-form").addClass("show");
            $("body").addClass("bodyon");
        })
        $(".pop-form .close").click(function(){
            $(".pop-form").removeClass("show");
            $("body").removeClass("bodyon");
        })
    },
    navMenu(nav){
        $("#nav"+nav).addClass("aon");
    },
    home: function () {
        //顶部滚动及滑过效果
        whirPublic.config.headerUp();
        
        //banner 轮播
        whirPublic.video.banner('.home-ban');
        
        //about
        $(".home-about .map li").hover(function(){
            $(this).addClass("on").siblings().removeClass("on");
        })

        //tec
        var $items = $(".home-technology .list .item");
        $items.eq(0).addClass("cur").find(".detail").show();
        $(".home-technology .list").on("click", ".cricle", function() {
            var $clickedItem = $(this).parent();
            var clickedIndex = $items.index($clickedItem); // 
            var isLastItem = $clickedItem.is($items.last());

            $items.removeClass("cur frist one").find(".detail").hide(); //
            $clickedItem.addClass("cur").find(".detail").show();

            // 
            if (clickedIndex === 1) {
                $items.eq(0).addClass("one");
            }
            // 
            if (isLastItem) {
                $items.eq(0).addClass("frist");
            }
        });
        //end

        $(".home-business .card-list .item").hover(
            function() {
                const $this = $(this);
                $this.data('hoverTimer', setTimeout(function() {
                $this.addClass("hover").siblings().removeClass("hover");
                }, 300));
            },
            function() {
                clearTimeout($(this).data('hoverTimer'));
                $(this).removeClass("hover");
            }
            );
        
    },
    mouse() {
        // 鼠标跟随效果 - 仅在桌面端启用
        if (window.innerWidth <= whirBreakpoints.mobile) {
            return; // 移动端不启用鼠标跟随效果
        }

        const $swiperMain = $('.swiper-main');
        const $mouse = $('.mouse');

        if ($swiperMain.length && $mouse.length) {
            const mouseWidth = $mouse.width();
             const mouseHeight = $mouse.height();
            // 设置初始状态
            $mouse.css({
                'opacity': '0',
                'pointer-events': 'none',
                'transition': 'opacity 0.3s ease',
                'z-index': '9999' // 确保鼠标图标在最上层
            });

            // 鼠标进入swiper-main区域
            $swiperMain.on('mouseenter', function () {
                $mouse.css('opacity', '1');
            });

            // 鼠标移动时跟随 - 使用节流优化性能
            let ticking = false;
            $swiperMain.on('mousemove', function (e) {
                if (!ticking) {
                    requestAnimationFrame(function () {
                        // 由于mouse元素使用position: fixed，直接使用clientX和clientY
                        const x = e.clientX - $mouse.width() / 2;
                        const y = e.clientY - $mouse.height() / 2;

                        $mouse.css({
                            'left': x + 'px',
                            'top': y + 'px',
                            'transition': 'none' // 移动时不使用过渡动画，保持跟随流畅
                        });
                        ticking = false;
                    });
                    ticking = true;
                }
            });

            // 鼠标离开swiper-main区域
            $swiperMain.on('mouseleave', function () {
                $mouse.css({
                    'opacity': '0',
                    'transition': 'opacity 0.3s ease'
                });
            });

            // 窗口大小变化时重新初始化
            $(window).on('resize', function () {
                if (window.innerWidth <= whirBreakpoints.mobile) {
                    mouseWidth = $mouse.width();
                    mouseHeight = $mouse.height();
                    // 移动端时隐藏鼠标图标
                    if (window.innerWidth <= whirBreakpoints.mobile) {
                        // 移动端时隐藏鼠标图标
                        $mouse.css('opacity', '0');
                    }
                }
            });
        }
    },
    
}


/**
 * 触发效果
 */
whirPublic.open = {
    /**鼠标悬停效果
     * @param {string} m - 效果主体选择器
     * @param {string} className - 效果样式
     * @returns {void}
     */
    hoverCss: function (m, className) {
        $(m).hover(function () {
            $(this).toggleClass(className ? className : 'show');
        });
    },
    /**点击触发效果
     * @param {string} btn - 触发效果的按钮选择器
     * @param {string} main - 效果主体选择器
     * @param {string} css - 效果样式
     * @param {string} outside - 点击外部区域关闭效果
     * @returns {void}
     */
    clickOpen: function (btn, main, css, outside) {
        $(btn).click(function (e) {
            $(main).toggleClass(css);
            $(document).on("click", function () {
                $(main).removeClass(css);
            });
            e.stopPropagation();
        });
        $(outside).on("click", function (e) {
            e.stopPropagation();
        });
    },
    /**WAP端菜单
     * @param {string} m - 菜单容器选择器
     * @param {string} nav - 菜单导航选择器
     * @param {string} dl - 菜单列表选择器
     * @param {string} dt - 菜单标题选择器
     * @param {string} dd - 菜单子项选择器
     * @returns {void}
     */
    wapToMenu: function (m, nav, dl, dt, dd) {
        $(m).each(function () {
            var _this = $(this).find(nav).find(dl);
            _this.each(function () {
                var e = $(this).find(dd).length
                if (e >= 1) {
                    $(this).find(dt).append('<span class="wap-icon__open"></span>');
                }
            });
        });
        $(".wap-icon__open").click(function () {
            var _dl = $(this).parents(dl)
            _dl.find(dd).slideToggle();
            _dl.addClass("active");
            _dl.siblings().removeClass("active");
            _dl.siblings().find(dd).slideUp();
        });
    },
    /**
     * 弹窗视频
     * @param {string} btn - 触发弹窗视频的按钮选择器
     * @returns {void}
     */
    videoOpen: function (btn, directives, parent) {
        $(btn).click(function () {
            var files = $(this).data("files");
            var data = window[$(this).data("name")];
            console.log(data);

            if (directives == 'outside') {
                $(".popup-box__video").remove();
                var titleArea = '';
                if (data && (data.title || data.intro)) {
                    titleArea = '<div class="tit-area"><div class="title">' + (data.title || '') + '</div><div class="edit-info">' + (data.intro || '') + '</div></div>';
                }
                $('body').append("<div class='popup-box__video flex__aic__jcc'><section class='inner'><div class='close'></div><video src='" + files + "' controls autoplay  x-webkit-airplay='true' x5-video-player-type='h5' x5-video-player-fullscreen='true' webkit-playsinline='true' playsinline='true'></video>" + titleArea + "</section></div>");
                $('body').css("overflow", "hidden");
                videoClose();
            } else if (directives == 'inside') {
                $(this).hide();
                $(this).parent(parent).parents("div").find(".inside_video").remove();
                $(this).parents(parent).append("<div class='inside_video'><video src='" + files + "' controls autoplay  x-webkit-airplay='true' x5-video-player-type='h5' x5-video-player-fullscreen='true' webkit-playsinline='true' playsinline='true'></video></div>");
            }
        });

        function videoClose() {
            $(".popup-box__video .close").click(function (e) {
                $(".popup-box__video").remove();
                $('body').css("overflow", "auto");
            });
        }
    },
    /**
     * 实现标签页切换功能
     * @param {string} m - 标签页容器选择器，包含标签按钮和内容区域的父元素
     * @param {string} toggleName - 触发切换的事件类型，'hover'表示鼠标悬停触发，其他值则为点击触发
     * @param {string} ul - 自定义标签按钮列表容器选择器，默认为'.tab-ul'
     * @param {string} li - 自定义标签按钮元素选择器，默认为'li'
     * @param {string} box - 自定义标签内容容器选择器，默认为'.tab-list'
     * @param {string} child - 自定义标签内容元素选择器，默认为'.box'
     * @param {string} effect - 切换效果类型，可选值：'fade'、'slide'，默认无动画
     * @param {number} duration - 动画持续时间（毫秒），默认为300
     * @returns {void}
     */
    tabChangeClick: function (m, toggleName, ul, li, box, child, effect, duration) {
        $(m ? m : '.whir-tab').each(function () {
            // 获取标签按钮容器，如果未提供自定义选择器则使用默认值'.tab-ul'
            var _ul = $(this).find(ul ? ul : '.whir-tab__ul')
            // 获取所有标签按钮，如果未提供自定义选择器则使用默认值'li'
            var _li = _ul.find(li ? li : '.whir-tab__li')
            // 获取标签内容容器，如果未提供自定义选择器则使用默认值'.tab-list'
            var _box = $(this).find(box ? box : '.whir-tab__list')
            // 获取所有标签内容元素，如果未提供自定义选择器则使用默认值'.box'
            var _child = _box.find(child ? child : '.whir-tab__box')
            // 设置动画持续时间，默认为300毫秒
            var animDuration = duration || 300;

            // 默认激活第一个标签按钮
            _li.eq(0).addClass("active");
            // 默认显示第一个标签内容
            if (effect == 'fade' || effect == 'slide') {
                _child.eq(0).show().siblings().hide();
            } else {
                _child.eq(0).addClass("active");
            }

            // 根据toggleName参数确定触发事件类型，'hover'对应鼠标悬停，其他值对应点击事件
            var event = toggleName === 'hover' ? 'mouseover' : 'click';
            // 为所有标签按钮绑定事件
            _li.on(event, function () {
                // 获取当前标签按钮的索引
                var e = $(this).index();
                // 激活当前标签按钮，移除其他按钮的激活状态
                $(this).addClass("active").siblings().removeClass("active");

                // 根据效果类型应用不同的动画
                if (effect === 'fade') {
                    // 淡入淡出效果
                    _child.hide();
                    _child.eq(e).fadeIn(animDuration);
                } else if (effect === 'slide') {
                    // 滑动效果
                    _child.stop(true, true).slideUp(animDuration);
                    _child.eq(e).stop(true, true).slideDown(animDuration);
                } else {
                    // 无动画效果，直接切换显示状态
                    _child.eq(e).addClass("active").siblings().removeClass("active")
                }
            });
        });
    }
}


/**
  * 搜索功能模块
  * cn: 中文搜索
  * en: 英文搜索
  * 其他语言搜索cn,en都可用，更改后面参数即可
  */
whirPublic.search = {
    cn: function (btn, kid, url, txt, txt1, txt2, txt3) {
        $(btn).jqSearch({
            TxtVal: txt ? txt : "请输入关键字",
            KeyTxt1: txt1 ? txt1 : "输入关键词搜索！",
            KeyTxt2: txt2 ? txt2 : "输入的关键词字数不要过多！",
            KeyTxt3: txt3 ? txt3 : "您输入的内容存在特殊字符！",
            KeyId: kid, //输入框id
            KeyUrl: url, //跳转链接
            KeyHref: "key", //链接传值
            Static: false //是否静态站
        });
    },
    en: function (btn, kid, url, txt, txt1, txt2, txt3) {
        $(btn).jqSearch({
            TxtVal: txt ? txt : "Please enter keywords",
            KeyTxt1: txt1 ? txt1 : "Enter keywords to search!",
            KeyTxt2: txt2 ? txt2 : "Don't enter too many keywords!",
            KeyTxt3: txt3 ? txt3 : "The content you entered contains special characters!",
            KeyId: kid, //输入框id
            KeyUrl: url, //跳转链接
            KeyHref: "key", //链接传值
            Static: false //是否静态站
        });
    }
}

/**
 * 视频轮播功能模块
 */
let publicSwiperVideo;
whirPublic.video = {
    /**
     * 初始化视频轮播
     * @param {string} name - 轮播容器选择器
     * @param {array} arr - 轮播图片数组
     * @param {string} ef - 轮播切换效果，默认为 'fade'
     * @param {string} pt - 分页器类型，默认为 'bullets'
     * @returns {void}
     */
    banner: function (name, arr, ef, pt) {
        // 确保 arr 是数组
        arr = Array.isArray(arr) ? arr : [];

        // 定义默认选择器
        var defaultSelectors = [
            '.whir-video__swiper',
            '.swiper-slide',
            '.controls-page',
            '.total',
            '.cur',
            '.arrow-next',
            '.arrow-prev',
            '.pause-play-btn'
        ];

        // 合并默认选择器和用户提供的选择器
        var newArr = [];
        for (var i = 0; i < defaultSelectors.length; i++) {
            // 如果用户提供了选择器且不为null，则使用用户的选择器，否则使用默认选择器
            newArr.push(name + " " + (arr[i] || defaultSelectors[i]));
        }

        let num_total = rang($(newArr[1]).length, 9)
        $(newArr[3]).text(num_total);

        whirPublic.video.addVideo(newArr[1]);
        whirPublic.video.main(newArr[0], ef, newArr[2], pt, newArr[5], newArr[6]);
        // 添加暂停/播放按钮功能
        $(newArr[7]).on('click', function() {
        if (publicSwiperVideo && publicSwiperVideo.autoplay) {
            if (publicSwiperVideo.autoplay.running) {
                publicSwiperVideo.autoplay.stop();
                $(this).removeClass('pause').addClass('play');
                $(this).attr('title', '播放');
            } else {
                publicSwiperVideo.autoplay.start();
                $(this).removeClass('play').addClass('pause');
                $(this).attr('title', '暂停');
            }
        }
      });
        publicSwiperVideo.on('slideChange', function () {
            var index = publicSwiperVideo.realIndex;
            var num = index + 1
            var num_real = rang(num, 9);
            $(newArr[4]).text(num_real);
        })

        function rang(a, b) {
            return a <= b ? '0' + a : a;
        }
    },
    /**
     * 配置并初始化 Swiper 视频轮播
     * @param {string} container - 轮播容器选择器
     * @param {string} effect - 轮播切换效果，默认为 'fade'
     * @param {string} paginationEl - 分页器选择器
     * @param {string} paginationType - 分页器类型，默认为 'bullets'
     * @param {string} nextButton - 下一个按钮选择器
     * @param {string} prevButton - 上一个按钮选择器
     * @returns {void}
     */
    main: function (container, effect, paginationEl, paginationType, nextButton, prevButton) {
        publicSwiperVideo = new Swiper(container, {
            loop: true,
            speed: 1200,
            autoplay: {
                delay: 4000,
                disableOnInteraction: false
            },
            effect: effect ? effect : 'fade',
            fadeEffect: {
                crossFade: true,
            },
            pagination: {
                el: paginationEl,
                type: paginationType ? paginationType : 'bullets',
                clickable: true,
                formatFractionCurrent: function (number) {
                    return number < 10 ? '0' + number : number;
                },
                formatFractionTotal: function (number) {
                    return number < 10 ? '0' + number : number;
                }
            },
            navigation: {
                nextEl: nextButton,
                prevEl: prevButton,
            },
            on: {
                init: function () {
                    for (let index = 0; index < this.slides.length; index++) {
                        const element = this.slides[index];
                        if ($(element).find('video').length > 0) {
                            $(element).find('video').attr("id", "banner-video__" + index)
                        }
                    }
                    playVideo(this.slides, this.activeIndex);
                },
                slideChange: function () {
                    for (let index = 0; index < this.slides.length; index++) {
                        const element = this.slides[index];
                        if ($(element).find('video').length > 0) {
                            $(element).find('video')[0].pause();
                            $(element).find('video')[0].currentTime = 0;
                            $(element).find('video')[0].muted = true;
                            $(element).find('.video-inner').removeClass("active");
                        }
                    }
                    playVideo(this.slides, this.activeIndex);
                }
            }
        });
        function playVideo(slide, index) {
            var videoInner = $(slide[index]).find('.video-inner');
            var winW = $(window).width() || window.innerWidth;
            var t = setTimeout(function () {
                if (videoInner.length > 0) {
                    if (winW <= whirBreakpoints.mobile) {//WAP
                        // 移除之前可能存在的事件监听器，防止重复绑定
                        videoInner.find(".open-video").off('click').on("click", function () {
                            if (publicSwiperVideo && publicSwiperVideo.autoplay) {
                                publicSwiperVideo.autoplay.stop();
                            }
                            videoInner.addClass("active");

                            // 使用jQuery查找视频元素，避免getElementById可能的null问题
                            var videoElement = videoInner.find("video")[0];
                            if (videoElement) {
                                videoElement.play();
                                videoElement.muted = false;

                                // 移除之前可能存在的ended事件监听器
                                $(videoElement).off('ended').on('ended', function () {
                                    publicSwiperVideo.slideNext();
                                    publicSwiperVideo.autoplay.start();
                                    videoInner.removeClass("active");
                                });
                            }
                        });
                    } else {//PC
                        if (publicSwiperVideo && publicSwiperVideo.autoplay) {
                            publicSwiperVideo.autoplay.stop();
                        }

                        // 使用jQuery查找视频元素，避免getElementById可能的null问题
                        var videoElement = videoInner.find("video")[0];
                        if (videoElement) {
                            videoElement.play();

                            // 移除之前可能存在的ended事件监听器
                            $(videoElement).off('ended').on('ended', function () {
                                publicSwiperVideo.slideNext();
                                publicSwiperVideo.autoplay.start();
                            });
                        }
                    }
                }
                clearTimeout(t);
            }, 300);
        }
    },
    /**
     * 为轮播项添加视频元素
     * @param {string} m - 轮播项选择器
     * @returns {void}
     */
    addVideo: function (m) {
        $(m).each(function (e) {
            var videoInner = $(this).find(".video-inner");
            if (videoInner.length > 0) {
                var _files = '';
                var files_desktop = videoInner.data("files_desktop");
                var files_mobile = videoInner.data("files_mobile");
                if (window.innerWidth > whirBreakpoints.mobile) {
                    _files = files_desktop;
                } else {
                    _files = files_mobile ? files_mobile : files_desktop;
                }
                //添加视频
                videoInner.append("<div class='video-box'><video src='" + _files + "' x-webkit-airplay='true' x5-video-player-type='h5' x5-video-player-fullscreen='true' webkit-playsinline='true' playsinline='true'  muted></video></div>");
                //添加移动端播放按钮
                videoInner.append("<div class='open-video'></div>");
            }
        })
    }
}