import {YtAssetsManager} from "../../libs/yt/index";
import {YtDisplayPool} from "../../libs/yt/index";
import {YtSceneManager} from "../../libs/yt/index";
import {NetManager} from "../../libs/tw/manager/NetManager"
import {DataManager} from "../../libs/tw/manager/DataManager"
//import {YtSceneManager} from "./YtSceneManager"
import {SlModuleName} from "../../libs/sl/index";
import {SlGameSceneModule} from "../../libs/sl/index";
import {GDispatcher} from "../../libs/tc/util/GDispatcher";
import {ExGameScene} from "./ExGameScene";
import { UseParticlee } from './UseParticlee';
export class ExGameSceneCon extends SlGameSceneModule{
    private _gold;

    private static instance: ExGameSceneCon;

    public static get ins(): ExGameSceneCon {
        if (!this.instance) {
            this.instance = new ExGameSceneCon();
        }
        return this.instance;
    }

    //游戏开始第一帧
    private gameBefore;


    //场景触摸状态
    private sceneEventState;


    //地图
    private maps=[]
    private maps2=[]
    private maps3=[]
    private maps4;
    private maps5;
    private maps6;
    private maps7;
    private maps8;
    private maps9;

    //地图预载最大长度
    private mapsMaxX=0;

    //物理躯壳
    private constraintBox;
    private playerBox;


    //物理灵魂
    private constraint;
    private constraint2;
    private player;

    //物理引擎默认对象
    private Matter=window["Matter"];
    private World = this.Matter.World;
    private Bodies = this.Matter.Bodies;
    private Engine=this.Matter.Engine;
    private engineMatter = this.Engine.create();


    
    //游戏暂停状态
    private isPause=false;

    private FPS=60;

    //连线模型
    private tube;

    //地图索引
    private ij:number=0;

    //连线长度
    private tubeLength:number=0;

    //用户状态
    private playerState:number;


    private touchState=0;

    constructor(){
        super()
    }

    public init(){
        YtDisplayPool.ins.displayPool[SlModuleName.GAME_PLAY_SCENE]=this;
    }

    protected resetGame(){
        this.clearAll(()=>{
            ExGameScene.ins.creatScene()
            var scene=YtSceneManager.ins.scene;
            this.display=ExGameScene.ins.display;
            var gl = new BABYLON.GlowLayer("glow", YtSceneManager.ins.scene);
            gl.intensity = 0.5;
            this.creatMap()
            this.creatPlay()
            this.usePhysics()
            
            this.removeEvent()
            this.removeEvent2()
            this.addEvent()
            this.addEvent2()
            this.creatMusic()
            if(localStorage.music==false){
                this.setMusicVolume(0)
            }else{
                this.setMusicVolume(1)
            }


           // this.againGame()
        })
    }


    protected againGame(){
        GDispatcher.dispatchEvent("enableMouseEvt",false);
        this.score=0;
        this.mapCon=0;
        this.mapConState=true;
        this.creatPlay()
        this.usePhysics()
        this.removeEvent()
        this.removeEvent2()
        this.addEvent()
    }


    private musics;


    private creatMusic(){
        this.musics={
            boom:new BABYLON.Sound("Cello",[YtAssetsManager.ins.resourceObject["binarys"]["gameScene"]["boom"]["url"]] , YtSceneManager.ins.scene,()=>{},{loop:false}),
            button:new BABYLON.Sound("Cello",YtAssetsManager.ins.resourceObject["binarys"]["gameScene"]["button"]["url"] , YtSceneManager.ins.scene,()=>{},{loop:false}),
            light:new BABYLON.Sound("Cello",YtAssetsManager.ins.resourceObject["binarys"]["gameScene"]["light"]["url"] , YtSceneManager.ins.scene,()=>{},{loop:false}),
            pick:new BABYLON.Sound("Cello",YtAssetsManager.ins.resourceObject["binarys"]["gameScene"]["pick"]["url"] , YtSceneManager.ins.scene,()=>{},{loop:false}),
        }
    }

    private setMusicVolume(volume){
        for (const key in this.musics) {
            if (this.musics.hasOwnProperty(key)) {
                const element = this.musics[key];
                element.setVolume(volume)
            }
        }
    }
    

/*     protected gameOver():void{
        this.removeEvent()
        console.log("游戏结束")
    } */


    protected clearAll(callback){
        callback()
    }

