<script setup lang="ts">
import { onMounted, reactive, ref, watch } from 'vue'
import {
  getSlideOffset,
  slideInit,
  slideReset,
  slideTouchEnd,
  slideTouchMove,
  slideTouchStart,
} from '@/utils/slide'
import { SlideType } from '@/utils/const_var'
import { _css } from '@/utils/dom'

const props = defineProps({
  index: { type: Number, default: 0 },
  changeActiveIndexUseAnim: { type: Boolean, default: true },
  name: { type: String, default: 'SlideVertical' },
})

const emit = defineEmits<{ 'update:index': [number] }>()

const slideListEl = ref<HTMLElement | null>(null)

const state = reactive({
  judgeValue: 20,
  type: SlideType.VERTICAL,
  name: props.name,
  localIndex: props.index,
  needCheck: true,
  next: false,
  isDown: false,
  start: { x: 0, y: 0, time: 0 },
  move: { x: 0, y: 0 },
  wrapper: { width: 0, height: 0, childrenLength: 0 },
})

watch(
  () => props.index,
  (newVal) => {
    if (state.localIndex !== newVal && slideListEl.value) {
      state.localIndex = newVal
      if (props.changeActiveIndexUseAnim) {
        _css(slideListEl.value, 'transition-duration', '300ms')
      }
      _css(
        slideListEl.value,
        'transform',
        `translate3d(0, ${getSlideOffset(state, slideListEl.value)}px, 0)`,
      )
    }
  },
)

onMounted(() => {
  if (slideListEl.value) slideInit(slideListEl.value, state)
})

function touchStart(e: PointerEvent) {
  if (slideListEl.value) slideTouchStart(e, slideListEl.value, state)
}

function touchMove(e: PointerEvent) {
  if (slideListEl.value) slideTouchMove(e, slideListEl.value, state)
}

function touchEnd(e: PointerEvent) {
  slideTouchEnd(e, state)
  if (slideListEl.value) slideReset(e, slideListEl.value, state, emit)
}
</script>

<template>
  <div class="slide vertical">
    <div
      ref="slideListEl"
      class="slide-list flex-direction-column"
      @pointerdown.prevent="touchStart"
      @pointermove.prevent="touchMove"
      @pointerup.prevent="touchEnd"
    >
      <slot />
    </div>
  </div>
</template>
