<template>
  <div class="scroll" ref="scroll">
    <div class="scroll-container" ref="container">
      <div
        class="scroll-content"
        ref="content"
        :style="{
          width: 'calc(100% + ' + this.vSize + 'px',
          height: 'calc(100% + ' + this.hSize + 'px',
        }"
        @scroll.stop="onScroll"
      >
        <slot></slot>
      </div>
    </div>
    <!--垂直滚动条-->
    <scroll-slider
      v-if="!hideV"
      :scrollTop="scrollTop"
      ref="sliderV"
      @change="silderVChange"
    ></scroll-slider>
    <!--水平滚动条-->
    <scroll-slider
      v-if="!hideH"
      sliderType="h"
      :scrollLeft="scrollLeft"
      ref="sliderH"
      @change="silderHChange"
    ></scroll-slider>
  </div>
</template>
<script>
import slider from "./slider.vue";
import ElementResizeDetectorMaker from "element-resize-detector";

export default {
  name: "scroll",
  props: {
    //隐藏垂直滚动条
    hideV: {
      type: Boolean,
      default: false,
    },
    //隐藏水平滚动条
    hideH: {
      type: Boolean,
      default: false,
    },
    resize: Boolean,
  },
  components: {
    "scroll-slider": slider,
  },
  data() {
    return {
      //垂直滚动条宽度
      vSize: 17,
      //水平滚动条高度
      hSize: 17,
      scrollTop: 0,
      scrollLeft: 0,
    };
  },
  mounted() {
    this.computeSliderV();
    this.computeSliderH();
    // 监听slot视图变化, 方法内部会判断是否设置了开启监听resize
    this.resizeListener();
  },
  methods: {
    onScroll(event) {
      this.scrollTop = this.$refs["content"].scrollTop;
      this.scrollLeft = this.$refs["content"].scrollLeft;
    },
    silderVChange(newval) {
      this.$refs["content"].scrollTop = newval;
    },
    silderHChange(newval) {
      this.$refs["content"].scrollLeft = newval;
    },
    //计算垂直滚动条的长度
    computeSliderV() {
      if (this.hideV) {
        return;
      }
      let clientEle = this.$refs["scroll"];
      let slotEle = this.$slots.default[0]["elm"];
      this.$refs.sliderV.computeSlider(slotEle, clientEle);
    },
    computeSliderH() {
      if (this.hideH) {
        return;
      }
      let clientEle = this.$refs["scroll"];
      let slotEle = this.$slots.default[0]["elm"];
      this.$refs.sliderH.computeSlider(slotEle, clientEle);
    },

    // slot视图大小变化时的监听
    resizeListener() {
      // 没开启监听reszie方法
      if (!this.resize) return;

      // 监听slot视图元素resize
      let elementResizeDetector = ElementResizeDetectorMaker({
        strategy: "scroll",
        callOnAdd: false,
      });

      // 记录视图上次宽高的变化
      const ele = this.$refs.scroll;
      elementResizeDetector.listenTo(ele, (element) => {
        // 初始化百分比
        this.computeSliderV();
        this.computeSliderH();
        this.scrollTop = this.$refs["content"].scrollTop;
        this.scrollLeft = this.$refs["content"].scrollLeft;
      });
    },
  },
};
</script>