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';
import { LotteryType } from './../../libs/tw/enum/LotteryType';

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 timeLab:eui.Label;
    public itemGroup:eui.Group;
    public timeGroup:eui.Group;
    public gameGroup:eui.Group;
    public effGroup:eui.Group;

    public bagCount:eui.Label;

    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;
    private gameTime:any;//持续时间
    public bar:eui.ProgressBar;
    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);
    }

    removeEvents() {
        super.removeEvents();

        this.removeEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
        this.removeEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onTap_this, 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();
        }
    }

    protected async preLoadRes() {
        //加载背景并设置背景图片
   

        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{

        this.bgHight        = 1800;
        this.goldPosArr     = [{x:0, y:-60}, {x:30, y:-100}, {x:50, y:-50}];
        this.gameTime = DataManager.ins.getData('getInformation').data.gameTime / 1000;
    }

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

        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'] : 10;
        this.scoreCount     = 0;
        this.lastSystemTime = 0;

        this.bagCount.text = this.scoreCount.toString();
        this.gameGroup.visible = false;
        this.timeGroup.visible = true;
       


        this.bar.value = 1*100;

        this.numImg.source = '2Img_png';

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

        //倒计时
        this.tickCount = this.gameTime;
        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.timeLab.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.timeLab.visible = true;
                    this.timeLab.text = this.tickCount + "S";
                }, 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 --;
            this.bar.value = (this.tickCount/this.gameTime)*100;
        }
        if(this.tickCount < 0){
        
            //游戏结束
            this.removeEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
            if(this.scoreCount > 0){
                this.submit();
            }else{
                this.unPrizePopup();
            }
            egret.Tween.removeTweens(this.timeBgActImg);
        }else{
            this.timeLab.text = this.tickCount + 'S';
            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 < 15){
            this.createFlower();
        }
        this.falling();
    }

    private createFlower():void{
        let orgY = 0;
        if(!this.flowerArr){
            this.flowerArr = [];
        }
        const contH     = 350;
        const rowCount  = window['rowCount'];
        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() * 4) + 2;
            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;
                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'); 
        if(this.tickCount <= 0)
        {
            return;
        }
        //PanelCtrl.instance.btnDelay(this);

        let gitem:eui.Group = e.target;
        if(gitem.name != ''){
            this.scoreCount ++;
            this.bagCount.text = this.scoreCount.toString();
            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;

            //在移动数组中删除
            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;

                });
            });
        }
    }
    private submit():void{

        NetManager.ins.getInformation((success,resultInformation) => {
            if(success)
            {
                NetManager.ins.gameSumbit((success,result) => {
                    console.log("提交成绩",success,result);
                    if(success && result && result.data && result.data.prizeId != 'thanks')
                    {
                        PanelCtrl.instance.show(ModuleTypes.PRIZE_PANEL, {data : result.data});
                    }
                    else if(result.data && result.data.prizeId == 'thanks')
                    {
                        this.unPrizePopup();
                    }
                    else
                    {
                        PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'活动太过火爆，请稍后重试'});
                        SceneCtrl.instance.change(ModuleTypes.START_SCENE);
                    }
                },resultInformation.data.timestamp,this.scoreCount,resultInformation.data.cid)
            }
            else
            {
                PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'活动太过火爆，请稍后重试'});
                SceneCtrl.instance.change(ModuleTypes.START_SCENE);
            }
        });
    }
    private unPrizePopup(){
        let idata = DataManager.ins.getData('getInformation').data;
        if(idata.canShare){
            PanelCtrl.instance.show(ModuleTypes.GAMEOVER_PANEL,  {type:1});
        }else{
            PanelCtrl.instance.show(ModuleTypes.GAMEOVER_PANEL,  {type:2});
        }
    }
    //循环播放动画
    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();
    }
}