    //创建场景基本元素
    protected creatMap():void{
        this.maps=[];
        this.maps2=[];
        this.maps3=[];
        this.maps4 = BABYLON.MeshBuilder.CreatePlane("baziBox", {width: 2.2, height:2.2},YtSceneManager.ins.scene);
        this.maps4.rotation.y=Math.PI*0.5;
        this.maps4.position.y=-100;
        this.maps4.material=this.display.b_1Material;


        this.maps5 = BABYLON.MeshBuilder.CreatePlane("baziBox", {width: 2.2, height:2.2},YtSceneManager.ins.scene);
        this.maps5.rotation.y=Math.PI*0.5;
        this.maps5.position.y=-100;
        this.maps5.material=this.display.b_2Material;
        
        this.maps6 = BABYLON.MeshBuilder.CreatePlane("baziBox", {width: 2.2, height:2.2},YtSceneManager.ins.scene);
        this.maps6.rotation.y=Math.PI*0.5;
        this.maps6.position.y=-100;
        this.maps6.material=this.display.b_3Material;

        this.maps7 = BABYLON.MeshBuilder.CreatePlane("baziBox", {width: 2.2, height:2.2},YtSceneManager.ins.scene);
        this.maps7.rotation.y=Math.PI*0.5;
        this.maps7.position.y=-100;
        this.maps7.material=this.display.b_4Material;
        this.maps7.scaling.y=1.5;

        this.maps8 = BABYLON.MeshBuilder.CreatePlane("baziBox", {width: 1.8, height:3.6},YtSceneManager.ins.scene);
        this.maps8.rotation.y=Math.PI*0.5;
        this.maps8.position.y=-100;
        this.maps8.material=this.display.b_6Material;
        this.maps8.scaling.y=1.5;


        this.maps8.setPivotMatrix(BABYLON.Matrix.Translation(0, -1.8, 0), false);
        
        this.maps9 = BABYLON.MeshBuilder.CreatePlane("baziBox", {width: 1.8, height:1.8},YtSceneManager.ins.scene);
        this.maps9.rotation.y=Math.PI*0.5;
        this.maps9.position.y=-100;
        this.maps9.material=this.display.b_5Material;
        this.maps9.scaling.y=4
        this.maps9.scaling.x=0.6




       

        console.log("this.maps8.material.diffuseTexture")
        console.log(this.maps8.material.diffuseTexture)

        this.maps8.rotation.x=-Math.PI*0.2;
        var tween = new TWEEN.Tween(  this.maps8.rotation);
        tween.to({x:Math.PI*0.2}, 2000);
        tween.yoyo(true);
        tween.start();
        tween.repeat(Infinity)

        var tween = new TWEEN.Tween( this.display.b_5Material.diffuseTexture);
        tween.to({ vOffset:2}, 2000);
        tween.start();
        tween.repeat(Infinity)

        var tween2 = new TWEEN.Tween( this.maps5.rotation);
        tween2.to({ z:Math.PI*2}, 2000);
        tween2.start();
        tween2.repeat(Infinity)


        for(var i=0; i<=20;i++){
            console.log(56565)
            this.maps[i] = BABYLON.MeshBuilder.CreateBox("myBox1_"+i, {height: 10, width: 2, depth: 1},YtSceneManager.ins.scene);
            this.maps[i].position.y+=100;
           // this.maps[i].convertToUnIndexedMesh();
            this.maps2[i] = BABYLON.MeshBuilder.CreateBox("myBox2_"+i, {height: 10, width: 2, depth: 1},YtSceneManager.ins.scene);
            this.maps2[i].position.y+=100;
          //  this.maps2[i].convertToUnIndexedMesh();
            this.maps3[i] = BABYLON.MeshBuilder.CreateBox("myBox3_"+i, {height: 10, width: 2, depth: 100},YtSceneManager.ins.scene);
            this.maps3[i].position.y+=100;
            this.maps3[i].convertToUnIndexedMesh();
            if(Math.round(i%2)==0){
                this.maps[i].material=this.display.map1Material
                this.maps2[i].material=this.display.map1Material
                this.maps3[i].material=this.display.map1Material
            }else{
                this.maps[i].material=this.display.map2Material
                this.maps2[i].material=this.display.map2Material
                this.maps3[i].material=this.display.map2Material
            }
        }
    }


    /**
     * 创建玩家躯壳
     */

    protected creatPlay():void{
        this.constraintBox = BABYLON.Mesh.CreateSphere("sphere1", 1, 0.3, YtSceneManager.ins.scene);
        this.constraintBox.position.y = 0;
        this.constraintBox.position.x = 10;
        this.constraintBox.material = this.display.lightMaterial;
    
        // Our built-in 'ground' shape. Params: name, width, depth, subdivs, scene
        this.playerBox = BABYLON.Mesh.CreateSphere("boxPlayer", 8, 0.5, YtSceneManager.ins.scene);
        this.playerBox.position.y =0;
        this.playerBox.position.x =10;
        this.playerBox.material = this.display.lightMaterial;

        this.setColor(0)
    }

    /**
     * 初始化物理引擎，注入灵魂
     */

    private isVisible=false


    private clearTimeouts=[]

    private pendulumState;

    private beforeReady=false;


    private eventBefore=0;

    //重置初始化数据
    private resetDatas():void {

       


        //靶子位置
        this["maps4"].position.y=-1000;
        this["maps5"].position.y=-1000;
        this["maps6"].position.y=-1000;
        this["maps7"].position.y=-1000;
        this["maps8"].position.y=-1000;
        this["maps9"].position.y=-1000;
        this.gameBefore=0;
        this.mapsMaxX=0;
        this.ij=0;
        this.tubeLength=0;
        this.playerState=1;
        this.sceneEventState=0;
        this.isVisible=false
        this.colorState=0;
        this.targetState=4;
        this.pendulumState=true;
        this.resurgenceState=1;

        
        this.mapCon=0;
        this.mapConState=true;
        this.mapStateCatch=0;
        //坡度状态
        this.slopeState=null;

        this.isPause=false
        this.beforeReady=false;


        this.checkpointCycle=0;
        this.checkpointCycleCount=1;

        this.touchState=0;
        //this.clearTimeouts=[];
    }

