<template>
  <div class="scroll-view-box" ref="refreshContainer">
    <slot></slot>
  </div>
</template>

<script>
import BScroll from '@better-scroll/core';
import Pullup from '@better-scroll/pull-up';
import ObserveDom from '@better-scroll/observe-dom'
import _ from 'lodash'

BScroll.use(Pullup).use(ObserveDom);

export default {
  name: 'scroll-view',
  props: {
    scrollTop: {
      type: [Number, String, Function],
    },
    scrollX: {
      type: Boolean,
      // required: false,
      default: false,
    },
    scrollY: {
      type: [Boolean, String],
      // required: false,
      default: true,
    }
  },
  data() {
    this.pullingUpHandlerD = _.debounce(this.pullingUpHandler, 1000) // 防抖
    return {
      startPos: 0,
      transitionHeight: 0,
      refreshText: '',
      scroll: null,
      isMore: true,
    };
  },
  methods: {
    pullingUpHandler() {
      this.$emit('scrolltolower');
      this.scroll.finishPullUp(); //每次上拉结束后，需要执行这个操作
      this.scroll.refresh(); //当滚动区域的dom结构有变化时，需要执行这个操作
    },
  },
  mounted() {
    this.scroll = new BScroll(this.$refs.refreshContainer, {
      scrollY: true, //垂直方向滚动
      observeDOM: true,
      click: true, //默认会阻止浏览器的原生click事件，如果需要点击，这里要设为true
      pullUpLoad: {
        threshold: 50,
        stop: 0, //下拉回弹后停留的位置
      }, //上拉加载更多
      pullDownRefresh: {
        threshold: 50, //触发pullingDown事件的位置
        stop: 0, //下拉回弹后停留的位置
      },
    });
    this.scroll.on('pullingUp',this.pullingUpHandlerD);
  },
  destroyed() {
    // 离开页面 销毁 实例对象
    this.scroll.destroy()
  },
};
</script>

<style scoped lang="less">
.scroll-view-box {
  width: 100%;
  height: 100vh;
  overflow: hidden;
}
</style>
