<template>
  <div
    class="single-long-image-serial-frames"
    :style="{
      width: frameWidth + 'px',
      height: props.height + 'px',
    }"
  >
    <img
      class="long-image"
      :style="{
        left: `calc(-${frameWidth}px * ${frameIdx})`,
      }"
      :src="props.imageSrc"
      alt=""
      draggable="false"
      @dragstart.prevent
    >
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'

const props = defineProps({
  imageSrc: {
    type: String,
    required: true,
  },
  totalWidth: {
    type: Number,
    required: true,
  },
  height: {
    type: Number,
    required: true,
  },
  frameNumber: {
    type: Number,
    required: true,
  },
  frameDuration: {
    type: Number,
    default: 41
  },
})

const frameWidth = ref(props.totalWidth / props.frameNumber)
console.assert(Number.isInteger(frameWidth.value), `序列帧的每帧宽度不是整数，可能导致播放时抖动！总宽度：${props.totalWidth}，帧数：${props.frameNumber}，每帧宽度：${frameWidth.value}`)

const frameIdx = ref(0)
let intervalId = null
onMounted(() => {
  intervalId = setInterval(() => {
    frameIdx.value++
    if (frameIdx.value === props.frameNumber) {
      frameIdx.value = 0
    }
  }, props.frameDuration)
})
onBeforeUnmount(() => {
  clearInterval(intervalId)
})

</script>

<style lang="less" scoped>
.single-long-image-serial-frames {
  position: absolute;
  overflow: hidden;
  pointer-events: none;
  > .long-image {
    position: absolute;
    height: 100%;
  }
}
</style>