import { Base, IBase } from "@/pages/HomePage/Top/base/Base.ts";
import { Assets, Container, Sprite, Text, Ticker } from "pixi.js";
import { Ease, Tween } from "@/core/tween";
import store from "@/store/store.ts";
import { prefixInteger } from "@/utils/utils.ts";
import { reactor, observer } from "@/pages/HomePage/Top/mobx/decorators.ts";

export interface IOverflowBubbleInfo {
  id: string;
  creditsNum: string,
  expireTime: number,
}

@observer
export class OverflowBubble extends Container implements IBase {

  text: Text;
  time: Text;
  id: string;

  constructor() {
    super();
    this.onLoad();
  }

  onLoad() {
    this.position.set(200, 240);

    this.addChild(new Sprite(Assets.get("红色气泡.png")))
      .anchor.set(0.5);

    this.text = this.addChild(new Text({
      text: `210`,
      style: {
        fontSize: 32,
        fill: 0xffffff,
        align: "center",
        fontWeight: "bold",
      }
    }));
    this.text.anchor.set(0.5);

    this.time = this.addChild(new Text({
      text: `23:59:59`,
      style: {
        fontSize: 21,
        fill: 0xffffff,
        align: "center",
      }
    }));
    this.time.anchor.set(0.5);
    this.time.position.set(0, 26);

    const tsp = this.addChild(new Sprite(Assets.get("标语.png")));
    tsp.anchor.set(0.5);
    tsp.position.set(0, 58);

    this.effect();

  }

  effect() {
    const y = this.y;
    Tween.get(this, { loop: true })
      .to({ y: y + 25 }, 2000, Ease.quadInOut)
      .to({ y: y }, 2000, Ease.quadInOut);
  }

  cdTarget = { cd: 0 }

  @reactor(() => store.indexData.overflowBubble)
  updateOverflow(info: IOverflowBubbleInfo) {
    if (!info) {
      this.visible = false;
      Tween.removeTweens(this.cdTarget);
      return;
    }

    const { id, creditsNum, expireTime } = info;

    this.id = id;
    this.text.text = creditsNum;

    this.cdTarget.cd = Math.max((expireTime - Date.now()) / 1000 >> 0, 1);
    this.setTime();
    Tween.removeTweens(this.cdTarget);
    Tween.get(this.cdTarget, { loop: true })
      .wait(1000)
      .call(() => {
        this.cdTarget.cd -= 1;
        if (this.cdTarget.cd <= 0) {
          this.cdTarget.cd = 0;
          store.updateIndexThrottle();
          Tween.removeTweens(this.cdTarget);
        }
        this.setTime();
      });
  }

  setTime() {
    const cd = this.cdTarget.cd;
    const h = Math.floor(cd / 3600);
    const min = Math.floor((cd - h * 3600) / 60);
    const sec = Math.floor(cd - h * 3600 - min * 60);
    this.time.text = `${prefixInteger(h, 2)}:${prefixInteger(min, 2)}:${prefixInteger(sec, 2)}`;
  }

  onUpdate(time: Ticker) {

  }

  onDestroy() {
    Tween.removeTweens(this);
    Tween.removeTweens(this.cdTarget);
  }

  destroy() {
    this.onDestroy();
    super.destroy();
  }

}
