<template>
  <div ref="elSkeletonBoxRef" style="flex: 1; width: 100%; height: 100%">
    <el-skeleton v-if="rows > 0" :rows="rows <= 0 ? 8 : rows - 1" :animated="animated" :loading="loading" style="height: 100%"></el-skeleton>
  </div>
</template>

<script setup lang="ts">
  import { ElSkeleton } from 'element-plus';
  import { useThrottleFn } from '@vueuse/core';

  const props = defineProps({
    /** 组件的高度 */
    height: { type: Number as PropType<number | undefined>, default: undefined },
    /** 是否使用动画 */
    animated: { type: Boolean, default: true },
    /** 是否显示加载结束后的 DOM 结构	 */
    loading: { type: Boolean, default: true },
  });

  /** skeleton每一条的高度  */
  const skeletonRowHeight = 32;

  /** 一共渲染多少条 */
  const rows = ref(Math.trunc((props.height || 320) / skeletonRowHeight));
  watch(
    () => props.height,
    (val) => {
      if (typeof val === 'number') {
        rows.value = Math.trunc(val / skeletonRowHeight);
      }
    }
  );

  const elSkeletonBoxRef = ref<HTMLDivElement>();
  const myObserver = new ResizeObserver(
    useThrottleFn(() => {
      const divDom: HTMLDivElement | undefined = elSkeletonBoxRef.value;
      if (divDom) {
        rows.value = Math.trunc((divDom.clientHeight + skeletonRowHeight / 2) / skeletonRowHeight);
      }
    }, 50)
  );

  onMounted(() => {
    const divDom: HTMLDivElement | undefined = elSkeletonBoxRef.value || undefined;
    if (divDom) {
      setTimeout(() => {
        rows.value = Math.trunc((divDom.clientHeight + skeletonRowHeight / 2) / skeletonRowHeight);
      }, 10);
      elSkeletonBoxRef.value && myObserver.observe(divDom);
    }
  });

  onUnmounted(() => {
    myObserver.disconnect();
  });
</script>
