<template>
  <div class="mtp-table-scroll">
    <slot name="header"></slot>
    <div class="mtp-table-scroll__container" ref="scrollElement">
      <slot :scroll="scroll"></slot>
    </div>
    <slot name="footer"></slot>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue';
import { debounce } from '@/utils/time';
import ResizeObserver from 'resize-observer-polyfill';

export default defineComponent({
  emits: ['ready'],
  props: {
    // 表头高度
    top: {
      type: Number,
      default: 27,
    }
  },
  setup(props, { emit }) {
    // 表格滚动区域宽高
    const scroll = ref({
      x: '100%',
      y: 'auto',
    })

    const scrollElement = ref<HTMLDivElement>();

    onMounted(() => {
      const onresize = debounce((entries: ResizeObserverEntry[]) => {
        for (const entry of entries) {
          const { height } = entry.contentRect;
          scroll.value.y = (height - props.top) + 'px';
        }
      }, 50);

      // 监听元素变化
      const resizeObserver = new ResizeObserver((entries: ResizeObserverEntry[]) => {
        onresize(entries);
      });

      if (scrollElement.value) {
        resizeObserver.observe(scrollElement.value);
      }

      emit('ready');
    })

    return {
      scroll,
      scrollElement,
    }
  },
})
</script>

<style lang="less">
@import './index.less';
</style>