import { NetManager } from './../../libs/tw/manager/NetManager';
import Scene from "../views/Scene";
import PanelCtrl from "../ctrls/panelCtrl";
import { DataManager } from "../../libs/tw/manager/DataManager";
import Loading from "../loading/Loading";
import MyImage from './MyImage';
import { ModuleTypes } from '../types/sceneTypes';
import SceneCtrl from '../ctrls/sceneCtrl';
import { Buried } from '../../libs/tw/util/Buried';
import { GCache } from '../../libs/tc/util/GCache';
import { GTime } from '../../libs/tc/util/GTime';
import { GDispatcher } from '../../libs/tc/util/GDispatcher';

export default class GameScene extends Scene {

    public bgImg:eui.Image;
    public goImg:eui.Image;
    public numImg:eui.Image;
    public timeBgActImg:eui.Image;

    public scoreNumLb:eui.Label;
    public timeNumLb:eui.Label;
    public itemGroup:eui.Group;
    public timeGroup:eui.Group;
    public gameGroup:eui.Group;
    public effGroup:eui.Group;

    private tick:number;
    private isStop:number;
    private bgHight:number;
    private addSpeed:number;
    private moveSpeed:number;
    private score:number;
    private tickCount:number;
    private scoreCount:number;//获得红包数量
    private goldPosArr:any[];
    private itemSizeArr:any[];
    private flowerArr:eui.Group[];
    private flowerCache:eui.Group[];
    private lastSystemTime:number;

    private mcJson:any;
    private mcImg:any;

    public get skinKey() { return 'GameScene' }
    public get groupName() { return 'game_scene' }

    constructor(data?) {
        super(data);
    }

