<!--
 * @Author: your name
 * @Date: 2022-04-12 16:09:32
 * @LastEditTime: 2022-04-13 15:41:17
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /gassafety-progress/gassafetyprogress-web/src/components/scrollCom/scroll.vue
-->
<template>
  <div
    class="scroll"
    @mouseover="stopScroll"
    @mouseout="startScroll"
    ref="wrapper"
  >
    <div ref="scroll" :style="{ top: pxTop }" class="contain">
      <slot :dataList="dataList" />
    </div>
  </div>
</template>

<script>
export default {
  props: {
    dataList: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      timer: null,
      top: 0,
      wrapperHeight: 0,
      scrollHeight: 0,
    };
  },
  computed: {
    pxTop() {
      return this.top + "px";
    },
  },

  mounted() {
    this.init();
  },
  watch: {
    dataList: {
      handler: function (val, oldVal) {
        this.top = 0;
        this.init();
      },
      deep: true,
    },
  },
  methods: {
    init() {
      clearInterval(this.timer);
      const { height: wrapperHeight } =
        this.$refs.wrapper.getBoundingClientRect();
      const { height: scrollHeight } =
        this.$refs.scroll.getBoundingClientRect();
      this.scrollHeight = scrollHeight;
      const maxTop = wrapperHeight - scrollHeight;

      // 如果没有超过，就不滚动了
      if (maxTop > 0) return;
      this.timer = setInterval(() => {
        // this.top = this.top-1;
        this.top = this.top - 0.5;
        if (this.top <= maxTop) {
          this.top = 0;
        }
      }, 24);
    },
    stopScroll() {
      clearInterval(this.timer);
    },
    startScroll() {
      this.init();
    },
  },

  beforeDestroy() {
    clearInterval(this.timer);
  },
};
</script>

<style lang="scss" scoped>
.scroll {
  height: 100%;
  // background: red;
  overflow: hidden;
  position: relative;
}
.contain {
  width: 100%;
  position: absolute;
}
</style>