import { ref, type Ref, reactive, computed } from 'vue'
import {
  getCenter
} from '../utils/index'
import {
  getDistance,
  getCenterByPoints
} from '../utils/algorithm'
import * as variables from './variables'
const {
  actives,
  x,
  y,
  oldX,
  oldY,
  scale,
  pageX,
  pageY,
  startX,
  startY,
  xSelection,
  ySelection,
  state
} = variables
let { svgWrap } = variables


let oldTiem = new Date().getTime()
let isTouchpad = false
let canMove = false

let oldDistance: number | undefined = 0 // 触摸时，上一次记录的2点距离
let distance = 0 // 触摸时，2点距离
let touchCenter: {
  offsetX?: number
  offsetY?: number
} = {} // 双指触摸缩放中心点

// 右键
function onMouseContextmenu(e: MouseEvent) {
  e.stopPropagation()
  e.preventDefault()
}

// 拖动 - 开始
function EventStart(e: any) {
  oldTiem = new Date().getTime()
  e.stopPropagation()
  if (!e.touches) e.preventDefault()
  pageX.value = e.pageX ?? e.touches[0].pageX
  pageY.value = e.pageY ?? e.touches[0].pageY
  oldX.value = x.value
  oldY.value = y.value
  canMove = true
}
// 拖动 - 中
function EventMove(e: any) {
  e.stopPropagation()
  if (!e.touches) e.preventDefault()
  if (!canMove) return
  x.value = (e.pageX ?? e.touches[0].pageX) - pageX.value + oldX.value
  y.value = (e.pageY ?? e.touches[0].pageY) - pageY.value + oldY.value
}
// 拖动 - 结束
function EventEnd(e: any) {
  if (!e.touches) e.preventDefault()
  // this.dragging = false
  canMove = false
}
function onTouchStart(e: TouchEvent) {
  distance = 0
  EventStart(e)
  e.preventDefault()
  document.addEventListener('touchmove', onTouchMove, false)
  document.addEventListener('touchend', onTouchEnd, false)
}
function onMouseDown(e: MouseEvent) {
  EventStart(e)
  document.addEventListener('mousemove', onMouseMove, false)
  document.addEventListener('mouseup', onMouseUp, false)
}
function onMouseMove(e: MouseEvent) {
  EventMove(e)
}
function onTouchMove(e: TouchEvent) {
  if (e.touches?.length === 2) {
    onTouchPinchZoom(e)
    return
  }
  EventMove(e)
}
function onMouseUp(e: MouseEvent) {
  EventEnd(e)
  document.removeEventListener('mousemove', onMouseMove)
  document.removeEventListener('mouseup', onMouseUp)
}
function onTouchEnd(e: TouchEvent) {
  touchCenter = {}
  oldDistance = undefined
  EventEnd(e)
  if (e.touches?.length) return
  document.removeEventListener('touchmove', onTouchMove, false)
  document.removeEventListener('touchend', onTouchEnd, false)
}

// 修改缩放和坐标
function getZoomXY(sc: number, { offsetX, offsetY }) {
  // 如果通过触控板缩放
  // if (isTouchpad) {
  //   sc = sc / 5
  // }
  sc = sc * 0.2
  if (scale.value + sc < 0.1) {
    sc = 0.1 - scale.value
  }
  // 上次缩放量
  const s1 = scale.value
  scale.value += sc
  // 本次缩放量
  const s = scale.value
  // 对象在缩放后移动量
  const dx = (1 - s / s1) * (offsetX - x.value)
  const dy = (1 - s / s1) * (offsetY - y.value)
  // 得到缩放后对象偏移点
  x.value += dx
  y.value += dy
}
// 滚轮 - 滚动 - 上下左右
function onWheel(e: WheelEvent) {
  e.preventDefault()
  e.stopPropagation()
  if (e.ctrlKey) {
    onMouseWheelZoom(e)
    return
  }
  y.value = y.value - e.deltaY
  x.value = x.value - e.deltaX
}
// 滚轮 - 缩放
function onMouseWheelZoom(e: WheelEvent) {
  if (!Number.isInteger(e.deltaY)) {
    // 使用触摸板缩放
    isTouchpad = true
  }
  getZoomXY(Math.sign(-e.deltaY) * 0.1, e)
  isTouchpad = false
}
// 双指 - 缩放
function onTouchPinchZoom(e: TouchEvent) {
  const [p1, p2] = e.touches
  const [offsetX, offsetY] = getCenterByPoints([p1.pageX, p1.pageY], [p2.pageX, p2.pageY])
  let diffLeft = 0
  let diffTop = 0
  let parent: HTMLElement | null | undefined = svgWrap?.parentElement
  if (touchCenter.offsetX === undefined) {
    while (parent) {
      diffLeft += parent?.offsetLeft ?? 0
      diffTop += parent?.offsetTop ?? 0
      parent = (parent?.offsetParent ?? parent?.parentElement) as HTMLElement | null
    }
    touchCenter = { offsetX: offsetX - diffLeft, offsetY: offsetY - diffTop }
  }
  distance = getDistance([p1.pageX, p1.pageY], [p2.pageX, p2.pageY])
  if (oldDistance === undefined) oldDistance = distance
  getZoomXY(Math.sign((distance - oldDistance)) * 0.1, { offsetX: touchCenter.offsetX, offsetY: touchCenter.offsetY })
  oldDistance = distance
}
// 缩放+-
export function zoomSize(type: number) {
  if (!(svgWrap)) return
  switch (type) {
    case 1:
      // 缩小
      getZoomXY(-0.5, {
        offsetX: svgWrap?.width.baseVal.value / 2,
        offsetY: svgWrap?.height.baseVal.value / 2
      })
      break
    case 2:
      // 放大
      getZoomXY(0.5, {
        offsetX: svgWrap?.width.baseVal.value / 2,
        offsetY: svgWrap?.height?.baseVal?.value / 2
      })
      break
    case 3:
      // 放大
      getZoomXY((1 - scale.value) * 5, {
        offsetX: svgWrap?.width.baseVal.value / 2,
        offsetY: svgWrap?.height?.baseVal?.value / 2
      })
      break
    default:
      // 重置
      // resetPosition()
      break
  }
}
// 重置位置缩放
export function resetPosition(nodeConfig) {
  // const nodeConfig = inject<any>('nodeConfig')
  // console.log(nodeConfig)
  const coords = getCenter(nodeConfig, svgWrap)
  x.value = coords.x
  y.value = coords.y
  scale.value = coords.scale
}

// 导出变量

// let svgWrap: SVGSVGElement | null = null
// 初始化
export function init(svgWrapRef: Ref<SVGSVGElement> | Ref<null>) {
  if (svgWrapRef?.value) {
    console.log('init svg')
    svgWrap = svgWrapRef.value
    svgWrap.addEventListener('mousedown', onMouseDown, false)
    svgWrap.addEventListener('touchstart', onTouchStart, false)
    svgWrap.addEventListener('contextmenu', onMouseContextmenu, false)
    svgWrap.addEventListener('wheel', onWheel, { passive: false })
  }
}
export function destroy() {
  svgWrap?.removeEventListener('mousedown', onMouseDown)
  svgWrap?.removeEventListener('wheel', onWheel)
}