<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 { v4 } from 'uuid';
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 uuid = v4();
    const scrollElement = ref<HTMLDivElement>();

    onMounted(() => {
      // 监听元素变化
      const resizeObserver = new ResizeObserver((entries: ResizeObserverEntry[]) => {
        debounce(() => {
          for (const entry of entries) {
            const { height } = entry.contentRect;
            scroll.value.y = (height - props.top) + 'px';
          }
        }, 50, uuid);
      });
      if (scrollElement.value) {
        resizeObserver.observe(scrollElement.value);
      }
      emit('ready');
    })

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

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