<script setup>
import { NCarousel, NDivider, NMarquee, NImage } from 'naive-ui'
import { onUnmounted, ref, watch, onMounted } from 'vue';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
import { useHome } from '@/store/home/index.js';
import { useTransitionComposable } from '@/composables/transition-composable';

const { transitionState } = useTransitionComposable();
const main = ref();
const secondImage = ref(null);
let scrollTween;
let ctx;
const { currentTab } = useHome();
let isScrolling = false;  // 添加滚动状态标记
const scrollThreshold = 50;  // 添加滚动阈值
let lastScrollTime = 0;  // 添加最后滚动时间记录

const handleTabClick = (tab) => {
  currentTab.value = tab;
}

const goToSection = (i) => {
  if (scrollTween) {
    scrollTween.kill();
  }

  // 防止频繁触发
  const now = Date.now();
  if (now - lastScrollTime < 500) return;  // 500ms 内不重复触发
  lastScrollTime = now;

  isScrolling = true;
  scrollTween = gsap.to(window, {
    scrollTo: { y: i * window.innerHeight, autoKill: false },
    duration: 0.8,  // 增加动画时间使其更平滑
    ease: "power2.inOut",
    onComplete: () => {
      scrollTween = null;
      isScrolling = false;
    },
    overwrite: true,
  });
};

// 添加滚轮事件处理
const handleWheel = (e) => {
  if (isScrolling) {
    e.preventDefault();
    return;
  }

  const delta = e.deltaY;
  const currentSection = Math.round(window.scrollY / window.innerHeight);

  // 只有当滚动量超过阈值时才触发
  if (Math.abs(delta) > scrollThreshold) {
    if (delta > 0 && currentSection < 3) {  // 向下滚动
      goToSection(currentSection + 1);
    } else if (delta < 0 && currentSection > 0) {  // 向上滚动
      goToSection(currentSection - 1);
    }
  }
};

// 监听滚轮事件
onMounted(() => {
  window.addEventListener('wheel', handleWheel, { passive: false });
});

onUnmounted(() => {
  window.removeEventListener('wheel', handleWheel);
  ctx?.revert();
  ScrollTrigger.killAll();
});

watch(
  [() => transitionState.transitionComplete, main],
  (newValue) => {
    if (newValue && main.value) {
      ctx = gsap.context((self) => {
        const panels = self.selector('.panel');

        // 为每个面板创建滚动触发器
        panels.forEach((panel, i) => {
          ScrollTrigger.create({
            trigger: panel,
            start: 'top center',
            end: 'bottom center',
            onToggle: (self) => {
              if (self.isActive && !isScrolling) {
                goToSection(i);
              }
            },
            preventOverlaps: true,
          });
        });

        // 移除之前的渐入动画代码
        panels.forEach((panel, i) => {
          // 背景视差
          const bg = panel.querySelector('.parallax-bg');
          if (bg) {
            gsap.to(bg, {
              yPercent: 30,
              ease: "none",
              scrollTrigger: {
                trigger: panel,
                start: "top bottom",
                end: "bottom top",
                scrub: true
              }
            });
          }

          // 内容视差
          const content = panel.querySelector('.content');
          if (content) {
            gsap.from(content, {
              yPercent: 50,
              opacity: 0,
              scrollTrigger: {
                trigger: panel,
                start: "top center",
                end: "center center",
                scrub: true
              }
            });
          }
        });

        // 修改第二个面板的动画配置
        ScrollTrigger.create({
          trigger: panels[1],
          start: "top 60%",    // 调整为更晚的触发时机
          end: "bottom 40%",   // 调整离开时机
          onEnter: () => {     // 进入第二幕时
            gsap.to(secondImage.value, {
              opacity: 1,
              y: 0,
              duration: 1.2,
              ease: "power2.out"
            });
          },
          onLeave: () => {     // 离开第二幕时（向下滚动）
            gsap.to(secondImage.value, {
              opacity: 0,
              y: -50,
              duration: 0.5,    // 加快渐出速度
              ease: "power1.in"  // 使用更快的缓动函数
            });
          },
          onEnterBack: () => { // 重新进入第二幕时（向上滚动）
            gsap.to(secondImage.value, {
              opacity: 1,
              y: 0,
              duration: 1.2,
              ease: "power2.out"
            });
          },
          onLeaveBack: () => { // 返回第一幕时（向上滚动）
            gsap.to(secondImage.value, {
              opacity: 0,
              y: 50,
              duration: 0.5,    // 加快渐出速度
              ease: "power1.in"  // 使用更快的缓动函数
            });
          }
        });
      }, main.value);
    }
  },
  { immediate: true }
);
</script>

