import { nextTick } from 'vue'

function useScroll() {
  let scrollRef = null

  const scrollToBottom = async () => {
    await nextTick()
    if (scrollRef)
      scrollRef.scrollTop = scrollRef.scrollHeight
  }

  const scrollToTop = async () => {
    await nextTick()
    if (scrollRef)
      scrollRef.scrollTop = 0
  }

  const scrollToBottomIfAtBottom = async () => {
    await nextTick()
    if (scrollRef) {
      const threshold = 100 // 阈值，表示滚动条到底部的距离阈值
      const distanceToBottom = scrollRef.scrollHeight - scrollRef.scrollTop - scrollRef.clientHeight
      if (distanceToBottom <= threshold)
        scrollRef.scrollTop = scrollRef.scrollHeight
    }
  }

  return {
    scrollRef,
    scrollToBottom,
    scrollToTop,
    scrollToBottomIfAtBottom,
  }
}

export default useScroll
