import type { Ref } from 'vue'

import { useEventListener } from 'vue-hooks-plus'
import { throttle } from 'lodash-es'

/**
 * 处理画布移动方法
 * @param element 画布元素
 */
export const useCanvasMove = (element: Ref<HTMLDivElement | undefined>) => {
  let flag = false
  /**
   * 鼠标按下事件
   */
  const onMouseDown = (e: MouseEvent) => {
    const target = e?.target as Element | null
    if (
      target?.closest('.stage-title') ||
      target?.closest('.edit-box') ||
      target?.closest('.component-content') ||
      target?.closest('.component-wrapper') ||
      target?.closest('.scaleplate-horizontal') ||
      target?.closest('.scaleplate-vertical') ||
      target?.closest('.refer-line-img') ||
      target?.closest('.workspace-bottom') ||
      target?.closest('.refer-line') ||
      target?.closest('.ignore-click') ||
      target?.closest('.moveable-area') ||
      target?.closest('.moveable-control') ||
      target?.closest('.moveable-edge')
    ) {
      return
    }

    // 当前未按下ctrl且是鼠标左键
    if (!e.ctrlKey && e.button === 0) {
      flag = true
    } else {
      flag = false
    }
  }

  /**
   * 鼠标移动事件
   */
  const onMouseMove = (e: MouseEvent) => {
    if (flag) {
      const moveX = -e.movementX
      const moveY = -e.movementY
      element.value?.scrollBy(moveX, moveY)
    }
  }

  /**
   * 鼠标抬起事件
   */
  const onMouseUp = () => {
    flag = false
  }

  useEventListener('mousedown', throttle(onMouseDown, 10), { target: element })
  useEventListener('mousemove', throttle(onMouseMove, 0), { target: element })
  useEventListener('mouseup', throttle(onMouseUp, 10))
}
