// 断点配置
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;
var delayCount = 1000;

whirPublic.config = {
    backTop: function () {
        //返回顶部
        $('.back-top').click(function () {
            $('html,body').animate({ scrollTop: 0 }, 800);
        });
    },
    top: function () {
        $("#m" + m).addClass('aon');
        // 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);
            }
        );

        //打开搜索
        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(".p-menu").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") + ")");

        });
        $(".wap-op").click(function () {
            $(this).parents("li").toggleClass("wap-show");
            $(this).parents("li").siblings().removeClass("wap-show");
        });

        $(".main-nav").mouseleave(function () {
            $(this).find("li").removeClass("show");
        });

    },
    bottom: function () {
        //顶部
        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');

        //底部栏目菜单
        $("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);
        });
		
///////////控制浏览器缩放
$("header," +
".home-ban .txt," +
".home-about .container," +
".home-prod," +
".home-gobal .txt," +
".home-project," +
".home-factory .container," +
".home-factory .factory," +
".home-esg," +
".home-news," +
"main").addClass("zoombox");

function asres(){
	var ww = window.devicePixelRatio;
	console.log(ww);
	//分辨率125%  100/125=0.8
	//分辨率125%  100*125=0.8  
	var _zoombox = $(".zoombox")

	//分辨率150%
	if(ww==1.50){
		_zoombox.css('zoom', 150/150);
	}
	if(ww==1.25){
		_zoombox.css('zoom', 125/125);
	}
    if (ww > 1 && ww < 1.25) {
        _zoombox.css('zoom', 100/100);
    }
	if(ww==1){
		_zoombox.css('zoom', 1);
	}   
};
 
