<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
  },
  loop: {
    type: Boolean,
    default: true,
  }
})

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

const emit = defineEmits(['over'])

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

</script>

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