import { Base } from "@/pages/HomePage/Top/base/Base.ts";
import { observer, reactor } from "@/pages/HomePage/Top/mobx/decorators.ts";
import store from "@/store/store.ts";
import { Bubble, IBubbleInfo } from "@/pages/HomePage/Top/Components/Bubble.ts";
import { OverflowBubble } from "@/pages/HomePage/Top/Components/OverflowBubble.ts";
import { handleLogExposure } from "@/MD.ts";
import { PlantGameBubble } from "@/pages/HomePage/Top/Components/PlantGameBubble.ts";

const posArr = [
  { x: 570, y: 250 },
  { x: 675, y: 450 },
  // { x: 90, y: 440 },
  { x: 645, y: 660 },
]

@observer
export class BubbleMgr extends Base {

  bubbleArr: Bubble[] = [];
  bubbleMap: Map<string, Bubble> = new Map();

  overflowBubble: OverflowBubble;
  plantGameBubble: PlantGameBubble;

  onLoad() {
    this.overflowBubble = this.addChild(new OverflowBubble());
    this.plantGameBubble = this.addChild(new PlantGameBubble());
  }

  @reactor(() => store.indexData.bubbleRecords)
  updateBubble(bubbleRecords: IBubbleInfo[]) {

    if (!bubbleRecords?.length) return;

    const bubbles = bubbleRecords.slice(0, posArr.length);

    const newBubbleKeys = [];
    bubbles.forEach((info) => newBubbleKeys.push(info.id));

    // 找到bubbleArr中不在newBubbleKeys中的bubble
    this.bubbleArr.forEach((bubble, i) => {
      if (bubble && !newBubbleKeys.includes(bubble.id)) {
        bubble.destroy();
        this.bubbleArr[i] = null;
        this.bubbleMap.delete(bubble.id);
      }
    });

    // 更新数据
    bubbles.forEach((info, index) => {
      const { id } = info;

      let bubble = this.bubbleMap.get(id);

      if (!bubble) {
        bubble = this.addChild(new Bubble());
        handleLogExposure(3);

        // 找到bubbleArr第一个空的位置
        let emptyPos = -1;
        for (let i = 0; i < posArr.length; i++) {
          if (!this.bubbleArr[i]) {
            emptyPos = i;
            break;
          }
        }

        bubble.position.set(posArr[emptyPos].x, posArr[emptyPos].y)
        bubble.ideaEffect(150 * index, Math.random() > 0.5 ? 1 : -1);

        this.bubbleArr[emptyPos] = bubble;
        this.bubbleMap.set(id, bubble);
      }
      bubble.setInfo(info);
    });

  }

  onDestroy() {
  }

}
