<template>
  <div
    class="frames-wrap"
  >
    <img
      v-for="index of frameTotalNum"
      v-show="frameCurNum === index - 1 ||
        frameCurNum - 1 === index - 1
      "
      :key="index"
      :src="imageSrcFunc(index)"
      alt=""
      @load="onFrameLoad(index - 1)"
      @error="onFrameError(index - 1)"
    >
  </div>
</template>

<script>
export default {
  props: {
    frameTotalNum: {
      type: Number,
      required: true,
    },
    frameInterval: {
      type: Number,
      default: 41.667
    },
    imageSrcFunc: {
      type: Function,
      required: true,
    }
  },
  emits: ['over'],
  data() {
    return {
      frameCurNum: 0,
      frameStateList: new Array(this.frameTotalNum),
      frameIntervalId: null,
      isPlaying: false,
    }
  },
  mounted() {
  },
  unmounted() {
    clearInterval(this.frameIntervalId)
  },
  methods: {
    onFrameLoad(idx) {
      this.frameStateList[idx] = true
    },
    onFrameError(idx) {
      this.frameStateList[idx] = false
    },
    play() {
      if (this.isPlaying) {
        return
      }
      this.isPlaying = true
      this.frameCurNum = 0
      this.frameIntervalId = setInterval(() => {
        const frameNumBackup = this.frameCurNum
        this.frameCurNum++
        if (this.frameCurNum === this.frameTotalNum) {
          clearInterval(this.frameIntervalId)
          this.isPlaying = false
          this.$emit('over')
          return
        }

        while (this.frameStateList[this.frameCurNum] === false) {
          this.frameCurNum++
        }
        if (this.frameStateList[this.frameCurNum] === undefined) {
          this.frameCurNum = frameNumBackup
        }
      }, this.frameInterval)
    },
    stop() {
      if (!this.isPlaying) {
        return
      }
      clearInterval(this.frameIntervalId)
      this.isPlaying = false
      this.frameCurNum = 0
    },
  },
}
</script>

<style lang="less" scoped>
  .frames-wrap {
    > img {
      width: 100%;
      height: 100%;
      object-fit: contain;
    }
  }
</style>