import { _decorator, Component, Node, Vec3, BoxColliderComponent, ICollisionEvent, ColliderComponent, Vec2, SkinningModelComponent, ModelComponent, SkeletalAnimationComponent } from "cc";
import { BulletManagerCtrl } from "../Bullet/BulletManagerCtrl";
import { ProtectvieCtrl } from "./ProtectvieCtrl";
const { ccclass, property } = _decorator;

@ccclass("PlayerCtrl")
export class PlayerCtrl extends Component {

  // @property({ type: EnemyManagerCtrl })
  // public enemyManagerCtrl: EnemyManagerCtrl = null;

  @property({ type: BulletManagerCtrl })
  public bulletManagerCtrl: BulletManagerCtrl = null;

  @property({ type: Node })
  public skeleNode: Node = null;

  @property({ type: Node })
  public protecivieNode: Node = null;

  //敌人目标是谁
  public enemyTraget: Node = null;

  //当前的血量
  public hp: number = 100;

  //小人当前的速度
  private speed: Vec3 = cc.v3();

  //枪支的一些配置信息
  private gunConfig: any = {};

  //是否是暂停状态
  private _isPause: boolean = false;
  public get isPause() {
    return this._isPause;
  }
  public set isPause(val: boolean) {
    this._isPause = val;

    //设置防护罩的暂停状态
    let protectiveNode: Node = this.node.getChildByName('protective') as Node;
    let protectiveCtrl: ProtectvieCtrl = protectiveNode.getComponent(ProtectvieCtrl);
    protectiveCtrl.isPause = val;
  }

  //小人当前的加速度
  private _acceleration: Vec3 = null;
  set acceleration(_a: Vec3) {
    if (_a == null || _a.length() == 0)
      this._acceleration = null;
    else
      this._acceleration = _a;
  }
  get acceleration() {
    return this._acceleration;
  }

  //切换目标需要的最小时间，如果没有这个东西，会出现快速频繁的再几个目标之间切换，会抖动
  public minSwitchTargetInterval: number = 1;
  //当前距离上次切换目标已经累计了多少时间
  private cumulativeSwitchTargetTime: number = 0;

  //发射子弹的间隔
  public minFireInterval: number = 0.1;
  //距离上次发射已经累计到了多少时间
  private cumulativeFireTime: number = 0;


  @property({ type: BoxColliderComponent })
  public boxCollider: BoxColliderComponent = null;

  start() {
    //设置分组掩码
    const group = (1 << 3) + (1 << 1);
    this.boxCollider.setGroup(group);
    const mask = (1 << 3) + (1 << 1);
    this.boxCollider.setMask(mask);

    //监听事件
    this.boxCollider.on("onTriggerEnter", this.onTriggerEnter, this);
    // this.boxCollider.on("onCollisionStay", this.onCollisionStay, this);
    // this.boxCollider.on("onCollisionExit", this.onCollisionExit, this);
  }

  onDestroy() {
    // this.boxCollider.off("onCollisionEnter", this.onCollisionEnter, this);
    // this.boxCollider.off("onCollisionStay", this.onCollisionStay, this);
    // this.boxCollider.off("onCollisionExit", this.onCollisionExit, this);
  }

  initGun(config: any) {
    //todo 初始化自己的gun
    this.minFireInterval = 1.0 / config.firingRate;
  }

  onTriggerEnter(event: ICollisionEvent) {
    if (this.isPause || this.isDead())
      return;

  //   let otherCollider: ColliderComponent = event.otherCollider;
  //   if(otherCollider== null || otherCollider.node == null)
  //     return;

  //   let enemyCtrl = otherCollider.getComponent(EnemyCtrl);
  //   if (enemyCtrl) {
  //     //先判断敌人是否是存活的
  //     if (cc.isValid(enemyCtrl.node, true)) {
  //       enemyCtrl.playAttackAnimation();
  //       this.modifyHp(-enemyCtrl.damage);
  //     }
  //   }
  }

  // onCollisionStay(event: ICollisionEvent) {

  // }

  // onCollisionExit(event: ICollisionEvent) {

  // }

