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 {

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

  overflowBubble: OverflowBubble;

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

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

    if (!bubbleRecords?.length) return;

    const newBubbleKeys = [];
    bubbleRecords.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);
      }
    });

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

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

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

        // 找到bubbleArr第一个空的位置
        let emptyPos = -1;
        for (let i = 0; i < 4; 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() {
  }

}
