import { Collider2D, Component, Contact2DType, IPhysics2DContact, Vec2, Vec3, _decorator } from 'cc'

import BulletManager from '../../script/game/manager/BulletManager'
import FishNetManager from '../../script/game/manager/FishNetManager'

import FishBase from './FishBase'
import WsManager from '../../script/game/manager/WsManager'
import CannonManager from '../../script/game/manager/CannonManager'
import FishUI from './FishUI'
import FishManager from '../../script/game/manager/FishManager'

const { ccclass, property } = _decorator

@ccclass('FishBulletBase')
export default class FishBulletBase extends Component {
  public bulletType: number = 0

  public targetP: Vec2

  public _cacheVec2: Vec2 = new Vec2()

  public _cacheVec3: Vec3 = new Vec3()

  private _collider: Collider2D | null = null

  private currFish: FishBase | null = null

  onLoad() {
    WsManager.instance.on(5, this.handelMsg, this)
    this._collider = this.getComponent(Collider2D)
    if (this._collider) {
      this._collider.sensor = true
      this._collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this)
    }
  }

  start() {}

  onEnable() {
    if (this._collider) this._collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this)
  }

  onDisable() {
    if (this._collider) this._collider.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this)
  }

  // 处理碰撞
  private handleFishCollision(fish: FishBase | null, contact: IPhysics2DContact | null) {
    if (fish && fish.isDead === 2) {
      this.node.getPosition(this._cacheVec3)
      this._cacheVec2.x = this._cacheVec3.x
      this._cacheVec2.y = this._cacheVec3.y
      FishNetManager.instance.addFishNet(this.bulletType, this._cacheVec2)
      BulletManager.instance.killBullet(this)
    }
  }

  // 碰撞检测
  onBeginContact(selfCollider: Collider2D, other: Collider2D, contact: IPhysics2DContact | null) {
    const fish: FishBase | null = other.getComponent(FishBase)
    WsManager.instance.onSend({
      fish_id: fish.fishId,
      cannon_id: CannonManager.instance.cannonType,
    })
    this.handleFishCollision(fish, contact)
  }

  handelMsg(res: any) {
    FishUI.instance.refreshScore(res)
    if (res.fish_status === 1) {
      FishManager.instance.killFish(res)
    }
  }

  protected onDestroy(): void {}
}
