<template>
  <div class="scroll-container" ref="container">
    <div class="scroll-content" :style="{ transform: `translateY(${translateY}px)` }">
      <slot :dataList="dataList" />
    </div>
  </div>
</template>

<script>
export default {
  props: {
    dataList: {
      type: Array,
      default: () => [],
    },
    speed: {
      type: Number,
      default: 0.5
    },
    interval: {
      type: Number,
      default: 24
    }
  },
  data() {
    return {
      timer: null,
      translateY: 0,
      containerHeight: 0,
      contentHeight: 0,
      isHover: false
    };
  },
  mounted() {
    this.initScroll();
  },
  watch: {
    dataList: {
      handler() {
        this.$nextTick(() => {
          this.resetScroll();
          this.initScroll();
        });
      },
      deep: true
    }
  },
  methods: {
    initScroll() {
      if (!this.$refs.container) return;

      this.containerHeight = this.$refs.container.clientHeight;
      this.contentHeight = this.$refs.container.firstElementChild?.scrollHeight || 0;

      // 如果内容高度小于容器高度，不需要滚动
      if (this.contentHeight <= this.containerHeight) {
        this.stopScroll();
        return;
      }

      this.startScroll();
    },
    startScroll() {
      this.stopScroll();
      this.timer = setInterval(() => {
        if (this.isHover) return;

        this.translateY -= this.speed;

        // 当内容完全滚出容器时，重置位置
        if (Math.abs(this.translateY) >= this.contentHeight) {
          this.translateY = this.containerHeight;
        }
      }, this.interval);
    },
    stopScroll() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    resetScroll() {
      this.translateY = 0;
      this.stopScroll();
    }
  },
  beforeDestroy() {
    this.stopScroll();
  }
};
</script>

<style lang="scss" scoped>
.scroll-container {
  height: 100%;
  overflow: hidden;
  position: relative;
}
.scroll-content {
  position: absolute;
  width: 100%;
  transition: transform 0.1s linear;
}
</style>
