<template>
  <div>
    <slot></slot>
  </div>
</template>

<script setup>
const props = defineProps({
  scrollRef: {
    type: [Object, null],
    required: true,
  },
  innerRef: {
    type: [Object, null],
    required: true,
  },
});
const now = ref(0);
const max = ref(0);
const scrollContainer = ref(null);
const innerRefs = ref(null);
const setActive = () => {
  if (innerRefs.value.clientHeight > props.scrollRef.wrapRef.clientHeight) {
    max.value =
      innerRefs.value.clientHeight - props.scrollRef.wrapRef.clientHeight + 20;
    inputSlider();
  }
};
const inputSlider = () => {
  const scrollAmountPerSecond = window.innerHeight * 0.07; // 每秒滚动的距离
  const totalScrollDistance = max.value; // 内容的总高度
  const duration = (totalScrollDistance / scrollAmountPerSecond) * 1000; // 动画总时长（毫秒）

  let startTime;

  function animate(time) {
    if (!startTime) startTime = time;
    const elapsed = time - startTime;

    // 计算当前位置
    const progress = Math.min(elapsed / duration, 1);
    now.value = progress * totalScrollDistance;
    props.scrollRef.setScrollTop(now.value);

    if (progress < 1) {
      requestAnimationFrame(animate);
    } else {
      now.value = 0; // 动画结束后重置位置
      props.scrollRef.setScrollTop(now.value);

      // 重置起始时间并重新开始动画
      startTime = time;
      requestAnimationFrame(animate);
    }
  }

  requestAnimationFrame(animate); // 启动动画
};
nextTick(() => {
  scrollContainer.value = props.scrollRef;
  innerRefs.value = props.innerRef;
});
defineExpose({
  setActive,
});
</script>

<style scoped></style>
