import { LevelBase } from "@/pages/GamePage/Components/LevelBase.ts";
import { Assets, Sprite } from "pixi.js";
import { Ease, Tween } from "@/core/tween";
import { GameEvent, globalEvent } from "@/pages/GamePage/GameEvent.ts";
import { rightWaitTime } from "@/pages/GamePage/Level/LevelConfig.ts";

export class Level22 extends LevelBase {

  level: number = 22;

  A: Sprite;
  B: Sprite;

  right: Sprite;

  onLoad() {
    super.onLoad();

    this.addChild(new Sprite(Assets.get(`level${this.level}/底.png`)))
      .position.set(194, 697);

    this.B = this.addChild(new Sprite(Assets.get(`level${this.level}/裤子.png`)));
    this.B.position.set(267, 1119);

    this.A = this.addChild(new Sprite(Assets.get(`level${this.level}/衣服.png`)));
    this.A.position.set(195, 808);

    const x = this.addChild(new Sprite(Assets.get(`level${this.level}/头.png`)))
    x.position.set(282, 697);
    x.interactive = false;
    x.eventMode = "none";

    this.right = this.addChild(new Sprite(Assets.get(`common/right.png`)));
    this.right.position.set(452, 1242);
    this.right.alpha = 0;
    this.right.interactive = false;
    this.right.eventMode = "none";

    [this.A, this.B].forEach((item) => {
      item.on("pointerdown", this.onAPointerDown, this);
      item.on("pointerup", this.onAPointerUp, this);
      item.on("globalpointermove", this.onAPointerMove, this);
    });

  }

  target = null;
  pos = null;

  onAPointerUp(e) {
    this.pos = null;
  }

  onAPointerDown(e) {
    this.target = e.target;
    const { x, y } = e.data.global;
    this.pos = {
      x: x - e.target.x,
      y: y - e.target.y
    }
  }

  onAPointerMove(e) {
    if (!this.pos) return;
    const { x, y } = e.data.global;
    const nx = x - this.pos.x;
    const ny = y - this.pos.y;
    this.target.position.set(nx, ny);

    this.check();
  }

  check() {

    const { x: ax, y: ay } = this.A;
    const { x: bx, y: by } = this.B;

    if (
      (ax < 0 || ax > 425 || ay < 600 || ay > 970)
      && (bx < 80 || bx > 450 || by < 840 || by > 1200)
    ) {
      this.setPauseCd(true);
      this.setTouchEnable(false);
      Tween.get(this.right)
        .to({ alpha: 1 }, 666, Ease.quadInOut)
        .wait(rightWaitTime)
        .call(() => {
          globalEvent.emit(GameEvent.NextLevel);
        });
    }
  }

  onDestroy() {
    super.onDestroy();
    Tween.removeTweens(this.right);
    [this.A, this.B].forEach((item) => {
      item.off("globalpointermove", this.onAPointerMove, this);
    });
  }

}
