import { DataManager } from './../../libs/tw/manager/DataManager';

import prePlayScene from "./prePlayScene";
import PlaySceneBase from "../../libs/new_wx/components/PlaySceneBase";
import PanelCtrl from "../../libs/new_wx/ctrls/panelCtrl";
import { ModuleTypes } from "../../libs/new_wx/types/sceneTypes";
import { NetManager } from "../../libs/tw/manager/NetManager";


const { TouchEvent } = egret;
export default class PlayScene extends PlaySceneBase{
    public get skinKey() { return 'Play' }

    public touchPlane:eui.Rect;
    public scoreTxt:eui.Label;
    public scoreTip:eui.Image;

    public BABYLON:any = window['BABYLON'];
    public rocketP:any;
    public rocketLine:any;
    public score:number = 0; // 分数
    private touchDown:boolean; // 是否点击屏幕
    private createCount:number = 0; // 生成云的计数

    constructor(){
        super()
        
        this.restart();
    }

    restart(){
        prePlayScene.instance.disposeAll();
        prePlayScene.instance.startTimestamp = Date.now();
        prePlayScene.instance.rocketP.position.set(0,30,0);
        prePlayScene.instance.cloudRange = 30;
        prePlayScene.instance.initCloudPool(prePlayScene.instance.cloudTemplate);
        this.addEventListener(egret.Event.ENTER_FRAME,this.onEnterFrame,this);
    }

