<template>
  <canvas 
    id="villageTree"
    type="2d"
    :width="`${systemInfo.windowWidth}px`" 
    :height="`${HEIGHT}px`" 
    :style="{
      width: systemInfo.windowWidth + 'px',
      height: HEIGHT + 'px',
    }"
    @touchstart="render.events.handleTouchStart"
    @touchmove="render.events.handleTouchMove"
    @touchend="render.events.handleTouchEnd"
    @touchcancel="render.events.handleTouchCancel"
  />
</template>

<script lang="ts" setup>
import { MiniRender } from '@/components/canvas/MiniRender';
import { UniWeappRender } from '@/components/canvas/UniWeappRender';
import { RandomUtils } from '@imengyu/imengyu-utils';
import { getCurrentInstance, onBeforeUnmount, onMounted } from 'vue';

let currentText : MiniRender.Text | null = null;
let treeMain : MiniRender.Sprite | null = null;
const todoTreeText = '现在没有树的动画，树是静态的。';

const emit = defineEmits<{
  (e: 'fruitPick'): void;
}>();

const HEIGHT = 260;
const instance = getCurrentInstance();
const systemInfo = uni.getWindowInfo();
const render = new MiniRender.Scene(
  {
    canvas: new UniWeappRender('villageTree', instance),
    width: systemInfo.windowWidth,
    height: HEIGHT,
    backgroundColor: '#000',
  }, 
  async function() {
    const bg = new MiniRender.Sprite();
    bg.src = 'https://xy.wenlvti.net/app_static/images/village/TreeTestBg.jpg';
    bg.x = 0;
    bg.y = 0;
    bg.width = systemInfo.windowWidth;
    bg.height = HEIGHT;

    const text = new MiniRender.Text(todoTreeText, {
      fontSize: 20,
      color: '#000',
      align: 'center',
      wrap: 'wrap',
      maxWidth: this.precentXToPixel(0.8),
    });
    text.x = this.precentXToPixel(0.2);
    text.y = this.precentYToPixel(0.12);
    currentText = text;

    treeMain = new MiniRender.Sprite();
    treeMain.src = 'https://xy.wenlvti.net/app_static/images/home/tree/Level4.png';
    treeMain.width = this.precentXToPixel(0.60);
    treeMain.height = this.precentYToPixel(0.85);
    treeMain.x = (this.width - treeMain.width) / 2;
    treeMain.y = (this.height - treeMain.height);
    treeMain.interactive = true;

    render.root
      .add(bg)
      .add(text)
      .add(treeMain)
  },
  (dtMs: number) => {

  }
);

function createFruit() {
  if (!treeMain)
    return;
  
  const fruit = new MiniRender.AnimateSprite({
    framerate: 7,
    images: ['https://xy.wenlvti.net/app_static/images/home/tree/AnimFruit.png'],
    frames: [
      [0, 0, 30, 30],
      [30, 0, 30, 30],
      [60, 0, 30, 30],
      [90, 0, 30, 30],
      [120, 0, 30, 30],
      [150, 0, 30, 30],
    ],
    animations: {
      default: { frames: [0, 1, 2, 3, 4, 5] },
    },
    playOnce: false,
    currentAnimation: 'walk',
  });
  fruit.play();
  //在树的区域内创建水果
  fruit.x = RandomUtils.genRandom(treeMain.x + treeMain.width / 2, treeMain.x + treeMain.width / 2);
  fruit.y = RandomUtils.genRandom(treeMain.y + treeMain.height / 2, treeMain.y + treeMain.height / 2);
  fruit.width = 30;
  fruit.height = 30;
  fruit.interactive = true;
  fruit.data = {
    type: 'fruit',
  };
  fruit.on('click', () => {
    emit('fruitPick');
  });
  render.root.add(fruit);
}

function createFruits(count: number) {
  //创建或者删除水果，使得数量等于count
  const fruitNodes = render.root.children.filter((child) => child.data?.type === 'fruit');
  const fruits = fruitNodes.length;
  if (fruits === count) {
    return;
  }
  if (fruits > count) {
    fruitNodes.slice(0, fruits - count).forEach((fruit) => {
      render.root.remove(fruit);
    });
    return;
  }
  for (let i = 0; i < count - fruits; i++) {
    createFruit();
  }
}

function removeAllFruit() {
  const fruits = render.root.children.filter(child => child.data?.type === 'fruit');
  fruits.forEach(fruit => {
    render.root.remove(fruit);
  });
}

function playStateAnimation(state: 'collect' | 'water' | 'fertilize' | 'task' | 'bless' | 'exchange') {
  //TODO: 播放动画
  if (currentText) {
    switch (state) {
      case 'collect':
        currentText.text = '拾果状态' + todoTreeText;
        removeAllFruit();
        break;
      case 'water':
        currentText.text = '浇水状态' + todoTreeText;
        break;
      case 'fertilize':
        currentText.text = '施肥状态' + todoTreeText;
        break;
      case 'task':
        currentText.text = '任务状态' + todoTreeText;
        break;
      case 'bless':
        currentText.text = '赐福状态' + todoTreeText;
        break;
      case 'exchange':
        currentText.text = '兑换状态' + todoTreeText;
        break;
    }
  }
}

defineExpose({
  reload: () => {
    render.root.removeAll();
    render.init();
  },
  createFruits,
  playStateAnimation,
});

onBeforeUnmount(() => {
  render.dispose();
});
onMounted(async() => {
  await render.init()
  render.start();  
});
</script>