import { _decorator, Component, Node, CCInteger, AnimationComponent, find, instantiate, Vec3, director, Vec2, log, Prefab, loader, AnimationState, v4, ModelComponent } from 'cc';
import { GameModel } from '../../../models/GameModel';
import { EventDispatcher } from '../../../../engines/events/EventDispatcher';
import GameConfigManager from '../../../models/GameConfigManager';
import CCSAnimationUtils from '../../../../engines/utils/CCSAnimationUtils';
import { FireEventComponent } from './components/FireEventComponent';
import { SoundManager } from '../../../../engines/sounds/SoundManager';
import { GameController } from '../GameController';
const { ccclass, property } = _decorator;


export class WeaponBase extends EventDispatcher{

    /**
     * 武器配置
     */
    public weaponConfig:any;
    /**
     * 武器的预制体
     */
    protected weaponPrefab:Prefab;
    /**
     * 子弹数量更改
     */
    public static EVENT_BULLET_CHANGE:string="EVENT_BULLET_CHANGE";

    protected leftHand:AnimationComponent;
    protected rightHand:AnimationComponent;
    protected leftSocket:Node;
    protected rightSocket:Node;

    public leftWeapon:Node;
    public rightWeapon:Node;

    protected gunfirePrefab:Prefab;
    protected leftGunFire:AnimationComponent;
    protected rightGunFire:AnimationComponent;

    /**
     * 开火方向 1 左边 2中间 3左边
     */
    public fireKey:number=0;
    protected isLeftFire:boolean;
    /**
     * 开火中
     */
    protected isFireing:boolean=false;
    protected isFire:boolean=false;
    public isReload:boolean=false;

    constructor(leftHand:AnimationComponent,rightHand:AnimationComponent){
        super();

        this.leftHand=leftHand;
        // this.leftHand.addComponent(FireEventComponent);
        this.rightHand=rightHand;
        // this.rightHand.addComponent(FireEventComponent);

        //武器配置
        this.weaponConfig=GameConfigManager.GetWeaponConfig(GameModel.single.currentWeaponId);
        this.weaponPrefab=loader.getRes(this.weaponConfig.prefab);
        
        this.InitHands();
        this.InitWeapons();
        this.Idle();
    }

    /**
     * 销毁
     */
    Destroy():void{
        this.weaponPrefab=null;
        //枪口火焰

        this.leftSocket.removeChild(this.leftWeapon);
        this.leftWeapon.destroy();
        this.leftWeapon=null;
        this.rightSocket.removeChild(this.rightWeapon);
        this.rightWeapon.destroy();
        this.rightWeapon=null;

        this.gunfirePrefab=null;
        this.leftGunFire.node.destroy();
        this.leftGunFire=null;
        this.rightGunFire.node.destroy();
        this.rightGunFire=null;
    }

    protected InitHands():void{
        this.leftSocket=find("RootNode/Arm/upper_arm_R/lower_arm_R/transform1/hand_R/transform2/Guns",this.leftHand.node);
        this.rightSocket=find("RootNode/Arm/upper_arm_R/lower_arm_R/transform1/hand_R/transform2/Guns",this.rightHand.node);

        // CCSAnimationUtils.SetAnimationEvent(this.leftHand,this.weaponConfig.handFireAnimation,this.weaponConfig.fireAnimationEvents);
        // CCSAnimationUtils.SetAnimationEvent(this.rightHand,this.weaponConfig.handFireAnimation,this.weaponConfig.fireAnimationEvents);

        //根据武器配置设置手臂动画速度
        CCSAnimationUtils.SetAnimationSpeed(this.leftHand,this.weaponConfig.handFireAnimation,this.weaponConfig.handFireAnimationSpeed);
        CCSAnimationUtils.SetAnimationSpeed(this.leftHand,this.weaponConfig.handReloadAnimation,this.weaponConfig.handReloadAnimationSpeed);

        CCSAnimationUtils.SetAnimationSpeed(this.rightHand,this.weaponConfig.handFireAnimation,this.weaponConfig.handFireAnimationSpeed);
        CCSAnimationUtils.SetAnimationSpeed(this.rightHand,this.weaponConfig.handReloadAnimation,this.weaponConfig.handReloadAnimationSpeed);
    }