$(function(){
	$(window).resize(function(){
        asres();
	});
	asres(); 
})
//////////
		
		
    },
    navMenu(nav){
        $("#nav"+nav).addClass("aon");
    },
	MarqueeScroll: function(){	
        $(document).ready(function () {
            let currentDirection = 'left';
            let scrollAmount = 200; // 设置默认滚动速度
            // 初始化 liMarquee 插件
            let marquee = initLiMarquee(currentDirection, scrollAmount);

            // 处理 prev 箭头点击事件
            $('.MarqueeScroll .arrows-prev').click(function () {
                currentDirection = 'left';
				scrollAmount ='200';
                // 销毁当前实例并重新初始化
                marquee.liMarquee('destroy');
                marquee = initLiMarquee(currentDirection, scrollAmount);
            });

            // 处理 next 箭头点击事件
            $('.MarqueeScroll .arrows-next').click(function () {
                currentDirection = 'right';
				scrollAmount ='200';
                // 销毁当前实例并重新初始化
                marquee.liMarquee('destroy');
                marquee = initLiMarquee(currentDirection, scrollAmount);
            });

            function initLiMarquee(direction, amount) {
                return $('.MarqueeScroll .MarqueeMain').liMarquee({
                    loop: -1,
                    hoverstop: true,
                    direction: direction,
                    scrollamount: amount // 添加 scrollamount 配置
                });
            }
        });

	},
	innerPageFullpage: function(){ 
         new fullpage('#innerPageFullPage', {
            responsiveWidth:1200,
            v2compatible: true,
			//navigation: true,
			anchors: ['page0', 'page1', 'page2', 'page3','page4', 'page5', 'page6', 'page7', 'page8', 'page9'],
            afterLoad: function (anchorLink, index) {
                if (index > 1) {
                  $("header").addClass("dark-style").removeClass("light-style");
                  $("header").off("hover");
                  isDark = true;
                }else{
                    $("header").removeClass("dark-style").addClass("light-style");
                    isDark = false;
                }
               
				if($("section#bottom").is('.active')){		
					$(this).prev().addClass("endSection")
				 }else{
					$(this).prev().removeClass("endSection")
				 }
			   
            },
        })
    },
    homeFullpage: function(){ 
         new fullpage('#fullPage', {
            responsiveWidth:1200,
            v2compatible: true,
            afterLoad: function (anchorLink, index) {
                if (index > 1) {
                  $("header").addClass("dark-style").removeClass("light-style");
                  $("header").off("hover");
                  isDark = true;
                }else{
                    $("header").removeClass("dark-style").addClass("light-style");
                    isDark = false;
                }
                if(index==1){
                    if($(".home-ban .swiper-slide-active").find("video")[0]){
                        $(".home-ban .swiper-slide-active").find("video")[0].play();
                    }
                }
                $(".home-main").find("video").each(function(){
                    $(this)[0].play();
                })
                if(index==3){
                    // 第三屏时启动 3D 轮播自动播放
                    const carousel = $('.carousel');
                    if (carousel.length > 0) {
                        const home3dState = carousel.data('home3dState');
                        if (home3dState && home3dState.startAutoStep) {
                            home3dState.startAutoStep();
                        }
                    }
                }               
                showTips()                 
            },
            afterRender:function() { 
                //banner 轮播
                whirPublic.video.banner('.home-ban');
        
                var cardNum=$(".whatwedo--card").length
                if(cardNum<7){
                    $(".carousel").hide();
                    return
                }
                if(cardNum=7){
                    $(".whatwedo--cards").append($(".whatwedo--cards").html())
                    whirPublic.config.home3d();
                }
            }
        })
    },
    home: function () {
        //fullpage
        whirPublic.config.homeFullpage();
        //home-gobal 地图
        $(".home-gobal .map  dd").eq(0).addClass("active");
        $(".home-gobal .map  dd").hover(function () {
            var _this = $(this)
            _this.addClass("active").siblings().removeClass("active");
        });
        //home-project
		$(function(){
			if($(window).width() >= 768){        
				$(".home-project .cate-list").each(function(){
					var _this=$(this);
					var num=_this.find(".item").length;
					if(num<=6){
					var licopy=_this.html()
					_this.append(licopy);
					}
				});
			}
			$('.home-project .cate-list').liMarquee({
				loop: -1,
				hoverstop: true,
			});
		});
//        new Swiper(".home-project .cate-list .swiper", {
//            slidesPerView: 4,
//            speed:500,
//            loop:true,
//            autoplay: {
//                delay: 3000,
//                disableOnInteraction: false,
//                pauseOnMouseEnter: true,
//            },
//            breakpoints: {
//                1024: {
//                    slidesPerView: 6,
//                }
//            },
//        });
        $(".home-project .table-2d .item").hover(function () {
            var _this = $(this)
            _this.addClass("active").removeClass("no-active").siblings().removeClass("active").addClass("no-active");
        }, function () {
            var _this = $(this)
            _this.removeClass("active no-active").siblings().removeClass("no-active");
        });
        //
        new Swiper('.home-news .swiper', {
            loop: true,
            loopAdditionalSlides: 3,
            slidesPerView: 1,
            spaceBetween: 10,
            breakpoints: {
                480: {
                    spaceBetween: 30,
                    slidesPerView: 2,
                },
                1024: {
                    spaceBetween: 50,
                    slidesPerView: 3,
                },
            },
            autoplay: {
                delay: delayCount,
                disableOnInteraction: false,
                pauseOnMouseEnter: true,
            },
        });

        // 初始化鼠标跟随效果
        whirPublic.config.mouse();
    },
    mouse() {
        // 鼠标跟随效果 - 仅在桌面端启用
        if (window.innerWidth <= whirBreakpoints.mobile) {
            return; // 移动端不启用鼠标跟随效果
        }

        const $swiperMain = $('.swiper-main');
        const $mouse = $('.mouse');

        if ($swiperMain.length && $mouse.length) {
            // 设置初始状态
            $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) {
                    // 移动端时隐藏鼠标图标
                    $mouse.css('opacity', '0');
                }
            });
        }
    },
    industry(id) {
        if (id) {
            var oft = $("#item-" + id).offset().top - $("header").outerHeight();
            $("html,body").animate({ scrollTop: oft }, 10);
        }

        $(".item").each(function () {
            var _slide = $(this).find(".swiper"), _prev = $(this).find(".arrows-prev"),
                _next = $(this).find(".arrows-next")
                , _swiper_slide = _slide.find(".swiper-slide").length
            if (_swiper_slide <= 3) {
                _slide.find(".swiper-wrapper").append("<div class='swiper-slide'><div class='more'></div></div>")
				_slide.find(".swiper-wrapper").parent().parent().addClass("no-swiper")
            }else{
            new Swiper(_slide[0], {
                slidesPerView: 4,
                spaceBetween: 10,
				loop: true,
				autoplay: {
					delay: delayCount,
					disableOnInteraction: false,
					pauseOnMouseEnter: true,
				},
                navigation: {
                    nextEl: _next[0],
                    prevEl: _prev[0],
                }
            })
			}
        })
		
		whirPublic.config.innerPageFullpage();
    },
    product(name) {
        if (name == 'home') {
            //列表
            const items = document.querySelectorAll('.item');
            for (let i = 0; i < items.length; i++) {
                // 每4个元素选中第0和第3个，形成0,3,4,7,8,11,12,15,16...的规律
                if ((i % 4 === 0) || (i % 4 === 3)) {
                    items[i].classList.add('long');
                }
            }
        }
        if (name == 'info') {
            //详情
            $(".current span").text($(".all-title").text());
            //图集
            if($(".swiper-gallery .swiper-slide").length!=0){
                new Swiper('.swiper-gallery .swiper',{
                    watchSlidesProgress: true,
                    slidesPerView: 'auto',
                    centeredSlides: true,
                    loop: true,
                    loopedSlides: 5,
                    autoplay: {
						delay: delayCount,
						disableOnInteraction: false,
						pauseOnMouseEnter: true,
                    },
                    navigation: {
                        nextEl: '.swiper-gallery .arrows-next',
                        prevEl: '.swiper-gallery .arrows-prev',
                    },
                    on: {
                        progress: function(progress) {
                            // 动态计算平移距离 - 响应式适配
                            var swiperWidth = this.width;
                            var slideWidth = this.slides[0].offsetWidth;
                            
                            // 基于1400px宽度时840px间距的比例计算
                            // 840 / 1400 = 0.6，所以使用swiper宽度的60%作为基础距离
                            var baseTranslateDistance = swiperWidth * 0.42;
                            
                            for (i = 0; i < this.slides.length; i++) {
                                var slide = this.slides.eq(i);
                                var slideProgress = this.slides[i].progress;
                            
                                var translateDistance = slideProgress * baseTranslateDistance;
                                var translate = translateDistance + 'px';
                                var scale = 1 - Math.abs(slideProgress) * 0.16;
                                var rotateY = slideProgress * 5;
                            
                                // 确保 position 和 zIndex 生效
                                slide.css({
                                    'position': 'relative',
                                    'z-index': 1000 - Math.abs(Math.round(slideProgress * 100)),
                                    'opacity': Math.abs(slideProgress) > 3 ? 0 : 1,
                                    'transform': 'translate3d(' + translate + ', 0, 0) scale(' + scale + ') rotateY(' + rotateY + 'deg)'
                                });
                            }
                        },
                        setTransition: function (swiper, transition) {
                            for (var i = 0; i < this.slides.length; i++) {
                                var slide = this.slides.eq(i)
                                slide.transition(transition);
                            }
                        }
                    }
                });
            }else{
                $(".swiper-gallery").hide();
            }

            //其他产品
			whirPublic.config.MarqueeScroll();



//            new Swiper('.relate-main .list .swiper', {
//                slidesPerView: 2,
//                spaceBetween: 10,
//				loop: true,
//				autoplay: {
//					delay: 4000,
//					disableOnInteraction: false,
//					pauseOnMouseEnter: true,
//				},
//                navigation: {
//                    nextEl: '.relate-main .arrows-next',
//                    prevEl: '.relate-main .arrows-prev',
//                },
//                breakpoints: {
//                    1024: {
//                        slidesPerView: 3,
//                        spaceBetween: 40
//                    }
//                }
//            });
            //feedback
            whirPublic.config.feedback();
        }
    },
    feedback:function(){
        $(".feedback dd").each(function () {
            var tips = $(this).find(".label-name");
            var input = $(this).find(".form-input");

            input.val("");
            input.focus(function () {
                tips.addClass('cg');
            });
            input.blur(function () {
                var val = $(this).val();
                if (val == "") {
                    tips.removeClass('cg');
                }
            });
            tips.click(function () {
                $(this).addClass('cg');
                $(this).next(".form-input").focus();
            });
        });
    },
    engry(name){
        if(name=='yanfa'){
            
			whirPublic.config.innerPageFullpage();
			
			whirPublic.config.flex_tab(".engry-tab .item");
			

            var swiper = new Swiper(".engry-slider .swiper-small", {
                slidesPerView: 4,
                freeMode: true,
                watchSlidesProgress: true,
              });
              var swiper2 = new Swiper(".engry-slider .swiper-big", {
                spaceBetween: 10,
				loop: true,
                speed: 2000,
				autoplay: {
					delay: delayCount,
					disableOnInteraction: false,
					pauseOnMouseEnter: true,
				},
                thumbs: {
                  swiper: swiper,
                },
              });
			  

		$(function(){
		
			if($(window).width() >= 768){        
				$(".engry-partner .father .group").each(function(){
					var _this=$(this);
					var num=_this.find(".item").length;
					if(num<=6){
					var licopy=_this.html()
					_this.append(licopy);
					}
				});
			}

			$('.engry-partner .father .group:nth-child(odd)').liMarquee({
				loop: -1,
				hoverstop: true,
			});
			$('.engry-partner .father .group:nth-child(even)').liMarquee({
				loop: -1,				
				hoverstop: true,
				direction: 'right',
			});
		});

			  

        }
        if(name=='design'){
            whirPublic.config.flex_tab(".design-four .item");
        }
        if(name=='ai'){
            whirPublic.open.videoOpen('.btn-play', 'inside', '.video-area');
			
        // 重新组织列表结构
        $(document).ready(function() {
            // 选择所有item元素
            var $items = $('.machine-path .list .item');
            var $list = $('.machine-path .list');
            
            // 清空原有内容
            $list.empty();
            
            // 每5个item组成一组
            for (var i = 0; i < $items.length; i += 5) {
                var $group5 = $('<div class="items-5"></div>');
                
                // 获取当前组的5个item
                var groupItems = $items.slice(i, i + 5);
                
                // 每2个item组成一个子组
                for (var j = 0; j < groupItems.length; j += 2) {
                    var $group2 = $('<div class="items-2"></div>');
                    
                    // 获取当前子组的2个item
                    var subGroupItems = groupItems.slice(j, j + 2);
                    
                    // 将item添加到子组中
                    subGroupItems.each(function() {
                        $group2.append($(this));
                    });
                    
                    // 将子组添加到5个一组的大组中
                    $group5.append($group2);
                }
                
                // 将大组添加到列表中
                $list.append($group5);
            }
        });
        //swiper
//        new Swiper(".machine-swiper .swiper",{
//            watchSlidesProgress: true,
//            slidesPerView: 2,
//            spaceBetween: 20,
//			loop: true,
//            autoplay: {
//				delay: delayCount,
//				disableOnInteraction: true,
//				pauseOnMouseEnter: true,
//            },
//            navigation: {
//                nextEl: ".machine-swiper .arrows-next",
//                prevEl: ".machine-swiper .arrows-prev",
//            },
//            breakpoints: {
//                1024: {
//                    slidesPerView: 4
//                }
//            }
//        })

			whirPublic.config.MarqueeScroll();




		
        }

        if(name=='shuzhi'){
            $(".step-items .swiper-slide").each(function(i){
               if(i%2==1){
                 $(this).addClass("odd");
               }
            });
          var tabswiper= new Swiper(".step-items .swiper",{
                spaceBetween: 10,
				loop: true,
				autoplay: {
					delay: delayCount,
					disableOnInteraction: false,
					pauseOnMouseEnter: true,
				},
                on:{
                    slideChange: function () {
                        var index = this.realIndex;
                        $(".swiper-tab .tab").eq(index).addClass("active").siblings().removeClass("active");
                    }
                }
           });
//           $(".swiper-tab .tab").hover(function () { 
//            var index = $(this).index();
//               tabswiper.slideToLoop(index, 500, false);
//           });
			$(".swiper-tab .tab").hover(
				function () {
					// 鼠标悬停时暂停自动播放
					tabswiper.autoplay.stop();
					var index = $(this).index();
					tabswiper.slideToLoop(index, 500, false);
				},
				function () {
					// 鼠标移开时恢复自动播放
					tabswiper.autoplay.start();
				}
			);
			
			whirPublic.config.innerPageFullpage();
			
        }
    },
    flex_tab:function(name){
            $(name).hover(function () {
                var _this = $(this)
                _this.addClass("active").removeClass("no-active").siblings().removeClass("active").addClass("no-active");
            });  
            $(name).eq(0).addClass("active").siblings().addClass("no-active");        
    },
    about:function(){
        whirPublic.open.videoOpen('.btn-play', 'inside', '.video-area');
		
		whirPublic.config.innerPageFullpage();
        
        $('.about-history .swiper-con .swiper-slide').each(function(){
            var $pre = $(this).find("pre");
            var text = $pre.text();
            // 按换行分割，兼容\r\n和\n
            var lines = text.split(/\r?\n/).filter(function(line){ return $.trim(line) !== ""; });
            if(lines.length > 0){
                var $dl = $('<dl></dl>');
                lines.forEach(function(line){
                    $dl.append($('<dd></dd>').text(line));
                });
                $pre.after($dl);
            }
            $pre.remove();
        });

        var swiper = new Swiper(".about-history .swiper-year", {
            slidesPerView: 3,
            freeMode: true,
            watchSlidesProgress: true,
            
            breakpoints: {
                1025: {
                    slidesPerView: 8,
                }
            },
            
          });
          var swiper2 = new Swiper(".about-history .swiper-con", {
            spaceBetween: 10,
			loop: true,
			autoplay: {
				delay: delayCount,
				disableOnInteraction: false,
				pauseOnMouseEnter: true,
			},
            navigation: {
              nextEl: ".about-history .arrows-next",
              prevEl: ".about-history .arrows-prev",
            },
            thumbs: {
              swiper: swiper,
            },
          });
          $(".about-history .swiper-year .swiper-slide").click(function(){
            swiper2.autoplay.stop();
          })
          $(".about-history .swiper-year .swiper-slide").mouseleave(function(){
              swiper2.autoplay.start();
          })
          

          if($(".about-honor .swiper-slide").length!=0){
            new Swiper('.about-honor .swiper',{
                watchSlidesProgress: true,
                slidesPerView: 'auto',
                centeredSlides: true,
                loop: true,
               // loopedSlides: 21,
				autoplay: {
					delay: delayCount,
					disableOnInteraction: false,
					pauseOnMouseEnter: true,
					reverseDirection: true,//从右到左
				},
                navigation: {
                    nextEl: '.about-honor .arrows-prev',//特意用相反方向
                    prevEl: '.about-honor .arrows-next',//特意用相反方向
                },
                on: {
                    progress: function(progress) {
                        // 动态计算平移距离 - 响应式适配
                        var slideWidth = this.slides[0].offsetWidth;
                        console.log(slideWidth);
                        
                        for (i = 0; i < this.slides.length; i++) {
                            var slide = this.slides.eq(i);
                            var slideProgress = this.slides[i].progress;
                            
                            // 使用更严格的判断条件，确保中心图绝对不缩放不平移
                            var isCenter = Math.abs(slideProgress) < 0.1; // 使用容差范围判断中心位置
                            
                            var scale, translateDistance;
                            
                            if (isCenter) {
                                // 中心图：不缩放，不平移
                                scale = 1;
                                translateDistance = 0;
                            } else {
                                // 非中心图：应用缩放和平移效果
                                var absProgress = Math.abs(slideProgress);
                                var startScale = 0.57;
                                var decrement = 0.06;
                                
                                // 计算缩放：从0.57开始，每次递减0.06
                                scale = startScale - (absProgress - 1) * decrement;
                                scale = Math.max(scale, 0.15); // 确保最小缩放比例
                                
                                // 计算平移距离
                                var baseTranslateDistance = slideWidth * (800 / 569);
                                var increment = slideWidth * (654 / 569);
                                translateDistance = baseTranslateDistance + (absProgress - 1) * increment;
                                
                                // 左边为负值，右边为正值
                                if (slideProgress < 0) {
                                    translateDistance = -translateDistance;
                                }
                            }
                            
                            var translate = translateDistance + 'px';

                            // 确保 position 和 zIndex 生效
                            slide.css({
                                'position': 'relative',
                                'z-index': 1000 - Math.abs(Math.round(slideProgress * 100)),
                                'transform': 'translate3d(' + translate + ', 0, 0) scale(' + scale + ')'
                            });
                        }
                    },
                    setTransition: function (swiper, transition) {
                        for (var i = 0; i < this.slides.length; i++) {
                            var slide = this.slides.eq(i)
                            slide.transition(transition);
                        }
                    }
                }
            });
        }else{
            $(".about-honor").hide();
        }
    },
    joinUs:function () { 
        new Swiper('.joinUs-life .swiper', {
            slidesPerView: 2,
            spaceBetween: 10,
			loop: true,
			autoplay: {
				delay: delayCount,
				disableOnInteraction: false,
				pauseOnMouseEnter: true,
			},
            navigation: {
                nextEl: '.joinUs-life .arrows-next',
                prevEl: '.joinUs-life .arrows-prev',
            },
            breakpoints: {
                1024: {
                    slidesPerView: 3,
                    spaceBetween: 28,
                },
            }
        });
    },
    layout:function(){
        if($(".layout-list .item").length==0){
            $(".layout-list").hide();
        }
    },
    invest:function(name,id){
       if(name=="activity"){
        $("#th" + id).addClass("aon")
       }
       if(name == "report"){
        $(".invest-report .item").each(function(){
            var n=$(this).find(".list").find("dd").length
            $(this).css("--n",n);
            if(n>=1){
                $(this).addClass("has-hover");
            }
        })
       }
       if(name == "notice"){
        $("#th"+ id).addClass("aon")
       }
    },
    home3d:function(){
        gsap.registerPlugin(ScrollTrigger, Draggable, InertiaPlugin);

        const $carousel = $('.carousel');
        const $cardsWrap = $('.whatwedo--cards');
        const dataKey = 'home3dState';

        if ($carousel.length === 0 || $('.whatwedo--card').length === 0) return;

        // 如已存在旧实例，先清理，防止重复事件与动画
        const prevState = $carousel.data(dataKey);
        if (prevState) {
            try { prevState.spinIntro && prevState.spinIntro.kill(); } catch (e) {}
            try { prevState.draggables && prevState.draggables.forEach(d => d && d.kill && d.kill()); } catch (e) {}
            try { prevState.autoStepTimer && clearInterval(prevState.autoStepTimer); } catch (e) {}
        }
        $(window).off('resize.home3d');
        $('.carousel .arrows-prev').off('click.home3d');
        $('.carousel .arrows-next').off('click.home3d');
        $cardsWrap.off('.home3d');

        // 基本设置（保留你的变量名/计算方法）
        let wid = $carousel.width();
        let cards = gsap.utils.toArray('.whatwedo--card');
        let totalCards = cards.length;
        let anglePerCard = 360 / totalCards;
        let dragDistancePerRotation = 3000; // 拖拽多少像素等于一圈（可调）
        let proxy = document.createElement('div');
        let cardsWid = wid > 1920 ? 1920 : wid;

        // 配置参数
        const config = {
            ease: "power1.in",
            enableDrag: false,
            pauseOnHover: true,
            enableAutoStep: false  // 改为 false，默认不自动播放
        };

        // 计算 transformOrigin（保留你的计算）
        let demical = wid < 415 ? 0.76 : (totalCards > 6 ? 0.44 : 0.38);
        let transformOrigin = wid > 414 && wid < 768 
            ? `50% 50% ${-wid * demical * 1.5}px` 
            : `50% 50% ${-cardsWid * demical * 1.5}px`;

        // 初始 baseAngles，并把 transformOrigin 设到每张卡
        const baseAngles = [];
        cards.forEach((card, i) => {
            baseAngles[i] = i * anglePerCard;
            gsap.set(card, {
                rotationY: baseAngles[i],
                transformOrigin: transformOrigin,
                z: 0
            });
        });

        // 性能优化：为每张 card 建立 quickSetter
        const setters = cards.map(card => gsap.quickSetter(card, 'rotationY', 'deg'));

        // 全局角度（累加，不做 0~360 限制）
        const rotObj = { angle: 0 };

        // 渲染函数：把 masterAngle 应用到所有卡片并更新 active
        function render() {
            for (let i = 0; i < totalCards; i++) {
                setters[i](baseAngles[i] + rotObj.angle);
            }
            updateActiveCard();
        }

        // active 判定：中间 + 左右各两张（共 5 张）
        function updateActiveCard() {
            const maxSteps = 2; // 左右各多少张，2 => 共 5 张
            for (let i = 0; i < totalCards; i++) {
                // 计算当前卡片的角度到 0° 的最短差值（-180..180）
                let angle = baseAngles[i] + rotObj.angle;
                let norm = ((angle % 360) + 360) % 360; // 0..360
                if (norm > 180) norm -= 360; // -180 .. 180

                // 以 steps 计算距离（四舍五入到最近张）
                let stepsAway = Math.round(Math.abs(norm) / anglePerCard);

                if (stepsAway <= maxSteps) {
                    $(cards[i]).addClass('active');
                } else {
                    $(cards[i]).removeClass('active');
                }
            }
        }

        // 进入视图的启动动画
        let spinIntro = gsap.timeline({
            scrollTrigger: {
                trigger: '.whatwedo--cards',
                start: 'top 70%',
                end: 'bottom top',
                scrub: false,
                toggleActions: 'play resume play play'
            }
        });

        // spinIntro
        //     .fromTo('.whatwedo--cards', { scale: 0.5 }, { scale: 1, duration: 1.2, ease: config.ease })

        // 初次渲染
        render();

        // 左右按钮（防重复绑定）

        $('.carousel .arrows-prev').on('click.home3d', function () {
            gsap.to(rotObj, {
                angle: '-=' + anglePerCard,
                duration: 0.3,
                ease: config.ease,
                overwrite: 'auto',          // 新增，防叠加
                onUpdate: render
            });
        });


		$('.carousel .arrows-next').on('click.home3d', function () {
            gsap.to(rotObj, {
                angle: '+=' + anglePerCard,
                duration: 0.3,
                ease: config.ease,
                overwrite: 'auto',          // 新增，防叠加
                onUpdate: render
            });
        });

        // 自动轮播：每3秒切换一次，等同点击右侧按钮
        let autoStepTimer = null;
        function startAutoStep() {
            if (autoStepTimer) return;
            autoStepTimer = setInterval(function(){
                // 保持与点击右按钮一致的动画参数
                gsap.to(rotObj, {
                    angle: '+=' + anglePerCard,
                    duration: 0.8,
                    ease: config.ease,
                    overwrite: 'auto',          // 新增，防叠加
                    onUpdate: render
                });
            }, 3000);
        }
        function stopAutoStep() {
            if (autoStepTimer) {
                clearInterval(autoStepTimer);
                autoStepTimer = null;
            }
        }
        // 避免与手动切换冲突：手动点击后重置计时（开启自动轮播时才生效）
        if (config.enableAutoStep) {
            $('.carousel .arrows-prev, .carousel .arrows-next').on('click.home3d', function(){
                stopAutoStep();
                var lst=setTimeout(function(){
                    startAutoStep();
                    clearTimeout(lst);
                }, 2000);
            });
            // startAutoStep(); // 注释掉这行，不自动启动
        }

        // 悬停暂停/离开恢复（可配置开关）
        if (config.enableAutoStep && config.pauseOnHover) {
            $cardsWrap.on('mouseenter.home3d', function(){
                stopAutoStep();
            });
            $cardsWrap.on('mouseleave.home3d', function(){
                startAutoStep();
            });
        }

        // 拖拽控制（像素映射到度数：dragDistancePerRotation px -> 360deg）
        let draggables = null;
        if (config.enableDrag) {
            let startAngleOnPress = 0;
            draggables = Draggable.create(proxy, {
                trigger: '.whatwedo--cards',
                type: 'x',
                inertia: true,
                allowNativeTouchScrolling: true,
                onPress() {
                    gsap.killTweensOf(rotObj);
                    autoTween.pause();
                    startAngleOnPress = rotObj.angle;
                },
                onDrag() {
                    const delta = (this.x - this.startX); // 拖动距离（像素）
                    rotObj.angle = startAngleOnPress + (delta / dragDistancePerRotation) * 360;
                    render();
                },
                onThrowUpdate() {
                    const delta = (this.x - this.startX);
                    rotObj.angle = startAngleOnPress + (delta / dragDistancePerRotation) * 360;
                    render();
                },
                onRelease() { /* no-op */ },
                onThrowComplete() { /* no-op */ }
            });
        }

        // 响应式：窗口变化时重算 transformOrigin 并重渲染
        function recalcGeometry() {
            wid = $carousel.width();
            cardsWid = wid > 1920 ? 1920 : wid;
            demical = wid < 415 ? 0.76 : (totalCards > 6 ? 0.44 : 0.38);
            num = wid < 415 ? 0.39 : (totalCards > 6 ? 0.28 : 0.23);
            transformOrigin = wid > 414 && wid < 768
                ? `50% 50% ${-wid * demical * 1.5}px`
                : `50% 50% ${-cardsWid * demical * 1.5}px`;

            cards.forEach(card => {
                gsap.set(card, { transformOrigin: transformOrigin });
            });
            render();
        }
        let resizeTimer = null;
        $(window).on('resize.home3d', function(){
            if (resizeTimer) clearTimeout(resizeTimer);
            resizeTimer = setTimeout(recalcGeometry, 150);
        });

        // 存储实例句柄，供二次调用时清理
        $carousel.data(dataKey, {
            spinIntro: spinIntro,
            draggables: draggables,
            autoStepTimer: autoStepTimer,
            startAutoStep: startAutoStep,  // 暴露启动方法
            stopAutoStep: stopAutoStep      // 暴露停止方法
        });

    },
    green: function (name) {
        if(name=='social'){
            whirPublic.config.circleAni(".social-main",false);
            if($(".social-honor .swiper-thumbs .swiper-slide").length!=0){
                  var swiper =new Swiper('.social-honor .swiper-txt .swiper',{ 
                    loop: true,
                    spaceBetween: 10,
                    effect: 'fade',
                    fadeEffect: {
                        crossFade: true
                    }
                });
               new Swiper('.social-honor .swiper-thumbs .swiper',{
                    watchSlidesProgress: true,
                    slidesPerView: 'auto',
                    centeredSlides: true,
                    loop: true,
                    autoplay: {
                        delay: delayCount,
                        disableOnInteraction: false,
                        pauseOnMouseEnter: true,
						reverseDirection: true,//从右到左
                    },
                    navigation: {
                        nextEl: '.social-honor .arrows-prev',//特意用相反方向
                        prevEl: '.social-honor .arrows-next',//特意用相反方向
                    },
                    on: {
                        progress: function(progress) {
                            // 动态计算平移距离 - 响应式适配
                            var slideWidth = this.slides[0].offsetWidth;
                           // console.log(slideWidth);
                            
                            for (i = 0; i < this.slides.length; i++) {
                                var slide = this.slides.eq(i);
                                var slideProgress = this.slides[i].progress;
                                
                                // 使用更严格的判断条件，确保中心图绝对不缩放不平移
                                var isCenter = Math.abs(slideProgress) < 0.1; // 使用容差范围判断中心位置
                                
                                var scale, translateDistance;
                                
                                if (isCenter) {
                                    // 中心图：不缩放，不平移
                                    scale = 1;
                                    translateDistance = 0;
                                } else {
                                    // 非中心图：应用缩放和平移效果
                                    var absProgress = Math.abs(slideProgress);
                                    var startScale = 0.57;
                                    var decrement = 0.06;
                                    
                                    // 计算缩放：从0.57开始，每次递减0.06
                                    scale = startScale - (absProgress - 1) * decrement;
                                    scale = Math.max(scale, 0.15); // 确保最小缩放比例
                                    
                                    // 计算平移距离
                                    var baseTranslateDistance = slideWidth * (700 / 498);
                                    var increment = slideWidth * (570 / 498);
                                    translateDistance = baseTranslateDistance + (absProgress - 1) * increment;
                                    
                                    // 左边为负值，右边为正值
                                    if (slideProgress < 0) {
                                        translateDistance = -translateDistance;
                                    }
                                }
                                
                                var translate = translateDistance + 'px';
                                // 透明度计算：中间为1，从第三个开始每次递减0.3
                                var absProgress = Math.abs(slideProgress);
                                var opacity;
                                if (absProgress < 3) {
                                    opacity = 1; // 中间和前两个位置保持完全不透明
                                } else {
                                    opacity = Math.max(0, 1 - (absProgress - 2) * 0.2); // 从第三个开始递减0.3
                                }
    
                                // 确保 position 和 zIndex 生效
                                slide.css({
                                    'position': 'relative',
                                    'z-index': 1000 - Math.abs(Math.round(slideProgress * 100)),
                                    'transform': 'translate3d(' + translate + ', 0, 0) scale(' + scale + ')',
                                    'opacity': opacity
                                });
                            }
                        },
                        setTransition: function (swiper, transition) {
                            for (var i = 0; i < this.slides.length; i++) {
                                var slide = this.slides.eq(i)
                                slide.transition(transition);
                            }
                        },
                        slideChange: function () {
                            console.log(this.realIndex);
                            swiper.slideToLoop(this.realIndex,500,false);
                        }
                    }, 
                });
            }else{
                $(".social-honor").hide();
            }
        } 
        if(name=='operate'){
            //feedback
            whirPublic.config.feedback();
        }
        if(name=='greenMain'){
            whirPublic.config.circleAni(".social-main",false);
            whirPublic.config.groupItemsByCount('.green-prod .imgs-row', '.item', 4, 'item-group');
        }
    },
    /**
     * 将元素按指定数量分组，组成items下的子元素
     * @param {string} container - 容器选择器，默认为'.items'
     * @param {string} itemSelector - 子元素选择器，默认为'.item'
     * @param {number} countPerGroup - 每组元素数量，默认为4
     * @param {string} groupClass - 分组容器的CSS类名，默认为'item-group'
     * @returns {void}
     */
    groupItemsByCount: function(container, itemSelector, countPerGroup, groupClass) {
        container = container || '.items';
        itemSelector = itemSelector || '.item';
        countPerGroup = countPerGroup || 4;
        groupClass = groupClass || 'item-group';
        
        $(container).each(function() {
            var $container = $(this);
            var $items = $container.find(itemSelector);
            var totalItems = $items.length;
            
            if (totalItems === 0) return;
            
            // 计算需要多少组（每组4个元素）
            var groupCount = Math.ceil(totalItems / countPerGroup);
            
            // 创建主分组容器
            for (var i = 0; i < groupCount; i++) {
                var $mainGroup = $('<div class="' + groupClass + '"></div>');
                $container.append($mainGroup);
            }
            
            // 将元素分配到各组并进行嵌套分组
            $items.each(function(index) {
                var mainGroupIndex = Math.floor(index / countPerGroup);
                var $mainGroup = $container.find('.' + groupClass).eq(mainGroupIndex);
                var itemIndexInGroup = index % countPerGroup;
                
                // 如果主分组还没有子分组，创建子分组
                if ($mainGroup.find('.subgroup-1, .subgroup-2').length === 0) {
                    $mainGroup.append('<div class="subgroup-1"></div>');
                    $mainGroup.append('<div class="subgroup-2"></div>');
                }
                
                var $subgroup1 = $mainGroup.find('.subgroup-1');
                var $subgroup2 = $mainGroup.find('.subgroup-2');
                
                if (itemIndexInGroup === 0) {
                    // 第一个元素放入subgroup-1
                    $subgroup1.append($(this));
                } else {
                    // 其他3个元素放入subgroup-2
                    $subgroup2.append($(this));
                    
                    // 如果subgroup-2还没有子分组，创建子分组
                    if ($subgroup2.find('.sub-subgroup-1, .sub-subgroup-2').length === 0) {
                        $subgroup2.append('<div class="sub-subgroup-1"></div>');
                        $subgroup2.append('<div class="sub-subgroup-2"></div>');
                    }
                    
                    var $subSubgroup1 = $subgroup2.find('.sub-subgroup-1');
                    var $subSubgroup2 = $subgroup2.find('.sub-subgroup-2');
                    
                    if (itemIndexInGroup === 1) {
                        // 第二个元素放入sub-subgroup-1
                        $subSubgroup1.append($(this));
                    } else {
                        // 第三、四个元素放入sub-subgroup-2
                        $subSubgroup2.append($(this));
                    }
                }
            });
        });
    },
    circleAni:function(main,isAuto){
        function getMinHeight(){ 
            var _this=$(".circle-nav"),
            dtNum=_this.find("dt").length;
            var _dt=_this.find("dt").eq(dtNum - 1)
            if(dtNum!=0){
                var minh=_dt.position().top + _dt.outerHeight();
                $(main).css("--minHeight",minh+"px")
            }
        }
        getMinHeight();
        window.addEventListener("resize",getMinHeight);
        //start
        var imgSwiper=new Swiper('.circle-anibox .swiper', { 
            effect: 'fade',
            speed:1000,
            fadeEffect: { 
                crossFade: true
            },
            autoplay: { 
                delay: 3000,
                disableOnInteraction: false,
                pauseOnMouseEnter: true
            },
            on:{
                slideChange: function () { 
                    var e=this.activeIndex;
                    $(".circle-img svg path").eq(e).addClass("active").siblings().removeClass("active");
                    $(".circle-nav dt").eq(e).addClass("active").siblings().removeClass("active");
                }
            }
        });
        $(".circle-nav dt").hover(function(){
            var e=$(this).index();
            $(this).addClass("active").siblings().removeClass("active");
            $(".circle-img svg path").eq(e).addClass("active").siblings().removeClass("active");
            imgSwiper.slideTo(e,1000,false);
        });
    },
	
}


