
import { _decorator, Component, Node, Vec3, Animation } from 'cc';
import { ResUtil } from '../utils/ResUtil';
import { Game } from './Game';
import { Utils } from '../utils/Utils';
import { userIns } from '../data/UserData';
import { Enemy } from './Enemy';
import { GMap } from './GMap';
import { uiMgr } from '../core/manager/UIManager';
import { Constants } from '../data/Constants';
import { audioMgr } from '../core/manager/AudioManager';
import { eventEmitter } from '../core/event/EventEmitter';
const { ccclass, property } = _decorator;

@ccclass('BuildEnemys')
export class BuildEnemys extends Component {
    @property({type: Animation,tooltip:"开门动画"})
    public openDoor: Animation = null;

    //敌人类型统计数组（保存每类敌人的总数量、剩余数量和配置数据）
    public enemyTypeRecords: Array<{
        enemyId: number, 
        total: number, 
        count: number, 
        enemyData: any}> = [];
    //所有敌人数据
    public queueEnemys: Array<any> = [];
    //保存每一波临时数据定时器记录
    public eTimeMaps = new Map <any,any>();
    //当前生成的敌人
    public allEnemys: Array<Enemy> = [];
    //每连杀3个敌人的次数
    public continuekillCount: number = 0;
    //map路径控制类
    public map: GMap = null;
     //敌人排序定时器
    private intervalId: number = 0;

    start(): void {
        this.map = this.node.getComponent(GMap);
        //加载敌人数据
        this.allEnemys = [];
        //敌人排序
        /*if(this.intervalId!= null){clearInterval(this.intervalId);}
        this.intervalId = setInterval((dt: number)=>{
            if(Game.I.isGameOver || Game.I.isPause) return;
            this.sortEnemyList();
        },0.25 * 1000);*/
    }

    /**
     * 开始游戏创建敌人
     */
    public async loadLevelEnemys(){
        if(Game.I.isGameOver 
            || Game.I.isPause)return;
        this.recycle();
        this.queueEnemys = this.readLevelEnemys();
        //总共每一个敌人延迟时间统计 0.1s检测一次
        let delay: number = 0;
        let interval: number = 0.0175;
        //敌人数据
        for(let idx = 0; idx < this.queueEnemys.length; idx++) {
            const eData:any = this.queueEnemys[idx];
            //每一种之间兵种间隔随机
            let t: number = Utils.getRandomFloat(eData.min_interval,eData.max_interval);
            //延迟时间
            delay += t;
            let tData: any = {
                data: eData,
                delay: delay, 
                curTime: 0,
                createComplete: false,
            }
            let time_id: number = setInterval(()=>{
                if(Game.I.isGameOver || Game.I.isPause) return;
                tData.curTime += interval;
                //延迟时间到了然后开始创建敌人
                if(tData.curTime >= tData.delay 
                    && !tData.createComplete){
                    tData.createComplete = true;
                    this.createEnemy(tData.data).then(()=>{
                        const timeFun = this.eTimeMaps?.get(tData);
                        if(timeFun){
                            clearInterval(timeFun);
                            this.eTimeMaps.delete(tData);
                        }
                    });
                }
            },interval * 1000);
            this.eTimeMaps.set(tData,time_id);
        }
        //敌人创建完成后 播放开门动画
        this.scheduleOnce(()=>{
            this.openDoor.play();
        },delay);
    }


