<!--
 * @Description: 
 * @Author: Format-qi 283810417@qq.com
 * @Date: 2022-03-06 13:16:00
 * @LastEditors: Format-qi 283810417@qq.com
 * @LastEditTime: 2022-06-24 14:02:41
-->
<template>
  <BzScrollbar ref="scrollbarRef" class="bz-scroll-container" v-bind="$attrs">
    <slot></slot>
  </BzScrollbar>
</template>

<script lang="ts">
  import { defineComponent, ref, unref, nextTick } from 'vue';
  import { BzScrollbar, ScrollbarType } from '/@/components/Scrollbar';
  import { useScrollTo } from '/@/hooks/event/useScrollTo';

  export default defineComponent({
    name: 'BzScrollContainer',
    components: { BzScrollbar },
    setup() {
      const scrollbarRef = ref<Nullable<ScrollbarType>>(null);

      /**
       * Scroll to the specified position
       */
      function scrollTo(to: number, duration = 500) {
        const scrollbar = unref(scrollbarRef);
        if (!scrollbar) {
          return;
        }
        nextTick(() => {
          const wrap = unref(scrollbar.wrap);
          if (!wrap) {
            return;
          }
          const { start } = useScrollTo({
            el: wrap,
            to,
            duration,
          });
          start();
        });
      }

      function getScrollWrap() {
        const scrollbar = unref(scrollbarRef);
        if (!scrollbar) {
          return null;
        }
        return scrollbar.wrap;
      }

      /**
       * Scroll to the bottom
       */
      function scrollBottom() {
        const scrollbar = unref(scrollbarRef);
        if (!scrollbar) {
          return;
        }
        nextTick(() => {
          const wrap = unref(scrollbar.wrap) as any;
          if (!wrap) {
            return;
          }
          const scrollHeight = wrap.scrollHeight as number;
          const { start } = useScrollTo({
            el: wrap,
            to: scrollHeight,
          });
          start();
        });
      }

      return {
        scrollbarRef,
        scrollTo,
        scrollBottom,
        getScrollWrap,
      };
    },
  });
</script>