/**
 * 触发效果
 */
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 //是否静态站
        });
    }
}
/**
 * 滚动动画功能模块
 */
whirPublic.scroll = {
    /**
     * home-ani 滚动动画
     * 实现svg-img和video的复杂动画序列
     */
    homeAni: function () {
        // 确保元素存在
        const homeAni = document.querySelector('.home-ani');
        const aniBox = document.querySelector('.home-ani .ani-box');
        const svgImg = document.querySelector('.home-ani .svg-img');
        const video = document.querySelector('.home-ani .ani-box .video');
        const homeAbout = document.querySelector('.home-about');

        if (!homeAni || !svgImg || !video || !homeAbout) {
            console.warn('home-ani 动画元素未找到', {
                homeAni: !!homeAni,
                svgImg: !!svgImg,
                video: !!video,
                homeAbout: !!homeAbout
            });
            return;
        }


        // 检查是否为移动端
        const isMobile = window.innerWidth <= whirBreakpoints.mobile;

        // 设置初始状态
        gsap.set(aniBox, { opacity: 0, transformOrigin: isMobile ?"6% 51%":"6% 71%" });
        gsap.set(svgImg, { opacity: 1 });
        gsap.set(video, { opacity: 0 });
        gsap.set(homeAbout, { opacity: 0, zIndex: -1 });

        // 创建主时间轴
        const tl = gsap.timeline({
            scrollTrigger: {
                trigger: homeAni,
                start: "top top",
                end: "+=100%",
                scrub: isMobile ? 0.5 : 1, // 移动端使用更小的scrub值
                pin: true,
                pinSpacing: true
            }
        });

        // 动画序列
        tl.to(aniBox, {
            opacity: 1,
            duration: 0.3,
            ease: "linear"
        })
            .to(aniBox, {
                scale:  isMobile ? 0.6 : 0.26,
                //transformOrigin: "0% 90%",
                duration: 1.5,
                ease: "linear"
            }, "+=0.3") // 延迟0.2秒开始缩小
            .to(svgImg, {
                opacity: 0,
                duration: 1,
                ease: "linear"
            }, "-=1.2") // 与aniBox缩放同时开始
            .to(video, {
                opacity: 1,
                duration: 1,
                ease: "linear"
            }, "-=1") // 与aniBox缩放同时开始 
            .to(aniBox, {
                transformOrigin:  isMobile ?"2% 155%":"2% 96%",
                duration: 1,
                ease: "linear"
            }, "-=0.2")
            .to(homeAbout, {
                opacity: 1,
                zIndex: 4,
                duration: 0.3,
                ease: "linear"
            }, "-=2")
            .to(homeAbout, {
                className: "home-about active",
                duration: 0
            }, "-=0.9"); // 动画完成后添加active样式

        // 动画时间轴创建完成
    }

}