    //初始化物理引擎
    protected usePhysics():void{

      //  GDispatcher.dispatchEvent("enableMouseEvt",false);
       // ModuleManager.ins.openModule(TlModuleName.WAITING_PANEL);
       
       this.touchState=0;
        // create an engine
        this.resetDatas()

        this.clearTimeouts.forEach((clearTime)=>{
            clearTimeout(clearTime) 
        })

        this.clearTimeouts=[]

        this.clearTimeouts.push(setInterval(()=>{
           // YtSceneManager.ins.engine.resize();
            GDispatcher.dispatchEvent("fps",{text:Math.round(YtSceneManager.ins.engine.getFps())});
        },1000))

        this.clearTimeouts.push(setInterval(()=>{
            this.pendulumState=!this.pendulumState;
           // GDispatcher.dispatchEvent("enableMouseEvt",true);
        },3000))

       
        this.World = this.Matter.World;
        this.Bodies = this.Matter.Bodies;
        this.Engine=this.Matter.Engine;
        this.engineMatter = this.Engine.create();;

        this.engineMatter.world.gravity.y=100
        this.player = this.Bodies.rectangle(0.1, 0.1, 0.1,0.1,{ restitution: 0.9 });
        this.player.mass=0.01

        this.player.position.x=this.playerBox.position.x;

        this.playerBox.isVisible=false;
        this.constraintBox.isVisible=false;

        this.player.position.y=this.playerBox.position.y;
        this.constraint = this.Matter.Constraint.create({
            pointA: { x: this.constraintBox.position.x, y: this.constraintBox.position.y },
            bodyB: this.player,
            pointB: { x: 0, y: 0 },
            length:5,
        });

        console.log("this.constraint")
        console.log(this.constraint)

        this.World.add(this.engineMatter.world, [this.constraint,this.player]);

      

        console.log("this.World")
        console.log(this.engineMatter.world.bodies)

        UseParticlee.ins.start()
       // UseParticlee.ins.setPSize(0.1,0.5);

/* 
       if(localStorage.firstInit){

       } */

       setTimeout(()=>{
            this.engineMatter.world.gravity.y=-0.01;
            this.isVisible=true;
            this.maps.forEach((map)=>{
                if (map.intersectsMesh(this.constraintBox, false)) {
                    this.constraintBox.position=new BABYLON.Vector3(map.position.x,map.position.y,map.position.z);
                    this.constraintBox.position.y=map.position.y-5;
                    this.constraintBox.isVisible=true;
                }
            })
            this.touchState=0;
           
       },500)

       setTimeout(()=>{
           this.beforeReady=true;
       },3000)
        
        this.display.skySphere.position=new BABYLON.Vector3(0,0,0);
        this.display.camera3.target=new BABYLON.Vector3(this.playerBox.position.x,-5,this.playerBox.position.z) ;

       
      
    }

    /**
     * 添加事件
     */
    protected addEvent():void{
        GDispatcher.addEvent("MouseDown",this.doEvents["MouseDown"]=this.onMouseDown,this)

        GDispatcher.addEvent("MouseUp",this.doEvents["MouseUp"]=()=>{
            if(this.touchState==1){
                this.touchState=0;
                this.sceneEventState=0
                this.World.remove(this.engineMatter.world, [this.constraint]);
            }
           
        },this)

        console.log("GDispatcher")
       // console.log(GDispatcher.thisObjPool)

        GDispatcher.addEvent("resurgence",this.doEvents["resurgence"]=()=>{
            this.doResurgence()
         },this)

        GDispatcher.addEvent("clearScene",this.doEvents["clearScene"]=()=>{
            this.clearScene()
        },this)

        GDispatcher.addEvent("buttonClick",this.doEvents["buttonClick"]=()=>{
            this.musics.button.play()
        },this)

        GDispatcher.addEvent("mussicOff",this.doEvents["mussicOff"]=()=>{
            this.setMusicVolume(0)
        },this)

        GDispatcher.addEvent("mussicOn",this.doEvents["mussicOn"]=()=>{
            this.setMusicVolume(1)
        },this)

       
        // alert(222)

        if(this.eventBefore==0){
            this.eventBefore++
            GDispatcher.addEvent("resurgence",this.doEvents["resurgence"]=()=>{},this)
            GDispatcher.addEvent("clearScene",this.doEvents["clearScene"]=()=>{},this)
        }
        

        this.doEvents["BeforeRender"]=YtSceneManager.ins.scene.onBeforeRenderObservable.add(()=>{
            this.beforeRender()
        })

        GDispatcher.dispatchEvent("updateScore",{state:1,score:0});
        this.doEvents["updateScore"]=setInterval(()=>{
            if(this.isPause==true){
                return false;
            }
            if(this.gameBefore!=0){
                this.score+=2;
                GDispatcher.dispatchEvent("updateScore",{state:1,score:2});
            }
        },1000)

        GDispatcher.addEvent("resetGame3D",this.doEvents["resetGame3D"]=()=>{
           this.againGame()
        },this)
    }




