const baseUrl = document.getElementById('require').getAttribute('data-src').split('/js/main')[0]

require.config({

  baseUrl: baseUrl.includes('/tpl/') ? baseUrl : '',

  waitSeconds: 60,

  paths: {
    'jquery': 'js/lib/jquery.min',
    'migrate': 'js/lib/jquery-migrate.min',
    'easing': 'js/lib/jquery.easing.min',
    'gsap': 'js/gsap/gsap.min',
    'scrolltrigger': 'js/gsap/ScrollTrigger.min',
    'until': 'js/gsap/until',
    'smoothscroll': 'js/gsap/custom_slide',
    'comcus': 'js/comcus',
    'lazyload': 'js/lib/lazyload.min',
    'tab': 'js/lib/jquery.sudyTab.min',
    'pen': 'js/pen',
    'swiper': 'js/swiper',
    'vivus': 'js/vivus',
  },
  map: {
    '*': {
      'min': 'js/lib/css.min'
    }
  },

  shim: {
    'migrate': ['jquery'],
    'easing': ['jquery'],
    'comcus': ['jquery'],
    'scrolltrigger': ['gsap'],
    'until': ['gsap'],
    'lazyload': ['jquery'],
    'tab': ['jquery'],
    'pen': ['jquery'],
    'swiper': ['jquery'],
  },

  urlArgs: 'ver=0.0.3'

})