/**
 * 视频轮播功能模块
 */
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',
            '.next',
            '.prev'
        ];

        // 合并默认选择器和用户提供的选择器
        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]);
        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) {
        let isInitialized = false;
        var SPnum=$(container).find('.swiper-slide').length
        console.log(SPnum);
        
        publicSwiperVideo = new Swiper(container, {
            loop: true,
            speed: 0,
            loopAdditionalSlides:SPnum,
            autoplay: {
                delay: 4000,
                disableOnInteraction: false
            },
            effect: effect ? effect : 'fade',
            fadeEffect: {
                crossFade: true
            },
            pagination: {
                el: paginationEl,
                type: paginationType ? paginationType : 'bullets',
                clickable: true,
                bulletClass: 'my',
                bulletActiveClass: 'active',
                modifierClass: 'my-pagination-',
                renderBullet: function (index, className) {
                    return '<div class="' + className + '"><span><i></i><i></i></span></div>';
                },
                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);
                    isInitialized = true;
                },
                slideChange: function () {
                    const currentSlide = this.slides[this.activeIndex];
                    const prevSlide = this.slides[this.previousIndex];

                    // 处理视频
                    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);

                    // 添加动画效果
                    if (isInitialized && prevSlide) {
                        const banOutside = $(prevSlide).find('.ban-outside');

                        // 添加过渡类名
                        $(prevSlide).addClass("out");
                        $(currentSlide).addClass("in");

                        gsap.timeline({
                            onComplete: () => {
                                // 移除过渡类名
                                $(prevSlide).removeClass("out");
                                $(currentSlide).removeClass("in");
                                banOutside.removeAttr("style");

                                // 更新激活状态
                                $(currentSlide).addClass("on").siblings().removeClass("on");
                            }
                        }).to(banOutside, {
                            height: 0,
                            duration: 2
                        });
                    } else {
                        // 首次加载时直接设置激活状态
                        $(currentSlide).addClass("on");
                    }
                }
            }
        });
        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];
                            console.log("videoElement:", videoElement);
                            
                            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>");
            }
        })
    }
}