<template>
  <JsvSpriteLoader
    v-if="show"
    :imageUrl="spriteSrc"
    :configUrl="jsonUrl"
    :onConfigReady="preloadCallback"
    :noNeedResource="false"
  >
    <JsvSpriteAnim
      ref="spriteController"
      :spriteInfo="spriteJsonInfo"
      :loop="repeat"
      :duration="duration"
      :imageUrl="spriteSrc"
      :spriteFrameSize="spriteOriginSize"
      :viewSize="{ w: layout.width, h: layout.height }"
      :onAnimEnd="onAnimEnd"
      :autostart="true"
    />
  </JsvSpriteLoader>
</template>

<script setup>
import { computed, shallowRef, onMounted } from "vue";
import { JsvSpriteAnim, JsvSpriteLoader, JsvSpriteTools } from "jsview";

const props = defineProps({
  spriteSrc: {
    type: String,
  },
  repeat: {
    type: Number,
  },
  layout: {
    type: Object,
  },
  onEnd: {
    type: Function,
  },
  duration: {
    type: Number,
  },
});

const spriteController = shallowRef();
const show = shallowRef(true);

const jsonUrl = computed(() => {
  return props.spriteSrc + ".json";
});

const _formatInfo = (config_json) => {
  const info = {
    frames: [],
    meta: {
      size: config_json.meta.size,
    },
  };

  let frames_ref = info.frames;

  for (let i = 0; i < config_json.frames.length; i++) {
    const target = config_json.frames[i].spriteSourceSize;
    frames_ref.push({
      target,
      source: config_json.frames[i].frame,
    });
  }

  return { info };
};

function onAnimEnd() {
  show.value = false;
  props.onEnd?.();
}

const spriteJsonInfo = shallowRef();
const spriteOriginSize = shallowRef();
const preloadCallback = (config_json, resolve_set) => {
  spriteJsonInfo.value = _formatInfo(config_json).info;

  // 调整设置的原图尺寸设置
  const guessSize = JsvSpriteTools.guessOriginSize(spriteJsonInfo.value);
  spriteOriginSize.value = guessSize;
  resolve_set(); // 通知loader数组设置完成
};

onMounted(() => {});
</script>