require(['jquery', 'migrate', 'smoothscroll', 'lazyload', 'easing', 'swiper', 'tab', 'pen', 'comcus', 'scrolltrigger', 'until',], function () {
 
  var ifAutoplay = $(".mbanner .news:eq(0) video").attr("src") == "";

  $(".mbanner .news .news_video").each(function () {
    if ($(this).find("video").attr("src") == "") {
      $(this).hide();
      $(this).siblings(".news_imgs").show();
    } else {
      $(this).show();
      $(this).siblings(".news_imgs").hide();
    }
  })

const hasNonEmptyVideoSource = videoEl => {
    if (!videoEl) return false;

    const videoSrc = videoEl.getAttribute('src');
    if (videoSrc != null && videoSrc.trim() !== '') {
      return true;
    }

    const sourceSrc = videoEl.querySelector('video[src]')?.getAttribute('src');
    if (sourceSrc != null && sourceSrc.trim() !== '') {
      return true;
    }

    return false;
  }


const handleSlideAutoplay = swiper => {
    if (typeof swiper.activeIndex !== 'number' || swiper.activeIndex < 0) return;

    const activeSlide = swiper.slides[swiper.activeIndex];
    const activeVideo = activeSlide?.querySelector('video');

    if (!hasNonEmptyVideoSource(activeVideo)) {
      // console.log('当前slide是图片');

      if (!swiper.autoplay.running) {
        swiper.autoplay.start();
      }

      return;
    }

    // console.log('当前slide是视频');

    swiper.autoplay.stop();

    if (Object.prototype.hasOwnProperty.call(activeVideo, '_playCleanup')) {
      activeVideo._playCleanup?.();
      activeVideo._playCleanup = null;
    }

    const createLoadTimeout = (timeoutMs = 5000) => {
      let timeoutId = null;

      const start = () => {
        timeoutId = setTimeout(() => {
          console.warn(`[视频加载超时]  $ {timeoutMs}ms 内未就绪，跳过播放`);
          if (typeof activeVideo._playCleanup === 'function') {
            activeVideo._playCleanup();
          }
          swiper.autoplay.start();
          swiper.slideNext();
        }, timeoutMs);
      };

      const clear = () => {
        if (timeoutId) {
          clearTimeout(timeoutId);
          timeoutId = null;
        }
      };

      return { start, clear };
    };

    const loadTimeout = createLoadTimeout(5000);

    const onError = () => {
      console.warn('视频加载失败:', activeVideo.error);
      loadTimeout.clear();
      swiper.autoplay.start();
    };

    const onEnded = () => {
      console.log('视频播放结束');
      loadTimeout.clear();
      swiper.autoplay.start();
      swiper.slideNext();
    };

    const onCanPlay = async () => {
      if (activeVideo._playAttempted) return;
      activeVideo._playAttempted = true;

      loadTimeout.clear();

      try {
        await activeVideo.play();
        activeVideo.addEventListener('ended', onEnded, { once: true });
      } catch (err) {
        console.warn('自动播放被阻止:', err);
        swiper.autoplay.start();
      }
    };

    const cleanup = () => {
      loadTimeout.clear();
      activeVideo.removeEventListener('error', onError);
      activeVideo.removeEventListener('canplay', onCanPlay);
      activeVideo.removeEventListener('ended', onEnded);
    };

    activeVideo.muted = true;
    activeVideo.loop = false;

    activeVideo._playAttempted = false;
    activeVideo._playCleanup = cleanup;

    activeVideo.addEventListener('error', onError, { once: true });
    activeVideo.addEventListener('canplay', onCanPlay, { once: true });

    if (activeVideo.readyState === HTMLMediaElement.HAVE_NOTHING) {
      activeVideo.load();
      loadTimeout.start();
    }

    if (activeVideo.readyState >= HTMLMediaElement.HAVE_FUTURE_DATA) {
      onCanPlay();
    }
  };


  var bannerswiper = new Swiper('.mbanner .swiper', {
    autoplay: true,
    loop: true,
    pagination: {
      el: '.swiper-pagination',
      clickable: true
    },
    autoplay: ifAutoplay,
    on: {
      init:handleSlideAutoplay,
      slideChangeTransitionEnd:handleSlideAutoplay,
      slideChangeTransitionStart: ins => {
        const { slides, previousIndex } = ins;

        if (typeof previousIndex !== 'number' || previousIndex < 0) return;

        const previousSlide = slides[previousIndex];
        const previousVideo = previousSlide?.querySelector('video');

        if (!hasNonEmptyVideoSource(previousVideo)) return;

        // console.log('前一个slide是视频，这里来清理。');

        previousVideo.pause();
        previousVideo.currentTime = 0;

        if (previousVideo._playCleanup) {
          previousVideo._playCleanup?.();
          previousVideo._playCleanup = null;
        }
      },
    },
  })


  new Swiper('.post-12 .swiper', {
    loop: true,
    pagination: {
      el: '.swiper-pagination',
      clickable: true
    },
    navigation: {
      nextEl: '.swiper-button-next',
      prevEl: '.swiper-button-prev',
    },
  })

  new Swiper('.post-21 .swiper', {
    loop: true,
    slidesPerView: 2,
    spaceBetween: 20,
    navigation: {
      nextEl: '.post-21 .swiper-button-next',
      prevEl: '.post-21 .swiper-button-prev',
    },
    breakpoints: {
      999: {  //当屏幕宽度大于等于320
        slidesPerView: 4,
        spaceBetween: $(".post-21 .example").width(),
      },
    },
  })
   new Swiper('.post-52 .swiper', {
  autoplay: {
        delay: 3000,
        disableOnInteraction: false,
      },
    slidesPerView: 1,
    loop: true,
  })

const regex = /【(.*?)】/g;
const ele=document.querySelector(".post-31"); 
const slides=window.getComputedStyle(ele).getPropertyValue("--slides")
let matches = [];
let match;
//var total=w31Jsons.length

/*
for(i=0;i<total;i++){ 
matches=[];
if(w31Jsons[i].title.lastIndexOf("】")>-1 && w31Jsons[i].title.lastIndexOf("【")>-1){
  var str=w31Jsons[i].title.slice(0,w31Jsons[i].title.lastIndexOf("】")+1)
  while ((match = regex.exec(str)) !== null) {
     matches.push(match[1]); 
  }
}
var source=matches.join(" | ")
var htm=`<div class="news">
                      <div class="linebox">
                        <div class="line"></div>
                        <div class="circle"></div>
                      </div>
                      <div class="field">${source}</div>
                      <div class="news_time">${w31Jsons[i].time}</div>
                      <div class="news_title line2"><a href="${w31Jsons[i].url}" target="_blank">${w31Jsons[i].title}</a></div>
                    </div>`
$(".post-31 .swiper-pc .news_list").append(htm)
}

//groupElements(slides)
function groupElements(x) {
  if (x <= 0) {
    console.error('x 必须是正整数');
    return;
  }
  const container = document.querySelector('.post-31 .swiper-pc .news_list');
  if (!container) {
    console.error('未找到 id 为 "container" 的容器');
    return;
  }

  const children = Array.from(container.children);
  container.innerHTML = ''; 

  for (let i = 0; i < children.length; i += x) {
    const group = children.slice(i, i + x);
    const newDiv = document.createElement('div');
    newDiv.classList.add("swiper-slide")
    //newDiv.append(...group);
    group.forEach(child => newDiv.appendChild(child));
    container.appendChild(newDiv); 
  }
}
*/
   $('.xxgd .xxgd_1').on('click', function(e) {
    e.preventDefault();
    
    var target = $('.bodycon1');
    if (target.length) {
      $('html, body').animate({
        scrollTop: target.offset().top
      }, 800, 'swing'); 
    }
  });
$(".post-31 .swiper-pc .news").each(function(){
matches=[];
var title=$(this).find(".news_title a").text();
if(title.lastIndexOf("】")>-1 && title.lastIndexOf("【")>-1){
  var str=title.slice(0,title.lastIndexOf("】")+1)
  var newtitle=title.slice(title.lastIndexOf("】")+1)
  while ((match = regex.exec(str)) !== null) {
     matches.push(match[1]); 
  }
  var source=matches.join(" | ")
  $(this).find(".field").text(source)
  $(this).find(".news_title a").text(newtitle)
}
})

  new Swiper('.post-31 .swiper-pc', {
    loop: true,
    navigation: {
      nextEl: '.post-31 .swiper-button-next',
      prevEl: '.post-31 .swiper-button-prev',
    },
  })

  new Swiper('.post-31 .swiper-wap', {
    loop: true,
    navigation: {
      nextEl: '.post-31 .swiper-button-next',
      prevEl: '.post-31 .swiper-button-prev',
    },
    slidesPerView: 2,
    spaceBetween:20
  })


  // addFirstDom({
  //   element: document.querySelectorAll('.post-12 li.news'),
  //   filepath: Path() + "images/link",
  //   callback: false
  // })

$(document).on("click",".post-72 li",function(){
if($(window).width()>999){
$(".post-72 li.fadeout").remove() 
$(".post-72 li.active").prevAll().remove()
$(".post-72 li").removeClass("clone") 
var prev=$(this).prevAll() 
var index=$(this).attr("class").split("index")[1].split(" ")[0]
$(".main7 .con").eq(index).addClass("selected").siblings().removeClass("selected")

if(!$(this).hasClass("active")){
 
$(".post-72 li").removeClass("n1 n2 n3 n4")
$(this).addClass("active n1").prevAll().addClass("fadeout")
//.siblings().removeClass("active")
prev.each(function(index,ele){   
      var cloned=$(ele).clone()
      cloned.addClass("fadein clone").removeClass("fadeout active"); 
      //$(ele).remove()
      $(".post-72 ul").append(cloned) 
})
setTimeout(function(){ 
    $(".post-72 li").removeClass("fadein ")  
    //$(".post-72 li.clone").removeClass("active") 
},600)
$(this).next().addClass("n2")
$(this).next().next().addClass("n3")
$(this).next().next().next().addClass("n4")
}

}
})

  new GsapAnimate.init({
    scrollTopAnime: ".Scroll-to-top", //置顶图标动画
    slideNavAnime: ".Quick-navigation", //锚点导航动画
    fixHeader: false, //头部固定
    isFixbanner: false,//大图全屏
    navMaxSreen: {
      control: ".menu-btn", //控制元素
      box: ".navbox", //元素
      hideDom: [".head-right .left", ".head-right .nav", ".header .searchbox"], //隐藏元素
    }, //导航咱开(不写是null)
    callback: function (target) {
      //回调函数 target:当前动画元素的元素
    },
  });

  //图片懒加载
  $('.lazy').lazyload({
    threshold: 100,
    data_attribute: 'src',
    effect: 'fadeIn'
  })

const loaderEl = document.querySelector('.pre-loader');
    if (loaderEl) {
      gsap.to(loaderEl, {
        opacity: 0,
        duration: .6,
        onComplete: () => {
          loaderEl.remove();
        }
      });
    }

})
