// 断点配置
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);}); 
    },
    backBot: function () {
        //滚动到底部
        var offset = 200,
		offset_opacity = 1200,
		scroll_top_duration = 1000,
		$back_to_bot = $('.fix-right');
        $(window).scroll(function(){
            ( $(this).scrollTop() > offset ) ? $back_to_bot.addClass('up') : $back_to_bot.removeClass('up');
                var win_top = $(this).scrollTop();

        });
        $('.back-bottom').click(function () { $('html,body').animate({ scrollTop: $('footer').offset().top }, 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 () {
        //顶部滚动及滑过效果
        whirPublic.config.headerUp();

        $("#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");
                    // $this.find(".sub").slideDown().siblings().find(".sub").slideUp();
                }, 300));
            }, function () {
                var $this = $(this);
                $this.removeClass('aon');
                $("#m" + m).addClass('aon')
                clearTimeout($this.data('hoverTimer'));
                $this.data('hoverTimer', setTimeout(function () {
                    $this.removeClass("show");
                    // $this.find(".sub").slideUp();
                }, 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") + ")");

        });
        $(".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");
        });
        $(".pat-menu dd").each(function(){
            $(this).children('a').click(function(){
                $(this).parent('dd').toggleClass("on")
            })
            $(this).find(".cat-op").click(function(){
                $(this).parent('dd').toggleClass("on")
            })
        })
        //滑过显示阴影效果
		$(".itemhover").hover(function(){
            $(this).addClass("activehover");
                },function(){
                        $(this).removeClass("activehover");
            });
            $(".itemhover2").hover(function(){
                $(this).addClass("activehover2");
        },function(){
                $(this).removeClass("activehover2");
        });
        $(".main-nav li").each(function(){
                if($(this).find('.sub').find('a').length >0){
                    $(this).children('span').find("a").attr('href','javascript:void(0);')
                }
                $(this).find("span").click(function(){
                    $(this).parents("li").toggleClass('aon')
                    $(this).parents("li").siblings().removeClass('aon')
                    $(this).siblings().find("dd").removeClass("on")
                })
            })

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

        //内页BANNER
        $(".pageBan").addClass("on");

        //顶部
        whirPublic.config.top();
        
        //判断无图
        $(document).ready(function() {
            // 处理所有图片及对应的a标签
            $(document).on('error', 'img', function() {
                const $img = $(this);
                const $a = $img.closest('a[data-fancybox]'); // 找到对应的Fancybox链接
                // 避免无限循环
                if (!this.src.includes('no-pic.svg')) {
                    // 更新图片src
                    this.src = noPicPath;
                    $img.addClass('no-pic');
                    // 同步更新a标签的href
                    if ($a.length) {
                        $a.attr('href', noPicPath);
                    }
                }
            });
            // 初始化检查：处理空src的图片和a标签
            $('img').each(function() {
                const $img = $(this);
                const $a = $img.closest('a[data-fancybox]');
                // 处理空src或已加载失败的图片
                if ((!this.src || this.src.trim() === '') || 
                    (this.complete && (this.naturalWidth === 0 || this.naturalHeight === 0))) {
                    // 直接设置无图
                    this.src = noPicPath;
                    $img.addClass('no-pic');
                    // 同步a标签href
                    if ($a.length) {
                        $a.attr('href', noPicPath);
                    }
                }
            });

        });
        //返回顶部
        whirPublic.config.backTop();
        //滚动到底部
        whirPublic.config.backBot();

        //右侧导航
         $(".fix-right .switch").click(function(){
            $(".fix-right").toggleClass("show");
         })
        // whirPublic.open.hoverCss('.fix-right li', 'show');

        //自定义下拉
        $(".select-txt").each(function () {
            var _this = $(this);
            _this.click(function (e) {
            _this.toggleClass("show").siblings().removeClass("show");
            });
            // 处理单选（hover类）
            _this.find(".hover li").click(function () {
                $(this).toggleClass("cur").siblings().removeClass("cur");
                var text = $(this).text();
                _this.find(".selected").text(text);
                _this.addClass("on");
            });
        });
        $("body").on('click', function (e) {
        if (!$(e.target).closest('.select-txt').length) {
            $('.select-txt').removeClass('show');
            }
        });

        //底部栏目菜单
        $("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");
        });

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

        //详情页
        $(".news-page dl").each(function() {
           var myhref = $(this).find("a").attr("href");
           if (myhref == "#") {
                            $(this).find("a").addClass("none");
                            $(this).find("a").removeAttr("href");
        }
        });
        $(".news-details .edit-info p").each(function() {
            if ($(this).has("img").length > 0) {
                            $(this).addClass("tc").css("text-indent","0em");
            }
        });
    },
    navMenu(nav){
        $("#nav"+nav).addClass("aon");
    },
    index: function () {

         $(".home-card .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");
            }
         );
         $(".home-card .item").each(function(){
            var _this=$(this);
            if($(_this).find("dd").length>3){
                _this.addClass("moreitem")
            }
         })
         //end

        
    },
    home: function () {

		//LEFT
		var timer = null;
		var i = 0;
		$(function ($) {
						$(window).on("resize", function (e) {
										i++;
										clearTimeout(timer);
										timer = setTimeout(function () {
														var links = $("#load-carousel").data("url")
														// console.log(links);
														$("#load-carousel").load(links);
										}, 1000)
						}).trigger("resize");
		});
		//PARTNER
		whirPublic.config.generateSplideSections(homelogo);

		$(".load-partner .splide").each(function (e) {
						var _this = $(this)[0]
						if (e % 2 === 0) {
										var z = 0.5
						} else {
										var z = -0.5
						}
						new Splide(_this, {
										speed: 600,
										arrows: false,
										pagination: false,
										type: 'loop',
										drag: 'free',
										focus: 'center',
										perPage: 6,
										breakpoints: {
														1024: {
																		perPage: 5,
														},
														640: {
																		perPage: 3,
														},
										},
										autoScroll: {
														speed: z,
										},
						}).mount(window.splide.Extensions);
		})
	},
	generateSplideSections(logos) {
			var total = logos.length;
			var groups = [];

			if (total < 12) {
							groups.push(logos);
			} else {
							var groupSize = Math.ceil(total / 4);
							for (var i = 0; i < total; i += groupSize) {
											groups.push(logos.slice(i, i + groupSize));
							}
			}

			var mainContainer = $(".load-partner");

			groups.forEach(function (group) {
							var section = document.createElement('section');
							section.classList.add('splide');

							var slider = document.createElement('div');
							slider.classList.add('splide__slider');

							var track = document.createElement('div');
							track.classList.add('splide__track');

							var list = document.createElement('ul');
							list.classList.add('splide__list');

							group.forEach(function (logo) {
											var listItem = document.createElement('li');
											listItem.classList.add('splide__slide');

											var img = document.createElement('img');
											img.src = logo.img;
											listItem.appendChild(img);
											list.appendChild(listItem);
							});

							track.appendChild(list);
							slider.appendChild(track);
							section.appendChild(slider);
							mainContainer.append(section);
			});
	},
	partner() {
	},
    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")
                }
            });
        });
    }
}
// 实现tabSwitch函数
function tabSwitch(tabContainer, tabItem, content, activeClass, animation) {
        // 设置默认值
        activeClass = activeClass || 'on';
        animation = animation || 'animated fadeIn';
        
        $(tabContainer).each(function () {
            var $tabSlide = $(this);
            var $items = $tabSlide.find(tabItem);
            var $contents = $tabSlide.find(content);
            
            // 初始化
            $items.first().addClass(activeClass);
            $contents.first().removeClass("nones").addClass(animation);
            
            // 使用事件委托处理点击
            $tabSlide.on("click", tabItem, function() {
                var $clickedItem = $(this);
                var index = $clickedItem.index();
                
                // 更新标签状态
                $items.removeClass(activeClass);
                $clickedItem.addClass(activeClass);
                
                // 更新内容区域
                $contents.addClass("nones").removeClass(animation);
                $contents.eq(index)
                    .removeClass("nones")
                    .addClass(animation);
            });
        });
}
// 实现tabSwitch切换内容和图片函数
function imageTabSwitch(tabContainer, tabItem, content, imageContainer, imageItem, activeClass) {
        // 设置默认值
            activeClass = activeClass || 'on';
            
            $(tabContainer).each(function () {
                var $tabSlide = $(this);
                var $items = $tabSlide.find(tabItem);
                var $contents = $tabSlide.find(content);
                var $images = $tabSlide.find(imageItem);

                // 初始化 - 默认第一个为选中状态
                $items.first().addClass(activeClass);
                $contents.first().removeClass('nones');
                $images.first().addClass('active');
                
                // 使用事件委托处理点击
                $tabSlide.on("click", tabItem, function() {
                    var $clickedItem = $(this);
                    var index = $clickedItem.index();
                    
                    // 更新标签状态
                    $items.removeClass(activeClass);
                    $clickedItem.addClass(activeClass);
                    
                    // 更新内容区域
                    $contents.addClass("nones");
                    $contents.eq(index).removeClass("nones");
                    
                    // 更新图片显示
                    $images.removeClass("active");
                    $images.eq(index).addClass("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>");
            }
        })
    }
}