    private clearsd;
    protected onMouseDown(){
        if(this.touchState==0){
            this.touchState=1;
            console.log("MouseDown")
            this.gameBefore++
            if(this.gameBefore>1){
                this.musics.light.play()
                this.constraintBox.position.x=this.playerBox.position.x+3;
                this.constraintBox.position.y=0;
                this.constraintBox.scaling.y=6000
                this.constraintBox.isVisible=false;
                this.World.remove(this.engineMatter.world, [this.constraint]);
    
    
                clearTimeout(this.clearsd)
    
                this.clearsd=setTimeout(()=>{
                  
                this.constraintBox.scaling.y=1
                this.constraintBox.isVisible=true;
                    this.maps.forEach((map)=>{
                        if (map.intersectsMesh(this.constraintBox, false)) {
                            this.constraintBox.position=new BABYLON.Vector3(map.position.x,map.position.y,map.position.z) ;
                            this.constraintBox.position.y=map.position.y-5;
                        }
                    })
    
                     this.sceneEventState=1
    
                    // this.sceneEventState=1
    
                    this.constraint = this.Matter.Constraint.create({
                        pointA: { x: this.constraintBox.position.x, y: this.constraintBox.position.y },
                        bodyB: this.player,
                        pointB: { x: 0, y: 0 },
                    });
    
                    this.World.add(this.engineMatter.world, [this.constraint]);
                },100)
               
            }else{
                this.sceneEventState=1
            }
        }
    }

    /**
     * 移除事件
     */
    protected removeEvent(){
        GDispatcher.removeEvent("MouseDown",this.doEvents["MouseDown"])
        GDispatcher.removeEvent("MouseUp",this.doEvents["MouseUp"])

        if(this.doEvents["resurgence"]){
            GDispatcher.removeEvent("resurgence",this.doEvents["resurgence"])
        }

        if(this.doEvents["clearScene"]){
            GDispatcher.removeEvent("clearScene",this.doEvents["clearScene"])
        }

        if(this.doEvents["buttonClick"]){
            GDispatcher.removeEvent("buttonClick",this.doEvents["buttonClick"])
        }

      /*   if(this.doEvents["mussicOff"]){
            GDispatcher.removeEvent("mussicOff",this.doEvents["mussicOff"])
        }

        if(this.doEvents["mussicOn"]){
            GDispatcher.removeEvent("mussicOn",this.doEvents["mussicOn"])
        } */

      //  GDispatcher.removeEvent("resurgence",this.doEvents["resurgence"])
       // GDispatcher.removeEvent("resurgence",this.doEvents["resurgence"])
        YtSceneManager.ins.scene.onBeforeRenderObservable.remove(this.doEvents["BeforeRender"])
        clearInterval(this.doEvents["updateScore"])
        clearTimeout(this.doEvents["setHardwareScalingLevel"])
    }

    /**
     * 添加全局事件
     */
    protected addEvent2():void{
        this.doEvents["setHardwareScalingLevel"]=setTimeout(()=>{


            if(window.navigator.userAgent.indexOf('iPhone OS 8') > -1 ){
                GDispatcher.dispatchEvent("tips",{text:"游戏不兼容ios8系统，请升级系统!"});
                setTimeout(()=>{
                    GDispatcher.dispatchEvent("GAME_START_SCENE");
                },2000)
                return false;
            }


            var _s=2-(this.FPS/60)*1.4;
            if(_s<=0.7){
                _s=0.7;
                GDispatcher.dispatchEvent("tips",{text:"手机配置较高,最佳渲染效果!"});
            }else{
                GDispatcher.dispatchEvent("tips",{text:"已降低渲染效果，以提高性能!"});
            }
            YtSceneManager.ins.engine.setHardwareScalingLevel(_s)
            console.log("优化渲染精度"+_s)

            setTimeout(()=>{
                GDispatcher.dispatchEvent("GAME_START_SCENE");
            },2000)
        },3000)
    }

    /**
     * 移除全局事件
     */
    protected removeEvent2(){
        GDispatcher.removeEvent("resetGame3D",this.doEvents["resetGame3D"])
        GDispatcher.removeEvent("setHardwareScalingLevel",this.doEvents["setHardwareScalingLevel"])
    }

    /**
     * 每帧都执行
     */


    private nowTime;
    private lastTime ;

    private pickState=0;

