import { ref, onUnmounted } from 'vue'

// 单例模式：所有实例共享同一个预览元素
let previewDiv: HTMLDivElement | null = null
let previewImg: HTMLImageElement | null = null
const show = ref(false)
let currentTarget: HTMLElement | null = null
let mousemoveHandler: ((ev: MouseEvent) => void) | null = null

// 初始化预览元素（只创建一次）
function initPreviewElement() {
  if (previewDiv) return

  previewDiv = document.createElement('div')
  previewDiv.style.position = 'fixed'
  previewDiv.style.zIndex = '9999999999999'
  previewDiv.style.display = 'none'
  previewImg = document.createElement('img')
  previewImg.style.width = '300px'
  previewDiv.appendChild(previewImg)
  document.body.appendChild(previewDiv)
}

// 清理函数：移除事件监听器和重置状态
function cleanup() {
  if (mousemoveHandler) {
    window.removeEventListener('mousemove', mousemoveHandler)
    mousemoveHandler = null
  }
  if (previewDiv) {
    previewDiv.style.display = 'none'
  }
  show.value = false
  currentTarget = null
}

// 导出清理函数，供路由切换时使用
export function cleanupImagePreview() {
  cleanup()
}

export default function useImagePreview() {
  // 确保预览元素已初始化
  initPreviewElement()

  // 创建 mousemove 处理器（如果还没有）
  if (!mousemoveHandler) {
    mousemoveHandler = (ev: MouseEvent) => {
      if (!currentTarget || !previewDiv) {
        cleanup()
        return
      }
      const rect = currentTarget.getBoundingClientRect()
      const inOrigin =
        ev.clientX >= rect.left &&
        ev.clientX <= rect.right &&
        ev.clientY >= rect.top &&
        ev.clientY <= rect.bottom

      const divRect = previewDiv.getBoundingClientRect()
      const inPreview =
        ev.clientX >= divRect.left &&
        ev.clientX <= divRect.right &&
        ev.clientY >= divRect.top &&
        ev.clientY <= divRect.bottom

      if (!inOrigin && !inPreview) {
        cleanup()
      }
    }
  }

  const mouseoverImg = (
    ev: MouseEvent,
    url: string,
    newWitdh?: string,
    newBorder?: boolean,
    positionBOOTTOM?: boolean,
  ) => {
    if (!previewDiv || !previewImg) return
    ev.preventDefault()
    if (show.value === true) return
    previewImg.src = url
    previewImg.style.backgroundColor = '#eee'
    if (newBorder) previewImg.style.border = '1px solid #eee'
    if (newWitdh) previewImg.style.width = newWitdh
    const cW = document.body.clientWidth
    const cH = document.body.clientHeight
    const cX = ev.clientX
    const cY = ev.clientY
    let x: number, y: number
    if (cY + 150 >= cH) y = cY - 300
    else y = cY - 150
    if (cX + 300 >= cW) x = cX - 300
    else x = cX + 60
    previewImg.onload = () => {
      if (!previewDiv || !previewImg) return
      previewDiv.style.left = x + 'px'
      previewDiv.style.top = y + 'px'
      previewDiv.style.display = 'block'
      if (positionBOOTTOM) {
        // 获取图片实际尺寸
        const imgWidth = previewImg.clientWidth
        const imgHeight = previewImg.clientHeight

        // 计算新位置（鼠标正下方）
        let x = cX / 2
        let y = cY + 150 // 20px 垂直偏移

        // 边界检测
        if (x + imgWidth > cW) {
          x = cW - imgWidth - 10
        }
        if (x < 0) {
          x = 10
        }
        if (y + imgHeight > cH) {
          y = cY - imgHeight - 20
        }
        if (y < 0) {
          y = 10
        }
        previewDiv.style.left = x + 'px'
        previewDiv.style.top = y + 'px'
      }
      show.value = true
      currentTarget = ev.currentTarget as HTMLElement
      if (mousemoveHandler) {
        window.addEventListener('mousemove', mousemoveHandler)
      }
    }
  }

  const mouseleaveImg = () => {
    // 在 mouseleave 时也要清理事件监听器
    cleanup()
  }

  // 组件卸载时清理（防止内存泄漏）
  onUnmounted(() => {
    cleanup()
  })

  return { mouseoverImg, mouseleaveImg }
}
