import { Vec2 } from "cc";
import { TB } from "../../../config/data/schema";
import GRoleDefault from "../../base/role/GRoleDefault";
import { GTactical } from "../../entity/GTactical";
import GDefaultMode from "./GDefaultMode";
import { instantiate } from "cc";
import { _decorator } from "cc";
import { Prefab } from "cc";
import JNFrameTime from "../../../../../extensions/ngame/assets/ngame/sync/frame/game/time/JNFrameTime";
import { v3 } from "cc";
import { GModeEvent } from "../GMode";
import { app } from "../../../App";
import { Node } from "cc";
const { ccclass, property } = _decorator;


//角色
export enum GNormalModePlayerEnum{
    PLAYER, //玩家
    ENEMY, //怪物
}

export interface GNormalModePlayerInfo{
    //阵法
    tactical: GTactical;
}

export default class GNormalModeBase<T,DT> extends GDefaultMode<T,DT>{

    @property(Prefab)
    playerPrefab: Prefab = null;
    @property(Prefab)
    enemyPrefab: Prefab = null;

    @property(Node)
    objects: Node = null;

    get scene():Node{
        return this.objects;
    }

    //玩家宠物
    playerRoles: GRoleDefault[] = [];
    //敌方宠物
    enemyRoles: GRoleDefault[] = [];
    
    //玩家信息
    playerInfo:GNormalModePlayerInfo;
    //宠物信息
    enemyInfo:GNormalModePlayerInfo;
    
    //玩家宠物位置
    playerPos: Vec2 = new Vec2(-400,0);
    //怪物位置
    enemyPos: Vec2 = new Vec2(400,0);

    //是否结束游戏
    _isEndGame:boolean = false;
    get isEndGame(){return this._isEndGame;}
    set isEndGame(value){this._isEndGame = value}

    onSyncInitSuccess(){
        this.playerInfo = { tactical: GTactical.getTactical().setOffset(this.playerPos) };
        this.enemyInfo = { tactical: GTactical.getTactical(true).setOffset(this.enemyPos) };

        //调整相机
        this.camera.enabled = true;
        let camreaPos = this.camera.node.worldPosition;
        this.camera.node.worldPosition = v3(0,400,camreaPos.z)
    }

    //获取配置
    getInfo(type: GNormalModePlayerEnum): GNormalModePlayerInfo {
        if(type == GNormalModePlayerEnum.PLAYER) return this.playerInfo;
        if(type == GNormalModePlayerEnum.ENEMY) return this.enemyInfo;
    }

    //获取阵营宠物
    getOnesRole(type: GNormalModePlayerEnum):GRoleDefault[]{
        if(type == GNormalModePlayerEnum.PLAYER) return this.playerRoles;
        if(type == GNormalModePlayerEnum.ENEMY) return this.enemyRoles;
    }

    //获取存活的宠物
    getOnesRoleAlive(type: GNormalModePlayerEnum):GRoleDefault[]{
        if(type == GNormalModePlayerEnum.PLAYER) return this.playerRoles.filter(role => !!role.get());
        if(type == GNormalModePlayerEnum.ENEMY) return this.enemyRoles.filter(role => !!role.get());
    }


    //生成宠物
    onGenRole(type: GNormalModePlayerEnum,index:number,info:TB.TbGRole):GRoleDefault {

        let tactical = this.getInfo(type).tactical;
        let pos:Vec2 = this.getInfo(type).tactical.getPosition(index);
        if(!pos) return;
        let role;
        if(type == GNormalModePlayerEnum.PLAYER)
            role = instantiate(this.playerPrefab);
        if(type == GNormalModePlayerEnum.ENEMY)
            role = instantiate(this.enemyPrefab);

        let entity = role.getComponent(GRoleDefault);
        //初始化
        entity.onInit(type,info,tactical,index);

        //绑定寻敌
        entity.onQueryEunmy = () => {
            return this.getEnumy(entity,type);
        }

        //绑定死亡回调
        entity.addKillBackEvent(this.onRoleKillBack.bind(this))
        //绑定受击回调
        entity.addHitCallback(this.onHitBack.bind(this));

        this.addGObject(entity,tactical.getPosition(index));

        this.getOnesRole(type).push(entity);

        return entity;

    }

    //获取敌人
    getEnumy(player:GRoleDefault,type:GNormalModePlayerEnum):GRoleDefault{

        let enumyOnes = GNormalModePlayerEnum.ENEMY
        //如果是ENEMY 则 它的敌人是 PLAYER
        if(type == GNormalModePlayerEnum.ENEMY) enumyOnes = GNormalModePlayerEnum.PLAYER

        //获取敌人
        let roles = this.getOnesRoleAlive(enumyOnes);

        //通过距离获取最近的敌人
        if(roles[0]){
            let len = Math.abs(Vec2.distance(player.v2World,roles[0].v2World));
            let enumy = roles[0];

            for (let index = 0; index < roles.length; index++) {
                const role = roles[index];
                let tLen;
                if(tLen = Math.abs(Vec2.distance(player.v2World,role.v2World)) < len){
                    enumy = role;
                    len = tLen;
                }
                
            }

            return enumy;
        }else{
            return null;
        }

    }

    //清理缓存
    onClearCache(){

        //清理宠物
        let roles = [...this.playerRoles];
        roles.forEach(role => {
            if(!role.get()){
                this.playerRoles.splice(this.playerRoles.indexOf(role),1);
            }
        })
        roles = [...this.enemyRoles];
        roles.forEach(role => {
            if(!role.get()){
                this.enemyRoles.splice(this.enemyRoles.indexOf(role),1);
            }
        })

    }

    //角色死亡回调
    onRoleKillBack(role:GRoleDefault){
        
        //死亡销毁
        JNFrameTime.getInstance().setTimeout(() => {
            if(role.isValid)
                role.node.destroy()
            else console.log(role,"无法销毁");
        },3000)

        //清理
        this.onClearCache();

        //如果任何一方死亡则调用结束
        if(!this.isEndGame){
            if(this.playerRoles.length == 0){
                this.isEndGame = true;
                return this.onBattleEnd(GNormalModePlayerEnum.ENEMY)
            }
            if(this.enemyRoles.length == 0){
                this.isEndGame = true;
                return this.onBattleEnd(GNormalModePlayerEnum.PLAYER)
            }
        }

    }

    //战斗结束(胜利队伍)
    onBattleEnd(win:GNormalModePlayerEnum){}

    //角色受击回调
    onHitBack(role:GRoleDefault,hit:number){

        if(!role.get()) return;

        //添加受击显示
        app.event.emit(GModeEvent.HIT,{
            mode:this,
            role:role,
            hit:hit,
            world:role.v2World,
            camera:this.camera,
        });

    }

}