    private onEnterFrame(){
        this.createCount++;
        if(this.createCount%500 == 0){
            // 生成新的 会动的云
            for(let i = 0; i < 5; i++){
                let nCloud = prePlayScene.instance.cloudTemplate.clone(`cloud_${i}`);
                let randomNum = Math.random();
                let newScale = Math.max(0.01*randomNum, 0.005)
                nCloud.scaling.set(0, 0, 0);
                let nCloudTW = egret.Tween.get(nCloud.scaling);
                nCloudTW.to({x:newScale,y:newScale,z:newScale}, 500).wait(1000).call(()=>{
                    let nnCloudTW = egret.Tween.get(nCloud.position,{onChange:()=>{
                        let distance = this.BABYLON.Vector3.Distance(new this.BABYLON.Vector3(0,0,0),prePlayScene.instance.rocketP.position);
                        if(distance<10){
                            prePlayScene.instance.removeEle(nCloud, prePlayScene.instance.cloudPool)
                            nCloud.dispose();
                        }
                    }});
                    nnCloudTW.to({x:0,y:0,z:0}, 15000).call(()=>{
                        prePlayScene.instance.removeEle(nCloud, prePlayScene.instance.cloudPool)
                        nCloud.dispose();

                    })
                });
                let newAngle = Math.random()*360;
                let newRadius = Math.max(Math.random() * prePlayScene.instance.cloudRange, 10);
                nCloud.position.set(newRadius*Math.cos(newAngle),newRadius*Math.sin(newAngle),0);
                nCloud.lookAt(new this.BABYLON.Vector3(0,0,0));
                nCloud.rotate(new this.BABYLON.Vector3(1,0,0),Math.PI/2);
                nCloud.visibility = 1;
                prePlayScene.instance.cloudPool.push(nCloud);
            }
            // 生成新的不会动的云
            for(let i = 0; i < 5; i++){
                let nCloud = prePlayScene.instance.cloudTemplate.clone(`cloud_${i}`);
                let randomNum = Math.random();
                let newScale = Math.max(0.01*randomNum, 0.005)
                nCloud.scaling.set(0, 0, 0);
                let nCloudTW = egret.Tween.get(nCloud.scaling);
                nCloudTW.to({x:newScale,y:newScale,z:newScale}, 500);
                let newAngle = Math.random()*360;
                let newRadius = Math.max(Math.random() * prePlayScene.instance.cloudRange, 10);
                nCloud.position.set(newRadius*Math.cos(newAngle),newRadius*Math.sin(newAngle),0);
                nCloud.lookAt(new this.BABYLON.Vector3(0,0,0));
                nCloud.rotate(new this.BABYLON.Vector3(1,0,0),Math.PI/2);
                nCloud.visibility = 1;
                prePlayScene.instance.cloudPool.push(nCloud);
            }
            // 生成不允许碰撞的云
            for(let i = 0; i < 5; i++){
                let nCloud = prePlayScene.instance.cloudTemplate.clone(`blackCloud_${i}`);
                let randomNum = Math.random();
                let newScale = Math.max(0.01*randomNum, 0.005)
                nCloud.scaling.set(0, 0, 0);
                let nCloudTW = egret.Tween.get(nCloud.scaling);
                nCloudTW.to({x:newScale,y:newScale,z:newScale}, 500).wait(5000).to({x:0,y:0,z:0},500).call(()=>{
                    prePlayScene.instance.removeEle(nCloud, prePlayScene.instance.cloudPool)
                    nCloud.dispose();
                });
                let newAngle = Math.random()*360;
                let newRadius = Math.max(Math.random() * prePlayScene.instance.cloudRange, 10);
                nCloud.position.set(newRadius*Math.cos(newAngle),newRadius*Math.sin(newAngle),0);
                nCloud.lookAt(new this.BABYLON.Vector3(0,0,0));
                nCloud.rotate(new this.BABYLON.Vector3(1,0,0),Math.PI/2);
                nCloud.visibility = 1;
                let blackMaterial = new this.BABYLON.StandardMaterial('blackMaterial', prePlayScene.instance.scene);
                blackMaterial.diffuseColor = new this.BABYLON.Color3(0,0,0); 
                nCloud.material = blackMaterial;
                nCloud.gameType = 'blackCloud';
                prePlayScene.instance.cloudPool.push(nCloud);
            }
        }
        
        if(prePlayScene.instance.planet){
            prePlayScene.instance.planet.rotation.y += 0.01;
        }

        if(prePlayScene.instance.realRocket){
            let distance = prePlayScene.instance.BABYLON.Vector3.Distance(new this.BABYLON.Vector3(0,0,0),prePlayScene.instance.rocketP.position);
            if(distance < 5){
                this.gameOver();
            }else{
                prePlayScene.instance.scene.render();
                if(distance > prePlayScene.instance.cloudRange){
                    prePlayScene.instance.cloudRange = distance + 20;
                }
                prePlayScene.instance.bg.rotate(new this.BABYLON.Vector3(0,0,1), -0.001)
                // 自转
                prePlayScene.instance.realRocket.rotation.y -= 0.1;
                // 向原点加速移动
                for(let cloud of prePlayScene.instance.cloudPool){
                    prePlayScene.instance.moveByVector3(cloud,cloud.position.subtract(new this.BABYLON.Vector3(0,0,0)).normalize(),0.005)
                    if (cloud.intersectsMesh(prePlayScene.instance.realRocket, true)) {
                        if(cloud.gameType == 'blackCloud'){
                            // 撞到了黑云 游戏结束
                            this.gameOver();
                        }else{
                            // 如果碰到了就让速度反向
                            prePlayScene.instance.downSpeed = -0.03;
                            prePlayScene.instance.startTimestamp = Date.now()
                            this.updateScore(1);
                            prePlayScene.instance.removeEle(cloud, prePlayScene.instance.cloudPool)
                            cloud.dispose()
                        }
                    }else{
                        
                    }
                }
                prePlayScene.instance.accelerateByVector3(prePlayScene.instance.rocketP, new this.BABYLON.Vector3(0,0,0).subtract(prePlayScene.instance.rocketP.position), prePlayScene.instance.downSpeed, prePlayScene.instance.downAddSpeed)
                
                // 是否触控发生
                if(this.touchDown){
                    prePlayScene.instance.rotateSpeed = 0.5;
                }else{
                    prePlayScene.instance.rotateSpeed = 0.05;
                }

                // 沿切线移动
                let tangent = new this.BABYLON.Vector3.Cross(new this.BABYLON.Vector3(0,0,0).subtract(prePlayScene.instance.rocketP.position),new this.BABYLON.Vector3(0,0,1)).normalize();
                prePlayScene.instance.moveByVector3(prePlayScene.instance.rocketP, tangent, prePlayScene.instance.rotateSpeed);
                const newForward = prePlayScene.instance.lastPosition.subtract(prePlayScene.instance.rocketP.position).normalize();

                if(newForward !== this.BABYLON.Vector3(0,0,0)){
                    prePlayScene.instance.rocket.lookAt(newForward)
                    prePlayScene.instance.lastPosition = prePlayScene.instance.rocketP.position.clone();
                }

                // 删除连线
                if(prePlayScene.instance.rocketLine){
                    prePlayScene.instance.rocketLine.dispose();
                }
                // 画连线
                let path = [
                    prePlayScene.instance.rocketP.position,
                    new this.BABYLON.Vector3(0,0,0)
                ];
                prePlayScene.instance.rocketLine = this.BABYLON.MeshBuilder.CreateTube("tube", {path: path, radius: 0.1}, prePlayScene.instance.scene);
            }
        }
    }


