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

export class Level24 extends LevelBase {

  level: number = 24;

  balls: Sprite[] = [];
  right: Sprite;
  error: Sprite;

  // 拖拽相关属性
  private dragData: { ball: Sprite, offset: { x: number, y: number } } | null = null;

  onLoad() {
    super.onLoad();

    // 创建四个球，并添加到balls数组中
    const ballA = this.addChild(new Sprite(Assets.get(`level${this.level}/球.png`)));
    ballA.position.set(125, 710);
    ballA.scale.set(134 / 378);
    this.balls.push(ballA);

    const ballB = this.addChild(new Sprite(Assets.get(`level${this.level}/球.png`)));
    ballB.position.set(434, 685);
    ballB.scale.set(182 / 378);
    this.balls.push(ballB);

    const ballC = this.addChild(new Sprite(Assets.get(`level${this.level}/球.png`)));
    ballC.position.set(205, 982);
    ballC.scale.set(90 / 378);
    this.balls.push(ballC);

    const ballD = this.addChild(new Sprite(Assets.get(`level${this.level}/球.png`)));
    ballD.position.set(410, 926);
    ballD.scale.set(156 / 378);
    this.balls.push(ballD);

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

    // 为每个球添加拖拽事件
    this.balls.forEach((ball) => {
      ball.on("pointerdown", this.onBallPointerDown, this);
      ball.on("globalpointermove", this.onBallPointerMove, this);
      ball.on("pointerup", this.onBallPointerUp, this);
      ball.on("pointerupoutside", this.onBallPointerUp, this);
    });
  }

  onBallPointerDown(e) {
    const ball = e.currentTarget as Sprite;
    console.log("开始拖拽球", ball);
    
    this.dragData = {
      ball: ball,
      offset: {
        x: e.data.global.x - ball.x,
        y: e.data.global.y - ball.y
      }
    };
    
    // 将当前球置于最上层
    this.setChildIndex(ball, this.children.length - 1);
  }

  onBallPointerMove(e) {
    if (!this.dragData) return;

    // 更新球的位置
    this.dragData.ball.x = e.data.global.x - this.dragData.offset.x;
    this.dragData.ball.y = e.data.global.y - this.dragData.offset.y;
  }

  onBallPointerUp(e) {
    if (!this.dragData) return;

    const draggedBall = this.dragData.ball;
    this.dragData = null;

    // 检查是否与其他球发生碰撞并合成
    this.checkMerge(draggedBall);
  }

  checkMerge(draggedBall: Sprite) {
    for (const ball of this.balls) {
      if (ball === draggedBall) continue;
      
      // 计算两球中心点的距离（由于锚点为默认值，需要加上半径偏移）
      const draggedCenterX = draggedBall.x + (draggedBall.width / 2);
      const draggedCenterY = draggedBall.y + (draggedBall.height / 2);
      const ballCenterX = ball.x + (ball.width / 2);
      const ballCenterY = ball.y + (ball.height / 2);
      
      const distance = this.getDistance(
        { x: draggedCenterX, y: draggedCenterY },
        { x: ballCenterX, y: ballCenterY }
      );
      
      // 计算两球的半径
      const draggedRadius = draggedBall.width / 2;
      const ballRadius = ball.width / 2;
      
      // 如果两球接触（距离小于两球半径之和）
      if (distance < draggedRadius + ballRadius) {
        console.log("球碰撞，开始合成");
        this.mergeBalls(draggedBall, ball);
        return;
      }
    }
  }

