import { onMounted, nextTick, onUnmounted, ref, Ref, computed } from 'vue'

function debounce(handler: CallableFunction, delay: number) {
  let timer: number | undefined = undefined
  return () => {
    clearTimeout(timer)
    timer = setTimeout(handler, delay || 0)
  }
}

export default function useTableScrollY(unavailableHeight = 0) {
  const pageContentWrapRef = ref<HTMLElement | null>(null)
  const pageContentWrapOffsetHeight = ref(0)
  const tableContentY = computed(() => {
    // 页面高度 - 不可用的高度
    return pageContentWrapOffsetHeight.value - unavailableHeight
  })

  const updatePageContentWrapOffsetHeightWithDebounce = debounce(() => {
    updatePageContentWrapOffsetHeight(pageContentWrapRef, pageContentWrapOffsetHeight)
  }, 100)

  onMounted(() => {
    nextTick(() => {
      setTimeout(() => {
        updatePageContentWrapOffsetHeight(pageContentWrapRef, pageContentWrapOffsetHeight)
        setTimeout(() => {
          updatePageContentWrapOffsetHeight(pageContentWrapRef, pageContentWrapOffsetHeight)
          setTimeout(() => {
            updatePageContentWrapOffsetHeight(pageContentWrapRef, pageContentWrapOffsetHeight)
          }, 200)
        }, 200)
      }, 200)
    })
    window.addEventListener('resize', updatePageContentWrapOffsetHeightWithDebounce)
  })

  onUnmounted(() => {
    window.removeEventListener('resize', updatePageContentWrapOffsetHeightWithDebounce)
  })

  function updatePageContentWrapOffsetHeight(
    pageContentWrapRef: Ref<HTMLElement | null>,
    pageContentWrapOffsetHeight: Ref<number>,
  ) {
    if (pageContentWrapRef.value) {
      pageContentWrapOffsetHeight.value = pageContentWrapRef.value.offsetHeight || 0
    }
  }

  return {
    tableContentY,
    pageContentWrapRef,
  }
}