    gameOver(){
        this.removeEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
        this.gameSubmitData(this.gameSubmitResult.bind(this), this.score);
    }

    // 提交成绩的回调
    private gameSubmitResult(success){
        
        if(!success){
            return;
        }
        let data = {score:this.score}
        if(DataManager.ins.gameGetSubmitResultData && DataManager.ins.gameGetSubmitResultData.lottery){
            PanelCtrl.instance.show(ModuleTypes.PRIZE_PANEL,data);
        }else{
            PanelCtrl.instance.show(ModuleTypes.NOPRIZE_PANEL,data);
            // SceneCtrl.instance.change(ModuleTypes.NOPRIZE_PANEL, data);
        }
    }

    /**
     * 提交游戏成绩
     * @param callback 
     * @param score 得分
     * @param allDynamics 防作弊数据
     * @param checkScore  是否校验得分
     * @param customizedType 定制类型 1推币机    
     */
    protected gameSubmitData(callback: Function, score: number, checkScore?: boolean, customizedType?: number): void {
        NetManager.ins.gameSubmit(
            (success: boolean) => { 
                if(success) {
                    this.getSubmitResult(callback, DataManager.ins.gameSubmitData.orderId); 
                } else {
                    callback(success);
                }
            },
            DataManager.ins.doStartData.ticketId,
            score,
            '[]',
            DataManager.ins.doStartData.submitToken,
            '',
            checkScore,
            customizedType);
    }
    
    /**
     * 查询提交结果
     * @param callback 
     * @param orderId 
     */
    private getSubmitResult(callback: Function, orderId: number): void {
        NetManager.ins.getSubmitResult(callback, orderId, () => {
            return DataManager.ins.gameGetSubmitResultData.flag;
        });
    }

    initEvents() {
        this.touchPlane.addEventListener( egret.TouchEvent.TOUCH_BEGIN, this.onTouchBegin_touchPlane, this);
        this.touchPlane.addEventListener( egret.TouchEvent.TOUCH_END, this.onTouchOut_touchPlane, this);
        this.touchPlane.addEventListener( egret.TouchEvent.TOUCH_CANCEL, this.onTouchOut_touchPlane, this);
        this.touchPlane.addEventListener( egret.TouchEvent.TOUCH_RELEASE_OUTSIDE, this.onTouchOut_touchPlane, this);
    }

    removeEvents() {
        this.touchPlane.removeEventListener( egret.TouchEvent.TOUCH_BEGIN, this.onTouchBegin_touchPlane, this);
        this.touchPlane.removeEventListener( egret.TouchEvent.TOUCH_END, this.onTouchOut_touchPlane, this);
        this.touchPlane.removeEventListener( egret.TouchEvent.TOUCH_CANCEL, this.onTouchOut_touchPlane, this);
        this.touchPlane.removeEventListener( egret.TouchEvent.TOUCH_RELEASE_OUTSIDE, this.onTouchOut_touchPlane, this);
    }

    private onTouchBegin_touchPlane(e:egret.TouchEvent){
        this.touchDown = true;
    }

    private onTouchOut_touchPlane(e:egret.TouchEvent){
        this.touchDown = false;
    }

    // 更新分数
    private updateScore(score?:number){
        let _score = 1;
        if(score){
            _score = score;
        }
        this.scoreTip.y = this.stage.stageHeight/2;
        this.scoreTip.scaleX = 0;
        this.scoreTip.scaleY = 0;
        this.scoreTip.alpha = 1;
        this.scoreTip.source = `+${_score}_png`;
        let scoreTw = egret.Tween.get(this.scoreTip);
        scoreTw.to({scaleX:1,scaleY:1},200).to({y:this.stage.stageHeight/2 - 100,alpha:0},100);
        this.score += _score;
        this.scoreTxt.text = `${this.score}`;
    }

}