import { ref } from 'vue'
import { throttle } from 'lodash-es'
import { MaybeComputedElementRef, useResizeObserver } from '@vueuse/core'

export function useBackBottom(el: MaybeComputedElementRef, cb: () => void) {
  const visible = ref(false)
  const lastScrollTop = ref(0)

  // 点击回到底部
  function clickBackBottom() {
    visible.value = false
    cb()
  }

  // 滚动处理逻辑
  function handleScrollMessageContainer(e: Event) {
    const target = e.target as HTMLElement

    const currentScrollTop = target.scrollTop

    // 向上滚动，显示返回底部图标
    if (currentScrollTop < lastScrollTop.value) {
      visible.value = true
    }

    // 是否滚动触底
    if (currentScrollTop + target.clientHeight >= target.scrollHeight - 5) {
      visible.value = false
    }

    lastScrollTop.value = currentScrollTop
  }

  // 节流处理滚动事件
  const throttleScrollContainer = throttle(handleScrollMessageContainer, 100, { leading: true })

  // 节流处理容器resize事件
  const throttledResizeCallback = throttle(
    (entries) => {
      const entry = entries[0]
      const { clientHeight, scrollHeight } = entry.target

      if (clientHeight >= scrollHeight && !visible.value) {
        visible.value = false
      }
    },
    300,
    { leading: true, trailing: true },
  )

  // 监听容器变化
  useResizeObserver(el, throttledResizeCallback)

  return { visible, clickBackBottom, throttleScrollContainer }
}
