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";

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

@observer
export class BubbleMgr extends Base {

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

  overflowBubble: OverflowBubble;

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

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

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

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


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

      let bubble = BubbleMgr.bubbleMap.get(id);
      if (!bubble) {
        bubble = this.addChild(new Bubble());

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

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

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

  }

  onDestroy() {

  }

}
