import { Assets, Container, Point, PointData, Sprite } from "pixi.js";
import { mapSize } from "@/pages/GamePage/config/Config.ts";

import { Circle } from "detect-collisions";
import { collisionSys } from "@/pages/GamePage/GamePage.tsx";

export class Snake extends Container {
  head: Sprite = null;
  bodyArr: Sprite[] = [];

  bodyScale: number = 1;
  energy: number = 0;

  private _length: number = 0;
  get length() {
    return this._length;
  }

  set length(value: number) {
    this._length = value;
    this.emit("updateLength", value);
  }

  get radius() {
    return this.bodyScale * 46 / 2;
  }

  // 位置相关
  private ready: boolean = false;
  isLife: boolean = true;

  speed: number = 166;

  dir: Point = new Point(1, 0);

  collider: Circle = null;

  init(){
    this.initUI();
    this.initPhy();
  }

  initUI() {
    this.ready = false;

    this.bodyArr.forEach((body) => {
      body.removeFromParent();
    });

    this.energy = 0;
    this.scale = 1;
    this.bodyArr.length = 0;

    // 设置头部
    this.head = this.addChild(new Sprite(Assets.get("蛇/初级/head.png")));
    this.head.angle = 0;
    this.head.position.set(375, 375);
    this.head.anchor.set(0.5, 0.5);

    this.length = 1;

    // 创建身体节点
    this.addEnergy(50);

    this.isLife = true;
    this.ready = true;
  }

  initPhy() {
    const p = this.head.getGlobalPosition();
    this.collider = collisionSys.createCircle(p, this.radius);
    this.collider.setScale(this.bodyScale, this.bodyScale);
  }

  updatePhy() {
    const p = this.head.getGlobalPosition();
    this.collider.setPosition(p.x, p.y);
    this.collider.setScale(this.bodyScale, this.bodyScale);
  }

  onEnable() {
  }

  onDisable() {
  }

  // 上次生长富余的能量
  private lastRemaining = 0;

  /**
   * 加能量
   * 暂定加长/双倍道具卡效果不叠加
   */
  addEnergy(value: number) {
    this.energy += value
    const growthThreshold = Math.floor(12 * this.bodyScale);

    value += this.lastRemaining;

    while (value >= growthThreshold) {
      value -= growthThreshold;
      if (this.bodyScale < 3) {
        this.bodyScale += 0.01;
      }
      this.grow();
    }

    this.lastRemaining = value;
    // this.speed = 600 * this.scale;
  }

  /**
   * 快速生长
   */
  fastGrow(energy: number) {
    this.addEnergy(energy)
    // for (let i = 0; i < time; i++) {
    //     this.grow();
    // }
  }

  /**
   * 生长
   */
  private grow() {

    if (this.length > 180) {
      return;
    }

    if (!this.isLife) return;

    this.length += 1;

    let len = this.bodyArr.length;

    const newBody = new Sprite(Assets.get("蛇/初级/body0.png"));

    const pre = this.bodyArr[len - 1] || this.head;

    newBody.angle = pre.angle;
    newBody.position.set(999999, 999999);
    newBody.scale.set(this.bodyScale, this.bodyScale);
    this.addChildAt(newBody, 0);
    newBody.anchor.set(0.5, 0.5);

    // newBody.active = isIntersect(
    //     newBody.getPosition(),
    //     this.head.getPosition(),
    //     this.vw,
    //     this.vh
    // );

    this.bodyArr.splice(len, 0, newBody);
  }

  positions: PointData[] = []; // 存储历史位置点
  private readonly HISTORY_LENGTH = 10; // 增加历史点数量
  private readonly SEGMENT_SPACING = 6.3; // 增加节点间距

  moveTime = 1 / 60;
  totalTime = 0;

  onUpdate(dt: number) {
    this.totalTime += dt;
    while (this.totalTime >= this.moveTime) {
      this.totalTime -= this.moveTime;
      this.move(this.moveTime);
    }

    this.updatePhy();
  }

  protected move(dt: number) {
    if (!this.ready || !this.isLife) {
      return;
    }

    const bodyLen = this.bodyArr.length;

    const headAngle = this.head.angle = Math.atan2(this.dir.y, this.dir.x) * 180 / Math.PI;

    // 更新头部位置
    const newHeadPos = this.dir
      .multiplyScalar(dt * this.speed)
      .add(this.head.position);

    if (newHeadPos.x < -10) newHeadPos.x = 750 + 10;
    if (newHeadPos.x > 750 + 10) newHeadPos.x = -10;

    if (newHeadPos.y < -10) newHeadPos.y = mapSize.height + 10;
    if (newHeadPos.y > mapSize.height + 10) newHeadPos.y = -10;

    this.head.position.set(newHeadPos.x, newHeadPos.y);
    const flipY = headAngle > 90 && headAngle < 270;
    this.head.scale.set(this.bodyScale, flipY ? -this.bodyScale : this.bodyScale);

    const space = this.SEGMENT_SPACING * this.bodyScale;

    // 存储历史位置
    this.positions.unshift(newHeadPos);
    // 确保历史位置点足够多，以容纳所有身体节点
    const requiredLength = this.bodyArr.length * space + 1;
    if (this.positions.length > requiredLength) {
      this.positions.pop();
    }

    // 更新身体节点位置
    for (let i = 0; i < bodyLen; i++) {
      const body = this.bodyArr[i];

      // 为每个节点计算一个固定的偏移量
      const offset = (i + 1) * (~~space);

      // 确保不会超出历史位置数组范围
      if (offset < this.positions.length) {
        const targetPos = this.positions[offset];

        // 计算角度
        if (offset > 0) {
          const prevPos = this.positions[offset - 1];
          body.angle = Math.atan2(
            targetPos.y - prevPos.y,
            targetPos.x - prevPos.x
          ) * 180 / Math.PI;
        }

        body.position.set(targetPos.x, targetPos.y);
        body.scale.set(this.bodyScale, this.bodyScale);
      }
    }

    // // 边界检查
    // const mapHalfWidth = Global.HALF_MAP_WIDTH;
    // const mapHalfHeight = Global.HALF_MAP_HEIGHT;
    // if (
    //   newHeadPos.x < -mapHalfWidth
    //   || newHeadPos.x > mapHalfWidth
    //   || newHeadPos.y < -mapHalfHeight
    //   || newHeadPos.y > mapHalfHeight
    // ) {
    //   this.death();
    // }

  }

  /****************************** 磁铁 ******************************/
  useMagnet() {
    this.clearMagnet();
    // this.magnetEffectNode.active = true;
    // this.magnetEffectNode.getComponent(Animation).play();
    // this.eatCollider.radius = Global.PROP_MAGNET_RADIUS;
    // this.scheduleOnce(this.clearMagnet, Global.PROP_MAGNET_DUR_TIME)

  }

  clearMagnet() {
    // this.unschedule(this.clearMagnet)
    // this.magnetEffectNode.active = false;
    // this.magnetEffectNode.getComponent(Animation).stop();
    // this.eatCollider.radius = 65;
  }

}