    protected beforeRender(){

      /*   console.log("localStorage.music")
        console.log(localStorage.music) */

        this.setMusicVolume(1)
        if(localStorage.music=="2"){
            this.setMusicVolume(0)
        }else if(localStorage.music=="1"){
            this.setMusicVolume(1)
        }
       // console.log(this.beforeReady)
      
        this.nowTime=Date.now();
        var dt = this.lastTime ? (this.nowTime - this.lastTime)/1000 : 0;
        dt = Math.min(1 / 10, dt);
        this.FPS= YtSceneManager.ins.engine.getFps();

      //  console.log(dt)
        this.Engine.update(this.engineMatter)


        if(this.gameBefore==0){
            if(this.pendulumState){
                this.Matter.Body.applyForce(this.player, {x:this.player.position.x,y:this.player.position.y}, {x:0.000001*dt,y:0})
            }else{
                this.Matter.Body.applyForce(this.player, {x:this.player.position.x,y:this.player.position.y}, {x:-0.000001*dt,y:0})
            }         
        }

        var path = [
            this.playerBox.position,
            this.constraintBox.position,
        ]

        if(this.tube){
            this.tube.dispose()
        }
    
        if(this.gameBefore==0){
            if(this.tube){
                this.tube.dispose()
            }
            this.tube = BABYLON.MeshBuilder.CreateTube("tube", {path: path, radius: 0.03}, YtSceneManager.ins.scene);
            this.tube.freezeWorldMatrix();
            this.tube.material = this.display.lightMaterial;
        }else{
            this.beforeReady=false;
            this.maps.forEach((map)=>{
                if (map.intersectsMesh(this.playerBox, false)) {
               //     this.isPause=true;
                    this.World.remove(this.engineMatter.world, [this.constraint]);
                    console.log("死亡")
                   if(this.playerState==1){
                        this.died()
                        this.musics.boom.play()
                   }
                    this.playerState=0;
                }
            })
            this.maps2.forEach((map)=>{
                if (map.intersectsMesh(this.playerBox, false)) {
                    this.World.remove(this.engineMatter.world, [this.constraint]);
                    console.log("死亡")
                    if(this.playerState==1){
                        this.died()
                        this.musics.boom.play()
                    }
                    this.playerState=0;
                }
            })


            this.pickCon()
           
            
            this.display.camera3.target=new BABYLON.Vector3(this.playerBox.position.x,this.playerBox.position.y,this.playerBox.position.z) ;
            this.display.skySphere.position=new BABYLON.Vector3(this.playerBox.position.x,this.playerBox.position.y,this.playerBox.position.z) ;
        }


        if(this.beforeReady==false){
            this.updateMap()
        }
            this.playerBox.position.x=this.player.position.x;
            this.playerBox.position.y=this.player.position.y;
            this.display.light4.position=this.playerBox.position;
    
            if(this.sceneEventState==1){
               
                this.tubeLength+=0.1*60/this.FPS;
                if(this.tubeLength>=1){
                    this.tubeLength=1
                }
                var _x=(this.constraintBox.position.x-this.playerBox.position.x)
                var _y=(this.constraintBox.position.y-this.playerBox.position.y)
    
                _x=this.tubeLength*_x
                _y=this.tubeLength*_y
              
                path = [
                    this.playerBox.position,
                    new BABYLON.Vector3(this.playerBox.position.x+_x,this.playerBox.position.y+_y,0),
                ]
                if(this.tube){
                    this.tube.dispose()
                }
                this.tube = BABYLON.MeshBuilder.CreateTube("tube", {path: path, radius: 0.03}, YtSceneManager.ins.scene);
                this.tube.freezeWorldMatrix();
                this.tube.material = this.display.lightMaterial;
                //this.engineMatter.world.gravity.x=0.01;
                if(this.player.position.x<=this.constraintBox.position.x){
                    this.Matter.Body.applyForce(this.player, {x:this.player.position.x,y:this.player.position.y}, {x:0.000005*dt,y:-0.000005*dt})
                }else{
                    this.Matter.Body.applyForce(this.player, {x:this.player.position.x,y:this.player.position.y}, {x:0.000005*dt,y:0.000005*dt})
                }
               
            }else if(this.sceneEventState==0){
                //this.engineMatter.world.gravity.x=0;
                this.Matter.Body.applyForce(this.player, {x:this.player.position.x,y:this.player.position.y}, {x:0,y:0})
                this.tubeLength=0
            }


            if(this.isVisible==true){
                this.playerBox.isVisible=true;
               // this.constraintBox.isVisible=true;
                this.tube.isVisible=true;
                UseParticlee.ins.Position(this.playerBox)
            }else{
                this.playerBox.isVisible=false;
              //  this.constraintBox.isVisible=false;
                this.tube.isVisible=false;
            }
      
            this.lastTime=this.nowTime;
           // console.log(this.playerBox.position)
    }



    /**
     * 根据场景动态更新地图
     */

    private mapCon=0;
    private mapCon2=1;
    private mapCon3=0;
    private mapConState=true;

    private mapStateCatch=0;

    //坡度状态
    private slopeState=null;


