<script setup lang="ts">
const props = withDefaults(
  defineProps<{
    name: string
    frames: number
    rate?: number
    autoPlay?: boolean
    loop?: boolean
  }>(),
  {
    rate: 24,
    frames: 0,
    autoPlay: true,
    loop: false,
  },
)

const OSS_URL = import.meta.env.VITE_OSS_URL

const frameDuration = 1000 / props.rate // 每帧持续时间（毫秒）
let currentFrame = 0 // 当前帧
let lastFrameTime = 0 // 结束帧

const canvas = ref()
let images: anyObj[] = []
function init() {
  // 加载所有帧图像
  images = Array(props.frames)
    .fill(null)
    .map((i, idx) => {
      const img = new Image()
      img.src = `${OSS_URL}/animation/sequence/${props.name}/frames_${idx + 1}.png`
      return img
    })
}

// 更新动画帧
function draw() {
  if (!canvas.value) return
  const now = Date.now()
  const elapsed = now - lastFrameTime
  const ctx = canvas.value.getContext('2d')
  if (elapsed >= frameDuration) {
    // 清空画布
    ctx.clearRect(0, 0, canvas.value.width, canvas.value.height)
    // 绘制当前帧
    ctx.drawImage(images[currentFrame], 0, 0, canvas.value.width, canvas.value.height)
    // 更新到下一帧
    if (props.loop) {
      currentFrame = (currentFrame + 1) % images.length
    } else {
      if (currentFrame < images.length - 1) {
        currentFrame++
      } else {
        return // 结束动画
      }
    }
    lastFrameTime = now
  }
  requestAnimationFrame(draw)
}

function pause() {
  // 停止动画
}

function play(frames = 0) {
  if (frames === 0) {
    currentFrame = 0
    lastFrameTime = 0
  }
  draw()
}

onMounted(async () => {
  if (!props.name) return console.error('name is required')
  if (!props.frames) return console.error('frames is required')

  init()
  props.autoPlay && draw()
})

defineExpose({
  play,
  // pause,
})
</script>

<template>
  <!--  -->
  <canvas ref="canvas" class="canvas" :width="1920" :height="1200"></canvas>
</template>

<style lang="scss" scoped>
.canvas {
  width: 100vw;
  // margin: auto 0;
  // height: 100%;
}
</style>