    /**
     * 读取敌人关卡数据
     */
    public readLevelEnemys(){
        const data: any = userIns.getCurLevelData();
        if(!data)return;
        Game.I.player.setPlayerPos();
        //最终生成的敌人队列 普通敌人临时存储 BOSS敌人临时存储
        let enemyQueue = [],normalEnemies = [],bossEnemies = [];
        //拆分并处理每个敌人配置
        data.dispose.split('|').forEach((item: string) => {
            const [enemyId, count] = item.split('_').map(Number);
            const enemyData = Utils.clone(userIns.enemyTable).find((e: any) => e.id == enemyId);
            //记录敌人类型统计
            if (enemyData) {
                this.enemyTypeRecords.push({
                    enemyId,
                    total: count,
                    count: count,
                    enemyData: Utils.clone(enemyData)
                });
                //敌人生命成长系数{生命值*（1+系数）}
                enemyData.hp = Math.floor((1 + data.coefficient) * enemyData.hp);
                if(enemyData.type === 2) { // BOSS类型
                    for(let i = 0; i < count; i++) {
                        bossEnemies.push({ ...enemyData });
                    }
                }else{//小兵类型
                    for(let i = 0; i < count; i++) {
                        normalEnemies.push({ ...enemyData });
                    }
                }
            }
        });
        //普通敌人乱序处理
        normalEnemies.sort(() => Math.random() - 0.5);
        //合并队列：普通敌人在前，BOSS在后
        enemyQueue.push(...normalEnemies, ...bossEnemies);
        return enemyQueue;
    }


    /**
     * 创建敌人
     * @param data 敌人数据
     * @returns 返回敌人
     */
    public async createEnemy(data:any): Promise<Enemy>{
        if(!Game.I.map 
            ||!Game.I.map
            ||!this.allEnemys
            ||!data)return;
        let item:Node = await ResUtil.loadRes(`enemy/enemy/${data.prb_name}`);
        item.active = true;
        item.parent = Game.I.map.node;
        const posArr:Vec3[] = this.map.getPaths(data);
        item.worldPosition = posArr[0];
        let e:Enemy = item.getComponent(Enemy);
        await e.init(data);
        e.walk(posArr);
        this.allEnemys.push(e);
        return e;
    }


    /**
     * 敌人被打死统计
     * @param enemy 敌人
     */
    public subtractEnemy(enemy: Enemy){
        if(!enemy 
            || !enemy.node 
            || Game.I.isGameOver)return;
        //删除一个敌人
        Utils.remove(this.allEnemys,enemy);
        this.allEnemys.forEach(e => e.addDiffHP());
        //从敌人实例获取id
        let record = this.enemyTypeRecords.find(record => record.enemyId == enemy.data?.id);
        if(record) {
           record.count = Math.max(record.count - 1, 0); 
        }
        //敌人数量改变
        eventEmitter.dispatch(Constants.eventName.enemy_num_change);
        if(this.allEnemys.length <= 0){
            audioMgr.playOneShot(Constants.audios.victory);
            Game.I.isGameOver = true;
            uiMgr.show(Constants.popUIs.settleUI,[{
                isWin: true,
                headShotNum: Game.I.player.headShotNum,
                cb: ()=>{}
            }]);
        }
    }

    /**
     * 敌人节点排序
     */
    public sortEnemyList(){
        if(Game.I.isPause 
            || Game.I.isGameOver)return;
        if(this.allEnemys.length <= 1)return;
        return;
        const minSortNum: number = 400;
        let k: number = this.allEnemys.length + 20; 
        if(this.allEnemys.length == 1){
            if(this.allEnemys[0].node.parent){
               this.allEnemys[0].node.setSiblingIndex(k + minSortNum);
            }
        }else{
            this.allEnemys.sort(function(x,y){
                let a: Vec3 = x.node.position;
                let b: Vec3 = y.node.position;
                if( a.y - b.y > 0.01 ){
                    return -1;
                }else if( a.y == b.y ){
                    return 0;
                }
                return 1;
            });
            for (let i = 0; i < this.allEnemys.length; i++) {
                if(this.allEnemys[0].node.parent){
                   this.allEnemys[i].node.setSiblingIndex(i + k + minSortNum);
                }
            }
        }
    }

    /**
     * 销毁数据
     */
    public recycle(){
        this.eTimeMaps.forEach((k,v) => {
            if(v!= undefined && v != null){
                clearInterval(v)
            }
        });
        this.eTimeMaps.clear();
        this.allEnemys.forEach(e => {e.recycle(false)});
        this.allEnemys = [];
        this.map.resetData();
        this.enemyTypeRecords = [];
    }

    /**
     * 当前杀敌数
     */
    public getCurKillNum(): number{
        return this.queueEnemys.length - this.allEnemys.length;
    }

    public onDisable () {
        if(this.intervalId!= null){
           clearInterval(this.intervalId);
        }
    }
}