    //检测是否击中靶子
    private pickCon(){
        for(var i=4;i<=9;i++){
            if (this["maps"+i].intersectsMesh(this.playerBox, false)) {
                this.musics.pick.play()
                if(i==8){
                    //是否击中摆动靶子的靶心
                    if(this.playerBox.position.y-this["maps"+i].position.y-4<=0.5&&this.playerBox.position.y-this["maps"+i].position.y-4>=-0.5){
                        UseParticlee.ins.startBazi(new BABYLON.Vector3(this["maps"+i].position.x,this["maps"+i].position.y-4,this["maps"+i].position.z),0)
                        console.log("jz")
                        this.pickCombo(i)
                        this.pickState=i
                       
                    }else{
                        this.pickCombo(-1)
                        this.pickState=0;
                        UseParticlee.ins.startBazi(new BABYLON.Vector3(this["maps"+i].position.x,this["maps"+i].position.y-4,this["maps"+i].position.z),1)
                    }
                   
                    console.log(this["maps"+i].position)
                    console.log(this.playerBox.position)
                }else if(i==9){
                    //是否击中瀑布
                    GDispatcher.dispatchEvent("addScore",{score:"过关奖励+10"});
                    GDispatcher.dispatchEvent("updateScore",{state:1,score:10});
                     UseParticlee.ins.startBazi(new BABYLON.Vector3(this["maps"+i].position.x,this["maps"+i].position.y,this["maps"+i].position.z),2)
                }else{

                  
                     //是否击中普通靶子的靶心
                    if(this.playerBox.position.y-this["maps"+i].position.y<=0.4&&this.playerBox.position.y-this["maps"+i].position.y>=-0.6){
                        this.pickCombo(i)
                        this.pickState=i
                        UseParticlee.ins.startBazi(new BABYLON.Vector3(this["maps"+i].position.x,this["maps"+i].position.y,this["maps"+i].position.z),0)
                    }else{
                        this.pickCombo(-1)
                        this.pickState=0;
                        UseParticlee.ins.startBazi(new BABYLON.Vector3(this["maps"+i].position.x,this["maps"+i].position.y,this["maps"+i].position.z),1)
                    }
                    console.log(this["maps"+i].position)
                    console.log(this.playerBox.position)
                }
                
                this["maps"+i].position.y=-100
               
                setTimeout(()=>{
                    UseParticlee.ins.stopBazi()
                },50)

                if(i==9){
                    if(this.colorState<4){
                        this.colorState++
                        this.setColor(this.colorState);
                    }else{
                        this.colorState=0
                        this.setColor(this.colorState);
                    }
                }
            }
        }
    }


    //金币加成统计，连击+1，最大5分
    private addScoreCount=2;

    private pickCombo(i){
        //判断是否连续击中靶心

        console.log("this.pickState")
        console.log(this.pickState)
        console.log(i)

        if(i==-1){
            GDispatcher.dispatchEvent("addScore",{score:"+1"});
            GDispatcher.dispatchEvent("updateScore",{state:1,score:1});
            return false;
        }

        if(this.pickState==8&&i==4){
            console.log("连击"+i)
            this.addScoreCount++
        }else if(this.pickState==9&&i==5){
            console.log("连击"+i)
            this.addScoreCount++
        }else if(i-this.pickState==1&&this.pickState!=8){
            console.log("连击"+i)
            this.addScoreCount++
        }else{
            this.addScoreCount=2;
        }

        if(this.addScoreCount>2){
            if(this.addScoreCount>5){
                this.addScoreCount=5;
            }
            GDispatcher.dispatchEvent("addScore",{score:"连击靶心+"+this.addScoreCount});
            GDispatcher.dispatchEvent("updateScore",{state:1,score:this.addScoreCount});
        }else{
            GDispatcher.dispatchEvent("addScore",{score:"击中靶心+"+this.addScoreCount});
            GDispatcher.dispatchEvent("updateScore",{state:1,score:this.addScoreCount});
        }
    }

    //动态更新地图

    private checkpointCycle=0;
    private checkpointCycleCount=1;
    private lostMapStateCatch;
    protected updateMap():void{
           // this.mapCon2=1;
            if(this.playerBox.position.x>this.mapsMaxX-20){
                this.mapCon2=1;
                if(this.score-this.checkpointCycle>50){
                    console.log("过关")
                    this.checkpointCycle=this.score
                    if(this.checkpointCycleCount>2){
                        this.checkpointCycleCount=1
                    }else{
                        this.checkpointCycleCount++
                    }
                }

                if(this.score>0){
                    this.checkPoint(this.checkpointCycleCount)
                }else{
                    this.mapCon3=-1;
                }

                

               

                this.mapsMaxX+=2
                this.maps[this.ij].position.x=this.mapsMaxX;
                this.maps[this.ij].position.y=(Math.random()*2.4*this.mapCon2+2)+this.mapCon;
                this.maps2[this.ij].position.x=this.mapsMaxX;
                this.maps2[this.ij].position.y=(Math.random()*2.2*this.mapCon2-14+this.mapCon3)+this.mapCon;
                this.maps3[this.ij].position.x=this.mapsMaxX;
                this.maps3[this.ij].position.z=50;
                this.maps3[this.ij].position.y=(Math.random()*1.6*this.mapCon2-17+this.mapCon3)+this.mapCon;
    
                console.log( "this.ij")
                console.log( this.ij)
    
                if(this.ij==1){
                   if(this.mapStateCatch<=6){
                    this.mapStateCatch++
                   }else{
                    this.mapStateCatch=0
                   } 
                }

               // if(this.lostMapStateCatch!=this.mapStateCatch)
    
                if(this.ij==1){
                     if(this.mapStateCatch!=6){
                        this.targetCon(this.mapsMaxX,this.maps[this.ij].position)
                        console.log("chuangjian")
                        console.log( this.maps[this.ij].position.y-8)
                    }
                }
    
                if(this.ij==1){
                    if(this.mapStateCatch==6){
                        this.maps9.position.x=this.mapsMaxX;
                        this.maps9.position.y= this.maps[this.ij].position.y-8;
                    }
                }
    
                this.ij++
                if(this.ij>=(this.maps.length-1)){
                    this.ij=0;
                }

                this.lostMapStateCatch=this.mapStateCatch
                
            }
    }


