import { ref, onMounted, onUnmounted, nextTick } from 'vue'

export const resizeListenerAndSwipeIndicator = (
  charts: any,
  getData: any
) => {
  const horizontalFlag = ref(true)
  const active = ref(0)
  const swipe = ref()
  const horizontalDiv = ref()
  onMounted(() => {
    console.log(swipe.value);
    
    if (horizontalDiv.value) {
      horizontalDiv.value.addEventListener('touchstart', handleTouchStart)
      horizontalDiv.value.addEventListener('touchmove', handleTouchMove)
      horizontalDiv.value.addEventListener('touchend', handleTouchEnd)
    }
  })

  onUnmounted(() => {
    disposeAll()
    if (horizontalDiv.value) {
      horizontalDiv.value.removeEventListener('touchstart', handleTouchStart)
      horizontalDiv.value.removeEventListener('touchmove', handleTouchMove)
      horizontalDiv.value.removeEventListener('touchend', handleTouchEnd)
    }
  })

  let startX = 0
  let startY = 0
  let isSwiping = false

  const handleTouchStart = (event: TouchEvent) => {
    if (horizontalFlag.value) return
    const touch = event.touches[0]
    startX = touch.pageX
    startY = touch.pageY
    isSwiping = true
  }

  const handleTouchMove = (event: TouchEvent) => {
    if (!isSwiping || horizontalFlag.value) return
    const touch = event.touches[0]
    const deltaX = touch.pageX - startX
    const deltaY = touch.pageY - startY
    if (Math.abs(deltaX) > Math.abs(deltaY)) {
      if (deltaX > 0) {
        next()
      } else if (deltaX < 0) {
        pre()
      }
      isSwiping = false
    }
  }

  const handleTouchEnd = () => {
    if (horizontalFlag.value) {
      isSwiping = false
    }
  }

  const disposeAll = () => {
    charts.value.forEach((chart: any) => {
      chart && chart.dispose()
      chart = null
    })
  }
  const onChange = (e: number) => {
    active.value = e
    const chart = charts.value[e]
    chart && chart.dispose()
    getData(active.value)
  }
  const showHorizontalChart = () => {
    horizontalFlag.value = !horizontalFlag.value
    if (!swipe.value) {
      nextTick(() => {
        charts.value[active.value].resize()
      })
    } else {
      disposeAll()
      swipe.value && swipe.value.resize()
      getData(active.value)
    }
  }
  const next = () => {
    swipe.value.next()
  }
  const pre = () => {
    swipe.value.prev()
  }
  return {
    onChange,
    active,
    next,
    pre,
    swipe,
    disposeAll,
    showHorizontalChart,
    horizontalFlag,
    horizontalDiv
  }
}
