import { _decorator, instantiate, Node, PhysicsGroup, tween, Vec3 } from 'cc';
import { Role, RoleState } from '../Role';
import { RoleData } from '../../../DataItem/ItemData';
import { LifeBar } from './LifeBar';
import { MyRole } from './MyRole';
import { MyTower } from './MyTower';
import { resMgr } from '../../../Frames/ResourcesMgr';
import { messageMgr } from '../../../Frames/MessageMgr';
import { GameOverData } from './Data/GameOverData';
const { ccclass, property } = _decorator;

@ccclass('Enemy')
export class Enemy extends Role {
    private _lifeBar: LifeBar = null;
    private _isDie: boolean = false;
    private _orePos: Vec3 = new Vec3(200, 100, 0);
    protected onLoad(): void {
        this._lifeBar = this.node.getComponent(LifeBar);
        this._isDie = false;
    }
    init(name: string, pos: Vec3, data: RoleData[], dir?: number) {
        super.init(name, pos, data, dir);
        this._initLifeBar();
    }

    //初始化血条
    private _initLifeBar() {
        this._lifeBar._curHp = this.hp;
        this._lifeBar._totalHp = this.hp;
    }
    update(deltaTime: number) {
        super.update(deltaTime);
        //this.stop();
        if (this._lifeBar._curHp <= 0) {
            super.playAnimation(RoleState.Die);
            if (this._isDie) return;
            this.createOre();
            this._isDie = true;
        }
    }

    createOre() {
        GameOverData.Instance.KillCount =  GameOverData.Instance.KillCount + 1;
        //触发消息
        messageMgr.dispatch("addOreCount");
        const ore: Node = instantiate(resMgr.getPrefab("Ore"));
        ore.parent = this.bulletLayer;
        ore.position = this.node.position;
        tween(ore)
            .delay(0.3)
            .to(2, { position: this._orePos })
            .delay(0.3)
            .call(() => { ore.destroy() })
            .start();
    }

    stop(): void {
        if (this.node.getWorldPosition().x <= 200) {
            this.isStop = true;
            super.playAnimation(RoleState.Idle);
            //this.playAnimation(RoleState.Attack);
            this.moveSpeed = 0;
        }
    }

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

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