    private checkPoint(type){
       
        if(type==1){
            this.mapCon3=0
            if(this.mapCon<=0.5&&this.mapCon>=-0.5){
                this.mapCon=0
                this.slopeState=null;
            }else if(this.mapCon<0){
                this.mapCon+=0.3;
                this.slopeState="up"
            }else if(this.mapCon>0){
                this.mapCon-=0.3;
                this.slopeState="down"
            }
        }else if(type==2){
            this.mapCon3=0
            if(this.mapCon<-10){
                this.mapConState=false;
            }
            if(this.mapCon>10){
                this.mapConState=true;
            }

            if(this.mapConState==true){
                this.mapCon-=0.3
                this.slopeState="down"
            }else{
                this.mapCon+=0.3
                this.slopeState="up"
            }
        }else if(type==3){
            if(this.mapCon<=0.5&&this.mapCon>=-0.5){
                this.mapCon=0
            }else if(this.mapCon<0){
                this.mapCon+=0.3;
                this.slopeState="up"
            }else if(this.mapCon>0){
                this.mapCon-=0.3;
                this.slopeState="down"
            }
           
            if(this.mapCon==0){
                this.slopeState=null;
                this.mapCon3=1.5;
                this.mapCon2=0;
            }
        }
    }

    private colorState=0;

    private targetState=4;

    //设置靶子位置
    private targetCon(mapsMaxX,position):void{
      //  let _s=this.getRandom(4, 7);
      this["maps4"].position.y=-1000;
      this["maps5"].position.y=-1000;
      this["maps6"].position.y=-1000;
      this["maps7"].position.y=-1000;
        if(this.targetState<=7){
            this.targetState++
            this["maps"+this.targetState].position.x=mapsMaxX;
         //   this["maps"+this.targetState].position.y= position.y-8;
            if(this.targetState==8){
                this["maps"+this.targetState].position.y= position.y-4+this.mapCon3;
            }else{
                this["maps"+this.targetState].position.y= position.y-8+this.mapCon3;
            }

            console.log("maps"+this.targetState)
        }else{
            this.targetState=4
            this["maps"+this.targetState].position.x=mapsMaxX;
            this["maps"+this.targetState].position.y= position.y-9+this.mapCon3;
            
        }
        if(this.slopeState=="up"){
            this["maps"+this.targetState].rotation.x=-Math.PI*0.1
        }else if(this.slopeState=="down"){
            this["maps"+this.targetState].rotation.x=Math.PI*0.1
        }else{
            this["maps"+this.targetState].rotation.x=0
        }
    }

    //获取随机数
    private getRandom(min, max){
        var r = Math.random() * (max - min);
        var re = Math.round(r + min);
        re = Math.max(Math.min(re, max), min)
        return re;
    }


    private resurgenceState=1;

    //原地复活
    private doResurgence(){
        GDispatcher.dispatchEvent("enableMouseEvt",false);
        this.touchState=0;
        this.playerBox.isVisible=true;
        this.tube.isVisible=true;
        this.isVisible=true;
        this.engineMatter.world.gravity.y=100
       // this.removeEvent();
        this.World.remove(this.engineMatter.world, [this.constraint]);
        this.addEvent();
        console.log("doResurgence")
        if(this.resurgenceState==0){
            return false
        }
        this.sceneEventState=0;
        this.resurgenceState=0
        this.beforeReady=true;
        this.gameBefore=0;
        this.playerState=1;
        console.log(45444)
        this.constraint = this.Matter.Constraint.create({
            pointA: { x: this.constraintBox.position.x, y: this.constraintBox.position.y },
            bodyB: this.player,
            pointB: { x: 0, y: 0 },
            length:3
        });

        setTimeout(()=>{
            this.engineMatter.world.gravity.y=-0.01;
            GDispatcher.dispatchEvent("enableMouseEvt",true);
            this.touchState=0;
        },500)
        console.log("this.constraint")
        console.log(this.constraint)

        this.World.add(this.engineMatter.world, [this.constraint]);
        setTimeout(()=>{
            this.isPause=false;
            this.display.camera3.target=new BABYLON.Vector3(this.constraintBox.position.x,this.constraintBox.position.y-4,this.constraintBox.position.z) ;
            this.display.skySphere.position=new BABYLON.Vector3(this.constraintBox.position.x,this.constraintBox.position.y-4,this.constraintBox.position.z) ;
        },100)
        setTimeout(()=>{
            this.resurgenceState=1
        },1000)
    }