  mergeBalls(ball1: Sprite, ball2: Sprite) {
    // 计算新球的位置（两球中心点的中点，然后转换回左上角坐标）
    const ball1CenterX = ball1.x + (ball1.width / 2);
    const ball1CenterY = ball1.y + (ball1.height / 2);
    const ball2CenterX = ball2.x + (ball2.width / 2);
    const ball2CenterY = ball2.y + (ball2.height / 2);
    
    const newCenterX = (ball1CenterX + ball2CenterX) / 2;
    const newCenterY = (ball1CenterY + ball2CenterY) / 2;
    
    // 计算新球的大小（使用更小的增长幅度）
    const scaleIncrease = Math.min(ball1.scale.x, ball2.scale.x) * 0.4; // 增长幅度减小为较小球的30%
    const newScale = Math.min(Math.max(ball1.scale.x, ball2.scale.x) + scaleIncrease, 1.2); // 最大限制调整为1.2
    
    // 移除较小的球，保留较大的球作为合成结果
    const keepBall = ball1.scale.x >= ball2.scale.x ? ball1 : ball2;
    const removeBall = ball1.scale.x >= ball2.scale.x ? ball2 : ball1;
    
    // 从balls数组中移除被合成的球
    const removeIndex = this.balls.indexOf(removeBall);
    if (removeIndex > -1) {
      this.balls.splice(removeIndex, 1);
    }
    
    // 移除被合成的球的事件监听
    removeBall.off("pointerdown", this.onBallPointerDown, this);
    removeBall.off("globalpointermove", this.onBallPointerMove, this);
    removeBall.off("pointerup", this.onBallPointerUp, this);
    removeBall.off("pointerupoutside", this.onBallPointerUp, this);
    
    // 计算新位置（左上角坐标）
    const newSize = 378 * newScale;
    const newX = newCenterX - (newSize / 2);
    const newY = newCenterY - (newSize / 2);
    
    // 播放合成动画
    Tween.get(keepBall)
      .to({ x: newX, y: newY, scaleX: newScale, scaleY: newScale }, 300, Ease.quadOut)
      .call(() => {
        // 移除被合成的球
        this.removeChild(removeBall);
        
        // 检查是否通关
        this.checkWinCondition();
      });
      
    Tween.get(removeBall)
      .to({ alpha: 0, scaleX: 0, scaleY: 0 }, 300, Ease.quadOut);
  }

  checkWinCondition() {
    console.log("检查通关条件，剩余球数:", this.balls.length);
    
    // 如果只剩一个球
    if (this.balls.length === 1) {
      console.log("达到通关条件");
      this.triggerSuccess();
    }
  }

  getDistance(point1: { x: number, y: number }, point2: { x: number, y: number }): number {
    const dx = point1.x - point2.x;
    const dy = point1.y - point2.y;
    return Math.sqrt(dx * dx + dy * dy);
  }

  triggerSuccess() {
    // 防止重复触发
    if (this.right.alpha > 0) return;

    console.log("开始通关动画");
    this.setTouchEnable(false);
    
    // 获取最后一个球
    const lastBall = this.balls[0];
    
    // 计算屏幕中间位置（假设屏幕尺寸为720x1280）
    const screenCenterX = 360;
    const screenCenterY = 940;
    
    // 计算球移动到屏幕中间时的位置（左上角坐标）
    const ballTargetX = screenCenterX - (lastBall.width / 2);
    const ballTargetY = screenCenterY - (lastBall.height / 2);
    
    // 球移动到屏幕中间的动画
    Tween.get(lastBall)
      .to({ x: ballTargetX, y: ballTargetY }, 600, Ease.quadInOut)
      .call(() => {
        // 球到达中间后，计算right的位置（球的右下角）
        const rightX = lastBall.x + lastBall.width - this.right.width + 20; // 稍微偏移一点
        const rightY = lastBall.y + lastBall.height - this.right.height + 20;
        
        // 设置right的位置
        this.right.position.set(rightX, rightY);
        
        // 显示right图标并完成通关
        Tween.get(this.right)
          .to({ alpha: 1 }, 444, Ease.quadInOut)
          .wait(2000)
          .call(() => {
            globalEvent.emit(GameEvent.NextLevel);
          });
      });
  }

  onDestroy() {
    super.onDestroy();
    
    // 移除所有球的tween动画
    this.balls.forEach(ball => {
      Tween.removeTweens(ball);
      ball.off("pointerdown", this.onBallPointerDown, this);
      ball.off("globalpointermove", this.onBallPointerMove, this);
      ball.off("pointerup", this.onBallPointerUp, this);
      ball.off("pointerupoutside", this.onBallPointerUp, this);
    });
    
    Tween.removeTweens(this.right);
  }
}