  modifyHp(val: number) {
    this.hp += val;
    cc.log("hero hp is: " + this.hp);
  }

  isDead(): boolean {
    return this.hp <= 0;
  }

  update(dt: number) {
    if (this.isPause)
      return;
    
    this.updateForSpeedAndPos(dt);
    this.updateForEnemyTarget(dt);
    this.updateForDirectionAndFire(dt);
    this.updateForProteciviePos(dt);
  }

  //先更新速度，再根据速度更新自己的位置
  updateForSpeedAndPos(dt: number) {
    if (this.acceleration == null) {
      if (this.speed.length() != 0) {
        //没有加速度的说，那么这个时候手指就从屏幕上下来了
        let acceleration = cc.v3(this.speed);
        acceleration.normalize();
        Vec3.multiplyScalar(acceleration, acceleration, 2 * dt);
        if (this.speed.length() < acceleration.length()) {
          this.speed = cc.v3(Vec3.ZERO);
        }
        else {
          Vec3.subtract(this.speed, this.speed, acceleration);
        }
      }
    }
    else {
      //有加速度说明手指还在屏幕上呢
      this.speed.x += (dt * this.acceleration.x);
      this.speed.y += (dt * this.acceleration.y);
      this.speed.z += (dt * this.acceleration.z);
    }

    //如果速度超过了10, 那么就需要限制
    let maxSpeed = 3;
    if (this.speed.length() > maxSpeed) {
      this.speed.normalize();
      let newSpeed = cc.v3();
      Vec3.multiplyScalar(newSpeed, this.speed, maxSpeed);
      this.speed = newSpeed;
    }
    let oldPos = this.node.getPosition();
    let newPos = cc.v3();
    Vec3.scaleAndAdd(newPos, oldPos, this.speed, dt);
    this.node.setPosition(newPos);
  }

  //更新自己的目标敌人是谁
  updateForEnemyTarget(dt: number) {
    // this.cumulativeSwitchTargetTime += dt;
    // if (this.enemyTraget == null || !cc.isValid(this.enemyTraget, true) || this.cumulativeSwitchTargetTime >= this.minSwitchTargetInterval) {
    //   this.enemyTraget = this.enemyManagerCtrl.getClosestEnemy();
    //   this.cumulativeSwitchTargetTime = 0.0;
    // }
  }

  private bulletNum:number = 0;
  //更新自己的旋转角度和开火
  updateForDirectionAndFire(dt: number) {

 
        this.bulletManagerCtrl.createBullet(0, cc.v3(0,1,0), cc.v3(0,0,-1));
        this.cumulativeFireTime = 0;
        this.bulletNum ++;
        cc.log("创建了：" + this.bulletNum + "：子弹");

    // if (this.enemyTraget) {
    //   let enemyPos = this.enemyTraget.getPosition();
    //   let selfPos = this.node.getPosition();
    //   let localPos = cc.v2(enemyPos.x - selfPos.x, -(enemyPos.z - selfPos.z));
    //   let angle: number = Vec2.angle(cc.v2(1, 0), localPos);
    //   if (localPos.y <= 0)
    //     angle = -angle;

    //   let rotation = angle * 180 / Math.PI;
    //   this.skeleNode.setRotationFromEuler(0, rotation + 90, 0);

    //   this.cumulativeFireTime += dt;
    //   if (this.cumulativeFireTime > this.minFireInterval) {
    //     let bulletPos = this.node.getPosition();
    //     let offsetPos: Vec3 = cc.v3();
    //     Vec3.subtract(offsetPos, enemyPos, selfPos);
    //     offsetPos.normalize();
    //     offsetPos.y = 0;
    //     Vec3.scaleAndAdd(bulletPos, bulletPos, offsetPos, 0.6);
    //     bulletPos.y = 0.8;
    //     this.bulletManagerCtrl.createBullet(0, bulletPos, offsetPos);
    //     this.cumulativeFireTime = 0;
    //   }
    // }
  }

  updateForProteciviePos(dt: number) {
    // this.protecivieNode.setPosition(cc.v3(0,0.331,0));
  }


  // update (deltaTime: number) {
  //     // Your update function goes here.
  // }
}