    //更新主题颜色
    private setColor(state?:number){
        var tween1 = new TWEEN.Tween(  this.display.map1Material.diffuseColor);
        var tween2 = new TWEEN.Tween(  this.display.map2Material.diffuseColor);
        var tween3 = new TWEEN.Tween(  YtSceneManager.ins.scene.fogColor);

        var colors=[
           /*  {
                map1:{r:134,g:2,b:207},
                map2:{r:92,g:26,b:178},
                fog:{r:223,g:116,b:245},
            },
            {
                map1:{r:21,g:179,b:69},
                map2:{r:4,g:206,b:96},
                fog:{r:38,g:83,b:46},
            },
            {
                map1:{r:184,g:23,b:77},
                map2:{r:202,g:6,b:30},
                fog:{r:244,g:123,b:115},
            },
            {
                map1:{r:172,g:91,b:25},
                map2:{r:205,g:127,b:3},
                fog:{r:243,g:218,b:117},
            },
            {
                map1:{r:5,g:100,b:255},
                map2:{r:33,g:150,b:243},
                fog:{r:115,g:141,b:245},
            } */

            {
                map1:{r:134,g:2,b:207},
                map2:{r:92,g:26,b:178},
                fog:{r:82,g:20,b:129},
            },
            {
                map1:{r:21,g:179,b:69},
                map2:{r:4,g:206,b:96},
                fog:{r:38,g:83,b:46},
            },
            {
                map1:{r:160,g:3,b:24},
                map2:{r:246,g:0,b:157},
                fog:{r:50,g:27,b:28},
            },
            {
                map1:{r:172,g:91,b:25},
                map2:{r:205,g:127,b:3},
                fog:{r:120,g:73,b:15},
            },
            {
                map1:{r:5,g:100,b:255},
                map2:{r:33,g:150,b:243},
                fog:{r:13,g:13,b:61},
            }
        ]
       
        if(!state){
            tween1.to({r:colors[0].map1.r/255,g:colors[0].map1.g/255,b:colors[0].map1.b/255}, 1000);
            tween1.start();

            tween2.to({r:colors[0].map2.r/255,g:colors[0].map2.g/255,b:colors[0].map2.b/255}, 1000);
            tween2.start();

            tween3.to({r:colors[0].fog.r/255,g:colors[0].fog.g/255,b:colors[0].fog.b/255}, 1000);
            tween3.start();
        }else{
            tween1.to({r:colors[state].map1.r/255,g:colors[state].map1.g/255,b:colors[state].map1.b/255}, 1000);
            tween1.start();

            tween2.to({r:colors[state].map2.r/255,g:colors[state].map2.g/255,b:colors[state].map2.b/255}, 1000);
            tween2.start();

            tween3.to({r:colors[state].fog.r/255,g:colors[state].fog.g/255,b:colors[state].fog.b/255}, 1000);
            tween3.start();
        }

    }

    //玩家死亡
    protected died(){
        GDispatcher.dispatchEvent("enableMouseEvt",false);
        //this.resurgenceState=0
        this.removeEvent()
        this.beforeReady=true;
        this.gameBefore=0;
      
        UseParticlee.ins.startBoom(this.playerBox)
        if(this.tube){
            this.tube.dispose()
        }
        setTimeout(()=>{
            UseParticlee.ins.stopBoom()
        },500)
      //  this.playerState=1;
        NetManager.ins.getCredits(()=>{ // 获取用户剩余积分
            NetManager.ins.getPrizeInfo(()=>{
                console.log(DataManager.ins.getPrizeInfoList)
                let unitName = DataManager.ins.getCreditsData.unitName ? DataManager.ins.getCreditsData.unitName : '积分'
                let userCredits = DataManager.ins.getCreditsData.consumerCredits ? DataManager.ins.getCreditsData.consumerCredits : 0;
                let costCredits = DataManager.ins.getPrizeInfoList[""+window["activityId"]+""].creditsPrice ? DataManager.ins.getPrizeInfoList[""+window["activityId"]+""].creditsPrice : 0;
                if(costCredits>userCredits){
                  //  this.gameOver()
                  this.maps4.position.y=-100;

                  if(this.constraint&&this.player){
                      this.World.remove(this.engineMatter.world, [this.constraint,this.player]);
                  }
                
                  this.Matter.World.clear(this.engineMatter.world);
                  this.Matter.Engine.clear(this.engineMatter);
                    setTimeout(()=>{
                        this.clearScene()
                        GDispatcher.dispatchEvent("gameOver");
                    },500)
                }else{
                    this.isVisible=false;
                    this.playerBox.isVisible=false;
                    this.tube.isVisible=false;
                    setTimeout(()=>{
                        if(localStorage.resurgence=="false"){
                            
                          //  ModuleManager.ins.openModule("GameResurrection");
                           
                        }else{
                            this.maps4.position.y=-100;

                            if(this.constraint&&this.player){
                                this.World.remove(this.engineMatter.world, [this.constraint,this.player]);
                            }
                          
                            this.Matter.World.clear(this.engineMatter.world);
                            this.Matter.Engine.clear(this.engineMatter);
                            this.clearScene()
                            GDispatcher.dispatchEvent("gameOver");
                        }
                    },500)
                }
            },window["activityId"])
        })

      
    }


    //清除场景不可复用的元素

    private clearScene(){
        if(this.tube){
            this.tube.dispose()
        }
        if(this.playerBox){
            this.playerBox.dispose()
        }
        if(this.constraintBox){
            this.constraintBox.dispose()
        }
       // UseParticlee.ins.stop()
    }

     /** * 求两点距离 */ 
     public getDistance(x1: number, y1: number, z1: number, x2: number, y2: number,z2: number) 
     {   var _x: number = Math.abs(x1 - x2); 
         var _y: number = Math.abs(y1 - y2); 
         var _z: number = Math.abs(z1 - z2); 
         return Math.sqrt(_x * _x + _y * _y+ _z * _z); 
     }
}
