import { _decorator, director, find, Label, PhysicsGroup } from 'cc';
import { LifeBar } from './LifeBar';
import { Role } from '../Role';
import { Enemy } from './Enemy';
import { GameOverData } from './Data/GameOverData';
import { UIMgr } from '../../../Frames/UIManager';
import { messageMgr } from '../../../Frames/MessageMgr';
import { MyTower } from './MyTower';
const { ccclass, property } = _decorator;

@ccclass('EnemyTower')
export class EnemyTower extends Role {
    private _lifeBar: LifeBar = null;
    private _strMyHp: Label = null;
    //敌人防御塔总血量通过数据表获取
    enemyTotalHp: number = null;
    protected onLoad(): void {
        this._lifeBar = this.node.getComponent(LifeBar);
        this._strMyHp = this.node.getChildByPath("ProgressBar/Label").getComponent(Label);
    }
    start() {
        this.hp = this.enemyTotalHp;
        this._initLifeBar();
        //super._setupPhysics();
    }

    //初始化血条
    private _initLifeBar() {
        this._lifeBar._curHp = this.hp;
        this._lifeBar._totalHp = this.hp;
    }
    update(deltaTime: number) {
        if (this._lifeBar._curHp <= 0) {
            this._gameOverDtSettlement();
        }
        this._strMyHp.string = `${this._lifeBar._curHp}/${this.hp}`;
    }

    //游戏结束数据结算
    private _gameOverDtSettlement(){
        const myTower = find("Canvas/GameRoot/MyTower").getComponent(MyTower);
        this._lifePercent(myTower.getCurHp(), myTower.getTotalHp())
        GameOverData.Instance.Win = true;
        UIMgr.openUI("GameOver");
        director.pause();
    }

    private _lifePercent(curHp: number, totalHp: number){
        if(totalHp <= 0){
            GameOverData.Instance.LifePercent = 0;
            return;
        }
        let lifePercent = Math.floor((curHp / totalHp) * 100);
        lifePercent = Math.max(0, Math.min(lifePercent,100));
        GameOverData.Instance.LifePercent = lifePercent;
    }

    //必须实现抽象方法
    protected _getCollisionGroup(): number {
        return PhysicsGroup.Enemy; //实际分组值根据项目设置
    }

    protected _isValidTarget(target: Role): boolean {
        //通过组件类型判断是否为敌人
        return target instanceof Enemy;
    }
}




