<template>
  <div class=""></div>
</template>

<script lang="ts" setup>
import { onBeforeUnmount, ref, watch } from 'vue';
const props = withDefaults(
  defineProps<{
    el: HTMLElement;
    maxLen: number;
    curLen: number;
    hasMorePages: boolean;
    loadingMore: boolean;
  }>(),
  {}
);
const emit = defineEmits(['submit']);
const is_first = ref(true);
const ScrollEvent = () => {
  const { el, maxLen, curLen, hasMorePages, loadingMore } = props;
  const domHeight = el.scrollHeight;
  const domTop = el.scrollTop;
  const cliheight = el.clientHeight;
  if (domHeight - cliheight - domTop <= 20 && curLen > maxLen) {
    // 滚动到底部
    if (hasMorePages) {
      // 如果当前加载更多已经执行，return
      if (loadingMore) {
        return;
      }
      //   通知父组件
      emit('submit');
    }
  }
};
watch(
  () => props.el,
  (v) => {
    if (v && is_first.value) {
      is_first.value = false;
      ScrollLoad();
    }
  }
);
const ScrollLoad = () => {
  const { el, maxLen } = props;
  if (el && maxLen) {
    el.addEventListener('scroll', ScrollEvent);
  }
};

onBeforeUnmount(() => {
  const { el } = props;
  if (el) {
    el.removeEventListener('scroll', ScrollEvent);
  }
});
</script>

<style lang="less"></style>