<template>
  <header className="header">
    <div class="logo">
      <img src="@/assets/image/logo.png" alt="logo" />
    </div>
    <div class="tabs">
      <div class="tab-item" :class="{ active: currentTab === 'home' }" @click="handleTabClick('home')">
        首页
      </div>
      <div class="tab-item" :class="{ active: currentTab === 'company' }" @click="handleTabClick('company')">
        公司概况
      </div>
      <div class="tab-item" :class="{ active: currentTab === 'business' }" @click="handleTabClick('business')">
        业务介绍
      </div>
    </div>
  </header>
  <main ref="main">

    <section className="panel first-panel">

      <n-carousel autoplay :interval="5000" class="no-hover">
        <img class="carousel-img" src="@/assets/image/banner/cn/b1.jpg">
        <img class="carousel-img" src="@/assets/image/banner/cn/b2.jpg">
        <img class="carousel-img" src="@/assets/image/banner/cn/b3.jpg">
      </n-carousel>

    </section>

    <section className="panel" style="background-color: rgba(248, 249, 255, 1);">
      <n-divider class="divider1" vertical />
      <div class="divider2" style=""></div>
      <div class="divider3" style=""></div>
      <div class="divider4" style=""></div>
      <n-divider class="divider5" vertical />
      <div class="parallax-bg" style="margin-top: 70px;">
        <img ref="secondImage" class="second-image" src="@/assets/image/head.png">


      </div>
      <div class="content">
        <div class="text-[#10253E] text-[54px] leading-[80px]">FiEE携手文艺创作者</div>
        <div class="text-[#10253E] text-[54px] leading-[80px]">启航全球影响力新征程</div>
      </div>
    </section>

    <section className="panel" style="background-color: #fff;">
      <div class="parallax-bg" style="margin-top: 70px;">



      </div>
      <div class="content3">
        <div class="text-[#8B59F7] text-[16px]">公司简介</div>
        <div class="text-[#10253E] text-[40px]  mt-[17px]">
          FiEE
        </div>
        <div class="text-[#455363] text-[16px]  mt-[31px]">
          作为一家深度扎根前沿科技领域的创新领航者，FiEE持续钻研
          AI、大数据在文艺创作中的应用。凭借对文艺理念的深度剖析，以及对创作实践的深刻洞察，我们精准把握文艺发展脉络。怀着满腔热忱，整合各类技术与资源，为文艺创作者提供从灵感启发到作品推广的全方位赋能。
        </div>
        <n-marquee auto-fill>
          <n-image width="80" height="80" src="https://07akioni.oss-cn-beijing.aliyuncs.com/07akioni.jpeg"
            style="margin-right: 24px" />
        </n-marquee>
      </div>

    </section>

    <section className="panel">
      <div class="parallax-bg">FOUR</div>
      <div class="content">
        <!-- 添加你的内容 -->
      </div>
    </section>
  </main>
</template>

<style scoped lang="scss">
.divider1 {
  position: absolute;
  z-index: 3;
  left: 477px;
  width: 1px;
  height: 100vw;

}

.divider2 {
  position: absolute;
  z-index: 3;
  left: 715px;
  width: 1px;
  height: 100vh;
  background-image: linear-gradient(to bottom, #E6EAEE 50%, transparent 50%);
  background-size: 1px 15px; // 第一个值是宽度，第二个值是虚线的总长度（实线+空白）
  background-repeat: repeat-y;
}

.divider3 {
  position: absolute;
  z-index: 3;
  left: 950px;
  width: 1px;
  height: 100vh;
  background-image: linear-gradient(to bottom, #E6EAEE 50%, transparent 50%);
  background-size: 1px 15px; // 第一个值是宽度，第二个值是虚线的总长度（实线+空白）
  background-repeat: repeat-y;
}

.divider4 {
  position: absolute;
  z-index: 3;
  left: 1186px;
  width: 1px;
  height: 100vh;
  background-image: linear-gradient(to bottom, #E6EAEE 50%, transparent 50%);
  background-size: 1px 15px; // 第一个值是宽度，第二个值是虚线的总长度（实线+空白）
  background-repeat: repeat-y;
}

.divider5 {
  position: absolute;
  z-index: 3;
  left: 1420px;
  width: 1px;
  height: 100vw;
}

.carousel-img {
  width: 100%;
  height: 100vh;
  object-fit: cover;
  image-rendering: -webkit-optimize-contrast;
  image-rendering: crisp-edges;
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
  transform: translateZ(0);
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.header {
  width: 100%;
  height: 55px;
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  position: fixed;
  z-index: 10;
  top: 0;
  left: 0;
  right: 0;
  padding: 0 10rem;
  background-color: transparent;
}

.logo {
  img {
    width: 108px;
    height: 33px;
  }
}

.tabs {
  display: flex;
  gap: 32px;
  margin-right: 32px;
}

.tab-item {
  font-size: 16px;
  color: #000000;
  cursor: pointer;
  transition: color 0.3s ease;
  padding: 4px 8px;

  &.active {
    color: #8B59FA;
  }

  &:hover {
    color: #8B59FA;
  }
}

.panel {
  height: 100vh;
  position: sticky;
  top: 0;
  color: var(--dark);
  font-size: 30px;
  overflow: hidden;

  &.first-panel {
    position: relative;

    .carousel-img {
      position: absolute;
      top: 0;
      left: 0;
      z-index: 1;
    }

    .content {
      position: relative;
      z-index: 2;
    }
  }
}

.parallax-bg {
  position: absolute;
  top: -10%;
  left: 0;
  width: 100%;
  height: 120%;
  z-index: 1;
}

.content {
  position: relative;
  z-index: 5;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.content3 {
  position: relative;
  z-index: 2;
  padding: 0 500px;
  height: 100%;
  display: flex;
  flex-direction: column;

}

.no-hover {
  pointer-events: none;
}

:deep(.no-hover) {

  .n-carousel__dots,
  .n-carousel__arrow {
    pointer-events: auto;
  }
}

.second-image {
  opacity: 0;
  padding: 0 64px;
  transform: translateY(50px);
  will-change: opacity, transform;
  pointer-events: none;
}

.divider3,
.divider4 {
  :deep(.n-divider) {
    border-left: none;
    background-image: linear-gradient(to bottom, #E6EAEE 50%, transparent 50%);
    background-size: 1px 30px;
    background-repeat: repeat-y;
  }
}
</style>