const useScroll = {
  data() {
    return {
      scrollableValue: 20,
      scrollableElement: null,
      scrollTop: void 0,
      __activated__: false,
    };
  },
  activated() {
    if (!this.__activated__) this.onActivated();
    this.scroll(this.scrollTop, 'instant');
  },
  deactivated() { this.onDeactivated(); },
  beforeRouteLeave(to, from, next) {
    this.scrollableElement = this.findScrollableElement();
    this.scrollTop = this.scrollableElement ? this.scrollableElement.scrollTop : void 0;
    next();
  },
  methods: {
    /* activated 生命周期调用 */
    onActivated() { this.__activated__ = true; },
    /* deactivated 生命周期调用 */
    onDeactivated() { this.__activated__ = false; },
    findScrollableElement(el) {
      if (this.$refs.scrollableElement) return this.unrefElement();
      if (el == null) el = this.$el;
      if (el && el.scrollHeight - el.clientHeight > this.scrollableValue) return el;
      else if (el) {
        for (const child of el.children) {
          const scrollable = this.findScrollableElement(child);
          if (scrollable) return scrollable;
        }
      }
      return null;
    },
    unrefElement(element) {
      if (!element) element = this.$refs.scrollableElement;
      return element && element._isVue ? element.$el : element;
    },
    /**
     * 滚动容器滚动
     * @param {number} top
     * @param {'instant' | 'smooth'} behavior
     */
    scroll(top, behavior = 'smooth') {
      const element = this.unrefElement() || this.scrollableElement;
      if (top == null) top = this.scrollTop;
      if (element != null && top != null) element.scrollTo({ top, behavior });
    },
  },
};

export default useScroll;