import { Ref, onBeforeUnmount, onMounted, ref } from 'vue'
import { addResizeListener, removeResizeListener } from '../dom'
import { debounce } from 'lodash-es'

export default function useElTableColumnWidth(
  selector: string,
): [Ref<HTMLElement | null>, Ref<number>, () => void] {
  // 返回值：元祖里添加第三个参数，实现二次渲染
  const tableWrapperRef = ref<HTMLDivElement | null>(null)
  const width = ref(0)
  // 清理事件监听器
  let cleanupResizeEventListener: (() => void) | undefined
  let cleanupThResizeEventListener: (() => void) | undefined

  let currentTh: HTMLElement | null = null
  const onThResize = () => {
    if (currentTh) width.value = currentTh.offsetWidth
  }
  // 监听目标列大小变化
  const watchThSizeChange = (th: HTMLElement) => {
    if (currentTh === th) return
    currentTh = th
    cleanupThResizeEventListener?.()
    addResizeListener(th, onThResize)
    cleanupThResizeEventListener = () => {
      removeResizeListener(th, onThResize)
      currentTh = null
    }
  }
  // 手动触发列宽更新
  const updateColumnWidth = () => {
    onTableWrapperResize()
  }
  // 表格容器大小变化监听
  const onTableWrapperResize = debounce(() => {
    const el = tableWrapperRef.value
    if (!el) return
    const th = el.querySelector(selector) as HTMLElement | null
    if (th) {
      width.value = th.offsetWidth
      watchThSizeChange(th)
    }
  }, 50)

  onMounted(() => {
    const el = tableWrapperRef.value
    if (!el) return
    cleanupResizeEventListener = () => {
      removeResizeListener(el, onTableWrapperResize)
    }
    addResizeListener(el, onTableWrapperResize)
  })

  onBeforeUnmount(() => {
    cleanupResizeEventListener?.()
    cleanupThResizeEventListener?.()
  })

  return [tableWrapperRef, width, updateColumnWidth]
}