    protected InitWeapons():void{
        this.leftWeapon=instantiate(this.weaponPrefab);
        this.leftSocket.addChild(this.leftWeapon);
        this.rightWeapon=instantiate(this.weaponPrefab);
        this.rightSocket.addChild(this.rightWeapon);
        
        this.gunfirePrefab=loader.getRes("d3d/gunFire/GunFire");
        this.leftGunFire=instantiate(this.gunfirePrefab).getComponent(AnimationComponent);
        this.rightGunFire=instantiate(this.gunfirePrefab).getComponent(AnimationComponent);

        let socket:Node=find(this.weaponConfig.fireSocketPath,this.leftWeapon);
        if(socket==null){
            console.error("配置挂点错误："+this.weaponConfig);
        }else{
            socket.addChild(this.leftGunFire.node);
        }
        socket=find(this.weaponConfig.fireSocketPath,this.rightWeapon);
        if(socket==null){
            console.error("配置挂点错误："+this.weaponConfig);
        }else{
            socket.addChild(this.rightGunFire.node);
        }

        let color4=v4(1,1,1,0);
        let leftWeaponModel:ModelComponent=this.leftWeapon.getComponentInChildren(ModelComponent);
        let rightWeaponModel:ModelComponent=this.rightWeapon.getComponentInChildren(ModelComponent);
        leftWeaponModel.sharedMaterial.setProperty('rimColor',color4);
        rightWeaponModel.sharedMaterial.setProperty('rimColor',color4);
    }
    
    StartFire(fireKey:number):void{
        this.fireKey=fireKey;
        this.isFireing=true;
        this.MoveFirePosition();
    }

    StopFire():void{
        this.isFireing=false;
        if(this.isReload){
            return;
        }
        this.Idle();
    }

    lastFireTime:number=0;
    Update(dt:number):void{
        if(this.isFireing==false||this.isReload){
            return;
        }
        //非自动技能时的开枪逻辑
        if(GameController.single.currentSkill!=null&&GameController.single.currentSkill.unController==false){
            let currentTime:number=director.getCurrentTime();
            if(currentTime-this.lastFireTime>GameController.single.currentSkill.fireInterval){
                this.Fire(!GameController.single.currentSkill.infiniteAmmo);
                this.lastFireTime=currentTime;
            }
        }else{
            if(this.isFire==false){
                //换弹
                if(this.bulletCount<=0){
                    this.Reload();
                    return;
                }
                this.Fire(true);
            }
        }
    }

    /**
     * 换弹
     */
    Reload():void{
        this.isReload=true;
        this.leftHand.play(this.weaponConfig.handReloadAnimation);
        this.rightHand.play(this.weaponConfig.handReloadAnimation);
        //左右手同步
        this.leftHand.on(AnimationComponent.EventType.FINISHED,this.ReloadComplete,this,true);
        SoundManager.single.StopSound("Weapon");
        SoundManager.single.PlaySound("Weapon",this.weaponConfig.reloadSound);
    }

    /**
     * 换弹完成
     */
    ReloadComplete():void{
        this.bulletCount=this.maxBulletCount;
        this.isReload=false;
        if(this.isFireing==false){
            this.Idle();
        }
    }

     /**
     * 将手移动到指定位置
     */
    MoveFirePosition():void{
        if(this.fireKey==0){
            return;
        }
        let Pos:Vec3;
        if(this.fireKey==1){
            Pos=this.leftHand.node.position;
            Pos.x=-0.4;
            this.leftHand.node.setPosition(Pos);
        }else if(this.fireKey==3){
            Pos=this.rightHand.node.position;
            Pos.x=0.4;
            this.rightHand.node.setPosition(Pos);
        }else if(this.fireKey==2){
            Pos=this.leftHand.node.position;
            Pos.x=-0.1;
            this.leftHand.node.setPosition(Pos);
            Pos=this.rightHand.node.position;
            Pos.x=0.1;
            this.rightHand.node.setPosition(Pos);
        }
    }
    
    /**
     * 开火
     */
    Fire(bullet:boolean):void{
        this.isFire=true;
    }

    /**
     * 空闲
     */
    private Idle():void{
        if(this.isFire){
            if(this.isLeftFire){
                this.rightHand.crossFade("Idle",0.5);
            }else{
                this.leftHand.crossFade("Idle",0.5)
            }
        }else{
            this.leftHand.crossFade("Idle",0.5);
            this.rightHand.crossFade("Idle",0.5);
        }
    }

    /**
     * 剩余子弹数量
     */
    get bulletCount():number{
        return this._bulletCount;
    }
    private _bulletCount:number=0;
    set bulletCount(value:number){
        this._bulletCount=value;
        if(this._bulletCount<=0){
            //换弹
            this.Reload();
            this._bulletCount=0;
        }
        this.DispatchEvent(WeaponBase.EVENT_BULLET_CHANGE);
    }

    /**
     * 弹夹数量
     */
    get maxBulletCount():number{
        return this.weaponConfig.clip;
    }

    /**
     * 换弹进度
     */
    get reloadProgress():number{
        if(this.isReload){
            let state:AnimationState=this.leftHand.getState(this.weaponConfig.handReloadAnimation);
            return  state.time/state.length;
        }
        return -1;
    }

 
}