import { onMounted, onBeforeUnmount } from 'vue'

export function useRowClickStyle(tableRef: any, rowClass: string = 'row--clicked') {
  const handleMouseDown = (event: any) => {
    const trElement = event.target.closest('tr')
    if (trElement && trElement.hasAttribute('rowid')) {
      const rowId = trElement.getAttribute('rowid')
      const allRows = document.querySelectorAll(`tr[rowid="${rowId}"]`)
      allRows.forEach((row) => {
        row.classList.add(rowClass)
      })

      const handleMouseUp = () => {
        allRows.forEach((row) => {
          row.classList.remove(rowClass)
        })
        // 移除 mouseup 事件监听器
        document.removeEventListener('mouseup', handleMouseUp)
      }

      // 监听 mouseup 事件，抬起鼠标时移除类名
      document.addEventListener('mouseup', handleMouseUp)
    }
  }

  onMounted(() => {
    const gridElement = tableRef.value?.$el
    if (gridElement) {
      // 为表格添加 mousedown 事件监听器
      gridElement.addEventListener('mousedown', handleMouseDown)
    }
  })

  onBeforeUnmount(() => {
    const gridElement = tableRef.value?.$el
    if (gridElement) {
      gridElement.removeEventListener('mousedown', handleMouseDown)
    }
  })
}
