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

export class Level12 extends LevelBase {

  level: number = 12;

  A: Sprite; // 头
  B: Sprite; // 尾

  right: Sprite;

  // 滑动轨迹相关
  private trailGraphics: Graphics;
  private isDrawing: boolean = false;
  private startPoint: { x: number, y: number } | null = null;
  private currentPoint: { x: number, y: number } | null = null;

  // 香烟分离状态
  private isSeparated: boolean = false;

  onLoad() {
    super.onLoad();

    this.A = this.addChild(new Sprite(Assets.get(`level${this.level}/头.png`)));
    this.A.position.set(67, 923);

    this.B = this.addChild(new Sprite(Assets.get(`level${this.level}/尾.png`)));
    this.B.position.set(265, 923);

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

    // 创建绘制轨迹的Graphics对象
    this.trailGraphics = this.addChild(new Graphics());
    this.trailGraphics.zIndex = 1000; // 确保轨迹在最上层

    // 启用stage交互
    const app = getApp();
    app.stage.interactive = true;
    app.stage.eventMode = "static";

    // 在stage上监听全局事件
    app.stage.on("pointerdown", this.onPointerDown, this);
    app.stage.on("globalpointermove", this.onPointerMove, this);
    app.stage.on("pointerup", this.onPointerUp, this);
    app.stage.on("pointerupoutside", this.onPointerUp, this);
  }

  onPointerDown(e) {
    if (this.isSeparated) return;

    console.log("开始滑动", e.data.global);
    this.isDrawing = true;
    this.startPoint = { x: e.data.global.x, y: e.data.global.y };
    this.currentPoint = { x: e.data.global.x, y: e.data.global.y };

    // 清除之前的轨迹
    this.trailGraphics.clear();
    console.log("清除轨迹，开始新的绘制");
  }

  onPointerMove(e) {
    if (!this.isDrawing || this.isSeparated) return;

    this.currentPoint = { x: e.data.global.x, y: e.data.global.y };

    console.log("更新轨迹点", this.currentPoint);

    // 绘制轨迹线条
    this.drawTrail();
  }

  onPointerUp(e) {
    if (!this.isDrawing || this.isSeparated) return;

    console.log("结束滑动", "起点:", this.startPoint, "终点:", this.currentPoint);
    this.isDrawing = false;

    // 检查滑动轨迹是否经过香烟
    if (this.checkTrailCrossedCigarette()) {
      this.separateCigarette();
    } else {
      // 如果没有成功分离，清除轨迹
      console.log("没有经过香烟，清除轨迹");
      setTimeout(() => {
        this.clearTrail();
      }, 1000);
    }
  }

  drawTrail() {
    if (!this.startPoint || !this.currentPoint) return;

    console.log("绘制轨迹，起点:", this.startPoint, "终点:", this.currentPoint);

    this.trailGraphics.clear();

    // 绘制从起点到终点的直线
    this.trailGraphics.moveTo(this.startPoint.x, this.startPoint.y);
    this.trailGraphics.lineTo(this.currentPoint.x, this.currentPoint.y);
    this.trailGraphics.stroke({ width: 6, color: 0xffffff });

    console.log("轨迹绘制完成，起点:", this.startPoint, "终点:", this.currentPoint);
  }

  checkTrailCrossedCigarette(): boolean {
    if (!this.startPoint || !this.currentPoint) return false;

    // 香烟的水平线段：从A的x到B的x+width
    const cigaretteStartX = this.A.x;
    const cigaretteEndX = this.B.x + this.B.width;
    const cigaretteY = this.A.y + (this.A.height / 2); // 使用香烟中间的y坐标

    console.log("香烟线段:", cigaretteStartX, "到", cigaretteEndX, "y坐标:", cigaretteY);

    // 检查轨迹线段是否与香烟水平线段相交
    const startY = this.startPoint.y;
    const endY = this.currentPoint.y;

    // 检查轨迹线段是否在y方向上跨越了香烟线段
    if ((startY <= cigaretteY && endY >= cigaretteY) || (startY >= cigaretteY && endY <= cigaretteY)) {
      // 计算轨迹线段在cigaretteY处的x坐标
      const startX = this.startPoint.x;
      const endX = this.currentPoint.x;

      let intersectionX;
      if (startY === endY) {
        // 水平线段，取任意一个x坐标
        intersectionX = startX;
      } else {
        // 计算交点的x坐标
        const t = (cigaretteY - startY) / (endY - startY);
        intersectionX = startX + t * (endX - startX);
      }

      console.log("交点x坐标:", intersectionX);

      // 检查交点是否在香烟线段的x范围内
      if (intersectionX >= cigaretteStartX && intersectionX <= cigaretteEndX) {
        console.log("轨迹与香烟线段相交!");
        return true;
      }
    }

    console.log("轨迹未与香烟线段相交");
    return false;
  }

  separateCigarette() {
    console.log("开始分离香烟");
    this.isSeparated = true;
    this.setTouchEnable(false);

    // 设置A的旋转锚点为尾巴连接处（B的左边缘）
    const pivotX = this.B.x - this.A.x; // 相对于A的x偏移
    const pivotY = this.A.height / 2; // A的中心高度
    this.A.pivot.set(pivotX, pivotY);

    // 调整A的位置以补偿pivot的变化
    this.A.x += pivotX;
    this.A.y += pivotY;

    // A向下旋转90度并向下移动
    Tween.get(this.A)
      .to({
        angle: -45, // 顺时针旋转90度
        y: this.A.y + 60 // 向下移动60像素
      }, 666, Ease.quadInOut)
      .call(() => {
        // 分离完成后，清除轨迹并显示通关
        this.clearTrail();
        setTimeout(() => {
          this.triggerSuccess();
        }, 500);
      });

    // B保持不动，不需要动画
  }

  clearTrail() {
    console.log("清除轨迹动画");
    Tween.get(this.trailGraphics)
      .to({ alpha: 0 }, 222, Ease.quadInOut)
      .call(() => {
        this.trailGraphics.clear();
        this.trailGraphics.alpha = 1;
        console.log("轨迹已清除");
      });
  }

  triggerSuccess() {
    console.log("开始通关动画");

    const rightX = this.B.x + this.B.width - this.right.width + 20;
    const rightY = this.B.y + this.B.height - this.right.height + 20;

    // 设置right的位置
    this.right.position.set(rightX, rightY);

    this.setPauseCd(true);
    // 显示right图标并完成通关
    Tween.get(this.right)
      .to({ alpha: 1 }, 444, Ease.quadInOut)
      .wait(rightWaitTime)
      .call(() => {
        globalEvent.emit(GameEvent.NextLevel);
      });
  }

  onDestroy() {
    super.onDestroy();

    // 移除动画
    Tween.removeTweens(this.A);
    Tween.removeTweens(this.B);
    Tween.removeTweens(this.right);
    Tween.removeTweens(this.trailGraphics);

    // 移除事件监听
    const app = getApp();
    app.stage.off("pointerdown", this.onPointerDown, this);
    app.stage.off("globalpointermove", this.onPointerMove, this);
    app.stage.off("pointerup", this.onPointerUp, this);
    app.stage.off("pointerupoutside", this.onPointerUp, this);
  }
}
