<script lang="ts" setup>
import { onMounted, onUnmounted } from 'vue';
import { Application, Container, Assets, Sprite } from 'pixi.js';
import { Spine } from '@esotericsoftware/spine-pixi-v8';
let app: Application;
let container: Container;

onMounted(async () => {
  // 在组件挂载后初始化 PixiJS
  app = new Application();

  // 初始化应用
  await app.init({
    // background: '#1099bb',
    width: 640,
    height: 480,
    backgroundAlpha: 0,
  });

  // 将画布添加到指定容器而不是 document.body
  const pixiContainer = document.getElementById('pixi-container');
  if (pixiContainer) {
    pixiContainer.appendChild(app.canvas);
  }
  try {
    // 使用本地资源文件
    const resource = await Assets.load('/public/cat.json');
    console.log(resource);
    const data = { "skeletonData": resource };
    const animation = new Spine(data);

    // 设置位置
    animation.x = app.screen.width / 2;
    animation.y = app.screen.height / 2;

    app.stage.addChild(animation);

    // 播放动画
    animation.state.setAnimation(0, 'run', true);
    animation.state.timeScale = 0.1;
    animation.autoUpdate = true;
  } catch (error) {
    console.error('Failed to load spine animation:', error);
  }

  // 创建容器
  container = new Container();
  app.stage.addChild(container);

  // 加载纹理
  const texture = await Assets.load('https://pixijs.com/assets/bunny.png');

  for (let i = 0; i < 25; i++) {
    const bunny = new Sprite(texture);
    bunny.x = (i % 5) * 40;
    bunny.y = Math.floor(i / 5) * 40;
    container.addChild(bunny);
  }

  // 居中容器
  container.x = app.screen.width / 2;
  container.y = app.screen.height / 2;
  container.pivot.x = container.width / 2;
  container.pivot.y = container.height / 2;

  // 添加动画
  app.ticker.add((time) => {
    container.rotation -= 0.01 * time.deltaTime;
  });
});

onUnmounted(() => {
  // 清理 PixiJS 应用
  if (app) {
    app.destroy(true, true);
  }
});
</script>

<template>
  <div id="pixi-container" style="width: 640px; height: 480px">
    <!-- PixiJS 画布将被添加到这里 -->
  </div>
</template>
