import { ref } from 'vue'

export default function useImagePreview() {
  const show = ref(false)
  const div = document.createElement('div')
  div.style.position = 'fixed'
  div.style.zIndex = '9999999999999'
  div.style.display = 'none'
  const img = document.createElement('img')
  img.style.width = '300px'
  div.appendChild(img)
  document.body.appendChild(div)

  let currentTarget: HTMLElement | null = null

  const mousemoveHandler = (ev: MouseEvent) => {
    if (!currentTarget) 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 = div.getBoundingClientRect()
    const inPreview =
      ev.clientX >= divRect.left &&
      ev.clientX <= divRect.right &&
      ev.clientY >= divRect.top &&
      ev.clientY <= divRect.bottom

    if (!inOrigin && !inPreview) {
      div.style.display = 'none'
      show.value = false
      window.removeEventListener('mousemove', mousemoveHandler)
      currentTarget = null
    }
  }

  const mouseoverImg = (
    ev: MouseEvent,
    url: string,
    newWitdh?: string,
    newBorder?: boolean,
    positionBOOTTOM?: boolean,
  ) => {
    ev.preventDefault()
    if (show.value === true) return
    img.src = url
    img.style.backgroundColor = '#eee'
    if (newBorder) img.style.border = '1px solid #eee'
    if (newWitdh) img.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
    img.onload = () => {
      div.style.left = x + 'px'
      div.style.top = y + 'px'
      div.style.display = 'block'
      if (positionBOOTTOM) {
        // 获取图片实际尺寸
        const imgWidth = img.clientWidth
        const imgHeight = img.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
        }
        div.style.left = x + 'px'
        div.style.top = y + 'px'
      }
      show.value = true
      currentTarget = ev.currentTarget as HTMLElement
      window.addEventListener('mousemove', mousemoveHandler)
    }
  }

  const mouseleaveImg = () => {
    if (show.value === false) return
    div.style.display = 'none'
    show.value = false
  }

  return { mouseoverImg, mouseleaveImg }
}