    initEvents() {
        super.initEvents();
        this.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onTap_this, this);
        GDispatcher.addEvent('restart', this.resetGame, this);
    }

    removeEvents() {
        super.removeEvents();

        this.removeEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
        this.removeEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onTap_this, this);

        GDispatcher.removeEvent('restart', this.resetGame, this);
        egret.Tween.removeTweens(this.timeBgActImg);
    }

    protected onSkinComplete(): void {
        super.onSkinComplete();
        
        this.once(egret.Event.ADDED_TO_STAGE, this.onLoad, this);
        if (this.stage) {
            this.onLoad();
        }
    }

    private bgtexture: egret.Texture;
    protected async preLoadRes() {
        //加载背景并设置背景图片
        this.bgtexture = await RES.getResAsync('gameBg_jpg');

        this.mcJson = await RES.getResAsync('goldEff_json');
        this.mcImg = await RES.getResAsync('goldEff_png');

        return new Promise(function (resolve, reject) {
            resolve();
        });
    }

    start(data?) {
        super.start(data);
        this.percentHeight = 100;

    }

    private onLoad(): void {
        this.initData();
        this.initUI();
    }

    private initData():void{

        const isfirst = GCache.readCache('showGuide');
        if (!isfirst) {
            GCache.writeCache('showGuide', 'true');
        }else{
            // this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
        }

        this.bgHight        = 1800;
        this.goldPosArr     = [{x:0, y:-60}, {x:30, y:-100}, {x:50, y:-50}];
    }

    private initUI(): void {
        this.resetGame();
    }

    private resetGame():void{

        let startDpmOut = Buried.connectDpm(110, 14, 1); // 点击埋点
        let startDcmOut = Buried.connectDcm(202, 0, 0); // 曝光埋点
        let exposure = Buried.createExposure(startDpmOut, startDcmOut);

        NetManager.ins.showLog(exposure);

        if(this.flowerArr){
            for(let i = 0; i < this.flowerArr.length; i++){
                let item = this.flowerArr[i];

                if(item.parent){
                    item.parent.removeChild(item);
                }

                if(this.flowerCache){
                    this.flowerCache.push(item);

                }
            }

        }
        this.flowerArr = [];

        this.isStop         = 1;
        this.tick           = 0;
        this.score          = 0;
        this.addSpeed       = window['addSpeed'] ? window['addSpeed'] : 0;
        this.moveSpeed      = window['moveSpeed'] ? window['moveSpeed'] : 5;
        this.scoreCount     = 0;
        this.lastSystemTime = 0;

        this.gameGroup.visible = false;
        this.timeGroup.visible = true;

        this.numImg.source = '2Img_png';

        this.numImg.scaleX = 0.3;
        this.numImg.scaleY = 0.3;

        //倒计时
        this.tickCount = window['tick'] ? window['tick'] : 10;

        this.timeBgActImg.rotation = 0;

        egret.Tween.get(this.timeBgActImg, {loop:true}).to({rotation:-360}, 2000);
        this.tickAct();
    }
    
    private tickAct():void{
        this.goImg.visible = true;
        this.timeNumLb.visible = false;

        let tick = 3;
        this.numImg.scaleX = 0.3;
        this.numImg.scaleY = 0.3;

        egret.Tween.get(this.numImg).to({scaleX:1.2, scaleY:1.2}, 300).to({scaleX:1, scaleY:1}, 200);
        egret.Tween.get(this.timeGroup, {loop:true}).wait(1000).call(function(){
            tick --;

            if(tick == 0){
                
                this.gameGroup.visible = true;
                this.timeGroup.visible = false;

                egret.Tween.removeTweens(this.timeGroup);

                setTimeout(() => {
                    this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);

                    this.goImg.visible = false;
                    this.timeNumLb.visible = true;
                    this.timeNumLb.text = this.tickCount;
                }, 1000);
            }else{
                this.numImg.source = (tick - 1) + 'Img_png';

                this.numImg.scaleX = 0.3;
                this.numImg.scaleY = 0.3;
        
                egret.Tween.get(this.numImg).to({scaleX:1.2, scaleY:1.2}, 300).to({scaleX:1, scaleY:1}, 200);
            }
        }, this);
    }

    private secondTick:number = 0;
    private onEnterFrame(){
        
        var useTime;
        if (this.lastSystemTime) {
            useTime = GTime.getTimestamp() - this.lastSystemTime;
        } else {
            useTime = 1000 / 60;
        }

        this.lastSystemTime = GTime.getTimestamp();

        //本次消耗的时间 / 正常每帧应该消耗的时间 算出倍率
        var times = useTime / (1000 / 60);
        //速度 * 倍率 = 本次应该移动的距离

        if(this.secondTick > 60){
            this.secondTick = 0;
            this.tickCount --;
        }

        if(this.tickCount < 0){
            let idata = DataManager.ins.getInformationZhaohangData.data;
            //游戏结束
            this.removeEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);

            if(PanelCtrl.instance.isLoseCoin){
                
                if(idata.ifCanAddJoinTimesByShare){
                    this.score = 1;//指示界面是否显示分享按钮
                    PanelCtrl.instance.show(ModuleTypes.GAMEOVER_PANEL,  {score:this.score, type:1});
                }else{
                    this.score = 2;//指示界面是否显示分享按钮
                    PanelCtrl.instance.show(ModuleTypes.GAMEOVER_PANEL,  {score:this.score, type:1});
                }
            }else{
                if(this.scoreCount > 0){
    
                    if(idata.ifCanAddJoinTimesByShare){
                        this.score = 1;
                    }else{
                        if(idata.joinTimesDetail){
                            let type = idata.joinTimesDetail[0].type;
                            if(type == '1'){//中奖分享获得次数
                                this.score = 2;
                            }else{//未中奖分享获得次数
                                this.score = 1;
                            }
                        }
                    }
        
                    this.submit();
                }else{
                    if(idata.ifCanAddJoinTimesByShare){
                        this.score = 1;//指示界面是否显示分享按钮
                        PanelCtrl.instance.show(ModuleTypes.GAMEOVER_PANEL,  {score:this.score, type:1});
                    }else{
                        this.score = 2;//指示界面是否显示分享按钮
                        PanelCtrl.instance.show(ModuleTypes.GAMEOVER_PANEL,  {score:this.score, type:1});
                    }
                }

            }

            egret.Tween.removeTweens(this.timeBgActImg);
        }else{
            this.timeNumLb.text = this.tickCount + '';
            this.secondTick += times;

        }

        if (this.tick > 19) {
            this.moveSpeed = Math.min(this.moveSpeed + this.addSpeed * this.tick / 19, 30);
            this.tick = 0;
        }

        this.moveSpeed *= this.isStop;

        this.tick += times;
        if(!this.flowerArr || this.flowerArr.length < 10){
            this.createFlower();
        }
        
        this.falling();
    }

    private createFlower():void{
        let orgY = 0;
        if(!this.flowerArr){
            this.flowerArr = [];
        }
        
        const contH     = 350;
        const rowCount  = 15;
        const orgX      = 30;

        if(this.flowerArr && this.flowerArr.length > 1){
            orgY = this.flowerArr[this.flowerArr.length - 1].y - contH;
        }

        for(let j = 0; j < rowCount; j++){
            const colCount  = Math.floor(Math.random() * 3) + 1;
            const contW     = Math.floor(690 / colCount);

            for(let i = 0; i < colCount; i++){
                if(!this.flowerCache){
                    this.flowerCache = [];
                }

                var img:eui.Image;
                var iGroup:eui.Group;
                if(this.flowerCache.length > 0){
                    iGroup = this.flowerCache.pop();
                }else{
                    iGroup = new eui.Group();
                    iGroup.width = 90;
                    iGroup.height = 106;
                    img = new MyImage();
                    img.name = 'img';
                    iGroup.addChild(img);
                    img.source  = 'icon_png';

                    img.touchEnabled = false;
                }

                let dir = Math.random() > 0.5 ? 1 : -1;
                // iGroup.rotation = dir * Math.floor(25 * Math.random());
                let rot = 20;
                egret.Tween.get(iGroup, {loop:true})
                .to({rotation:dir * rot}, 1000)
                .to({rotation:dir * 0}, 1000)
                .to({rotation:dir * -rot}, 1000)
                .to({rotation:dir * 0}, 1000);
                
                this.flowerArr.push(iGroup);
                iGroup.name = '' + (this.flowerArr.length - 1);


                let iW = 90;
                let iH = 106;


                iGroup.anchorOffsetX = 45;
                iGroup.anchorOffsetY = 53;


                iGroup.x = orgX + i * contW + (contW - iW) * Math.random() + iW * 0.5;
                iGroup.y = orgY - (j * contH + (contH - iH) * Math.random()) + iH * 0.5;
            }

        }

        console.log(this.flowerArr);
    }

    private falling():void{
        var len: number = this.flowerArr.length;
        for (var i = len - 1; i >= 0; i--) {
            let img = this.flowerArr[i];
            //如果下一次移动y坐标为正数责添加到舞台
            if (img.y + this.moveSpeed > 0) {
                this.itemGroup.addChild(img);
            }
            img.y += this.moveSpeed;

            //超出舞台或者跟人物发生碰撞
            if (img.y >= this.parent.height + 100) {
                this.itemGroup.removeChild(img);
                this.flowerArr.splice(i, 1);
                img.y = 0;
                // img.clean();
                len -= 1;
                // i -= 1;

                if(!this.flowerCache){
                    this.flowerCache = [];
                }

                this.flowerCache.push(img);
            }

            
        }
    }


    private onBegin_this():void{
        
    }

    private onTap_this(e:egret.TouchEvent):void{
        console.log('点击talkBtn'); 
        PanelCtrl.instance.btnDelay(this);

        // let startDpmOut = Buried.connectDpm(110, 14, 1); // 点击埋点
        // let startDcmOut = Buried.connectDcm(202, 0, 0); // 曝光埋点
        // let exposure = Buried.createExposure(startDpmOut, startDcmOut);

        // NetManager.ins.clickLog(exposure);

        let gitem:eui.Group = e.target;
        if(gitem.name != ''){
            this.scoreCount ++;
            console.log('gname=' + gitem.name);

            var effImg:eui.Image = new eui.Image();
            effImg.source = 'lightImg_png';
            effImg.x = 45;
            effImg.y = 53;

            effImg.anchorOffsetX = 129;
            effImg.anchorOffsetY = 132;

            gitem.addChildAt(effImg, 0);

            gitem.touchEnabled = false;
            gitem.touchChildren = false;

            // //金币洒出
            // for(let i = 0; i < 3; i++){
            //     var img:eui.Image = new eui.Image();
            //     gitem.addChild(img);
            //     img.source = 'goldImg_png';
            //     img.x = 28;
            //     img.y = 36;

            //     egret.Tween.get(img).to({x:this.goldPosArr[i].x, y:this.goldPosArr[i].y}, 300);
            // }


            //在移动数组中删除
            let idx = this.flowerArr.indexOf(gitem);
            this.flowerArr.splice(idx, 1);

            egret.Tween.removeTweens(gitem);
            egret.Tween.get(gitem).to({scaleX:1.5, scaleY:1.5}, 300);

            //背景光效
            egret.Tween.get(effImg).to({rotation:30}, 300).call(() => {
                let iconImg = gitem.getChildByName('img');
                gitem.removeChildAt(1);

                var mcFactory = new egret.MovieClipDataFactory(this.mcJson, this.mcImg);
                var mc:egret.MovieClip = new egret.MovieClip(mcFactory.generateMovieClipData());
                mc.anchorOffsetX = 150;
                mc.anchorOffsetY = 150;
                mc.x = gitem.x;
                mc.y = gitem.y;

                this.effGroup.addChild(mc);
                mc.play();
                egret.Tween.get(effImg).to({rotation:39, alpha: 0}, 100);
                egret.Tween.get(effImg).wait(790).call(() => {
                    gitem.removeChildAt(0);
                    gitem.addChild(iconImg);
                    gitem.scaleX = 1;
                    gitem.scaleY = 1;
                    gitem.rotation = 0;
                    //在显示对象中删除
                    gitem.parent.removeChild(gitem);
                    //添加到缓存数组中
                    this.flowerCache.push(gitem);

                    this.effGroup.removeChild(mc);

                    gitem.touchEnabled = true;
                    gitem.touchChildren = true;

                });


                

                // //清空红包group
                // let iconImg = gitem.getChildByName('img');
                // gitem.removeChildAt(1);
                // let len = gitem.numChildren;
                // for(let i = 0; i < len; i++){
                    // gitem.removeChildAt(1);
                // }
                
                // gitem.addChild(iconImg);



                
            });
            

        }

        
    }

    private submit():void{
        NetManager.ins.getNgameSubmit((success) => {
            if(!success){
                
                PanelCtrl.instance.show(ModuleTypes.GAMEOVER_PANEL, {score:this.score, type:1});
                return;
            }
            console.log('测试轮询')
            NetManager.ins.getOrderStatusNew((data) => {
                if (data == 'pollingFaild' || !data) {
                    console.log('轮询失败：' + data);
                    Loading.instace.hide();
                    
                    PanelCtrl.instance.show(ModuleTypes.GAMEOVER_PANEL, {score:this.score, type:1});
                }else{//出奖
                    Loading.instace.hide();
                    //弹出奖品框待处理
                    if(!DataManager.ins.getCustomOrderStatusData.lottery){    
                        
                        PanelCtrl.instance.show(ModuleTypes.GAMEOVER_PANEL, {score:this.score, type:1});
                    }else{ 
                        PanelCtrl.instance.show(ModuleTypes.PRIZE_PANEL, {score:this.score});
                    }
                }

            }, DataManager.ins.doJoinData.orderId, () => {
                return !(DataManager.ins.getCustomOrderStatusData.code == '0000000000');
            })
        }, DataManager.ins.doJoinData.orderId, this.score, '[]', DataManager.ins.getNgameStartStatusData.data.submitToken, '');
    }

    

    //循环播放动画
    private playAnimation(target: egret.tween.TweenGroup, isLoop: boolean = true): void {
        if (isLoop) {
            for (var key in target.items) {
                target.items[key].props = { loop: true };
            }
        }
        target.play();
    }
}