import Scene from "../views/Scene";
import PanelCtrl from "../ctrls/panelCtrl";
import { ModuleTypes } from "../types/sceneTypes";
import SceneCtrl from "../ctrls/sceneCtrl";
import { NetManager } from "../../libs/tw/manager/NetManager";
import { DataManager } from "../../libs/tw/manager/DataManager";
import Loading from "../loading/Loading";
import ItemCell1 from "./ItemCell1";
import { GDispatcher } from "../../libs/tc/util/GDispatcher";
import { playSound } from "../ctrls/soundCtrl";
import { NetName } from "../../libs/tw/enum/NetName";
import TopLayerCtrl from "../ctrls/topLayerCtrl";
import { GCache } from "../../libs/tc/util/GCache";
import { Buried } from "../../libs/tw/util/Buried";
import NumGroup from "./NumGroup";

export default class GameScene extends Scene {
    private mainbg:eui.Image;
    private timeDownNum: number;
    private gameTickNum: number;
    private gTickStart: boolean;
    private timer: egret.Timer;
    private isSuccess: boolean;
    public soundBtn:eui.Group;

    public arrowImg:eui.Image;
    public handImg:eui.Image;
    public moneyGroup:eui.Group;
    public guideGroup:eui.Group;

    public moneyActGroup:eui.Group;
    public mainGroup:eui.Group;
    public timeGroup:eui.Group;
    public catActGroup:eui.Group;
    public actGroup:eui.Group;
    public tipsGroup:eui.Group;
    public tipImg0:eui.Group;
    public tipImg1:eui.Group;

    public tipsLb:eui.Label;


    public timeDownLb:eui.Label;

    public numGroupC0:eui.Group;
    public numGroupC1:eui.Group;
    public numGroupC2:eui.Group;
    public numGroupC3:eui.Group;

    private catAct0:SVGA.EgretMovieClip;
    private catAct1:SVGA.EgretMovieClip;
    private upStrag:SVGA.EgretMovieClip;
    private diaoluo0:SVGA.EgretMovieClip;
    private diaoluo1:SVGA.EgretMovieClip;
    private timeDownSvg:SVGA.EgretMovieClip;

    private numGroup0:NumGroup;
    private numGroup1:NumGroup;
    private numGroup2:NumGroup;
    private scoreNum:number;
    private moveTime:number;
    public get skinKey() { return 'GameScene' }
    public get groupName() { return 'game_scene' }

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

    initEvents() {
        super.initEvents();
        this.soundBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_soundBtn, this);
        this.timer.addEventListener(egret.TimerEvent.TIMER, this.ontimer, this);
    }

    removeEvents() {
        super.removeEvents();
        // this.soundBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_soundBtn, this);
        this.guideGroup.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_guideGroup, this);
        this.removeEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onBegin, this);
        this.removeEventListener(egret.TouchEvent.TOUCH_END, this.onEnd, this);
        this.timer.removeEventListener(egret.TimerEvent.TIMER, this.ontimer, this);
        this.timer.stop();//停止倒计时

        egret.Tween.removeTweens(this.handImg);
        if(this.arrawShap){
            egret.Tween.removeTweens(this.arrawShap);
        }
        egret.Tween.removeTweens(this);

    }

    protected onSkinComplete(): void {
        super.onSkinComplete();

        this.mainbg.texture = this.bgtexture;

        this.guideGroup.alpha = 0;
        this.guideGroup.visible = true;

        this.moneyGroup.y = 1624;
        this.handImg.scaleX = 0;
        this.handImg.scaleY = 0;

        this.scoreNum = 0;
        this.moveTime = 0;
        
        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');
        console.log('载背景并设置背景图片mainscene');

        this.catAct0 = await PanelCtrl.instance.getSvga('resource/assets/svga/game/catAct0.svga') as SVGA.EgretMovieClip;
        this.catAct1 = await PanelCtrl.instance.getSvga('resource/assets/svga/game/catAct1.svga') as SVGA.EgretMovieClip;
        this.upStrag = await PanelCtrl.instance.getSvga('resource/assets/svga/game/upStrag.svga') as SVGA.EgretMovieClip;
        await PanelCtrl.instance.getSvga('resource/assets/svga/game/diaoluo0.svga') as SVGA.EgretMovieClip;
        await PanelCtrl.instance.getSvga('resource/assets/svga/game/diaoluo1.svga') as SVGA.EgretMovieClip;
        await PanelCtrl.instance.getSvga('resource/assets/svga/game/getMoneyAct.svga') as SVGA.EgretMovieClip;
        this.timeDownSvg = await PanelCtrl.instance.getSvga('resource/assets/svga/game/timeDownSvg.svga') as SVGA.EgretMovieClip;

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

    start(data?) {
        super.start(data);
        this.timer = new egret.Timer(1000);
        this.percentHeight = 100;
        // this.timeDownNum = window['tickTips'] ? window['tickTips'] : 5;
    }

    private onLoad(): void {
        for(let i = 1; i < 4; i++){
            this['numLb' + i].visible = false;
        }

        this.initNum();

        let bdata1 = DataManager.ins.getData(NetName.BASE_INFO);
        if(bdata1 && bdata1.data){
            this.timeDownNum = bdata1.data.countDownSeconds;
            this.tipsLb.text = '游戏时间' + bdata1.data.countDownSeconds + 's，向上滑动钱币，倒计时开始';
        }else{
            this.timeDownNum = 30;
            this.tipsLb.text = '游戏时间' + 30 + 's，向上滑动钱币，倒计时开始';
        }

        this.showAct();
        this.initUI();
    }

    private arrawShap:egret.Shape;
    private arrawIdx:number;
    private maxScore:number;
    private initUI(): void {
        let bdata1 = DataManager.ins.getData(NetName.BASE_INFO);
        if(bdata1 && bdata1.data){
            this.maxScore = bdata1.data.maxScore;
        }

        this.tipsGroup.visible = false;
        if(window['isOpenMusic'] == undefined || window['isOpenMusic'] == null || window['isOpenMusic'] == false){
            this['mImg0'].visible = false;
            this['mImg1'].visible = true;
        }else{
            this['mImg0'].visible = true;
            this['mImg1'].visible = false;
        }

        this.catActGroup.addChild(this.catAct0);
        this.timeGroup.addChild(this.catAct1);
        this.catAct0.x = 260;
        this.catAct0.y = 178;

        this.catAct1.x = 40;
        this.catAct1.y = 273;

        GCache.init([window['appid'] + '', Buried.oaId + '', DataManager.ins.getData(NetName.GET_PROJECT_USER_INFO).data.consumerId + '']);


        const isPrize = GCache.readCache('isGuide');
        if(!isPrize){
            GCache.writeCache('isGuide', 'true');
            this.showGuideAct();
        }else{
            this.startGame();
        }

        this.timeDownLb.textFlow = [
            { text: this.timeDownNum + '', style:{textColor:0xd4381b} },
            { text: 's', style:{textColor:0xb73d13} }
        ];
        console.log(this.soundBtn)

    }

    private initNum():void{

        this.numGroup0 = new NumGroup('shiwei');
        this.numGroupC1.addChild(this.numGroup0);
        this.numGroup1 = new NumGroup('baiwei', 'shiwei');
        this.numGroupC2.addChild(this.numGroup1);
        this.numGroup2 = new NumGroup('qianwei', 'baiwei');
        this.numGroupC3.addChild(this.numGroup2);

        for(let i = 0; i < 3; i++){
            var maskShap = new egret.Shape();
            maskShap.graphics.beginFill(0xe6844e, 1);
            maskShap.graphics.drawRect(0, 0, 61, 79);
            maskShap.graphics.endFill();
            maskShap.x = this["numGroupC" + (i + 1)].x;
            maskShap.y = this["numGroupC" + (i + 1)].y;
            this["numGroupC" + (i + 1)].mask = maskShap;
    
            this.timeGroup.addChild(maskShap);

        }
    }

    private showGuideAct():void{

        this.arrawIdx = setTimeout(() => {

            var maskShap = new egret.Shape();
            maskShap.x = 304;
            // maskShap.y = 520;
            maskShap.y = 761;
            maskShap.graphics.beginFill(0xe6844e, 1);
            maskShap.graphics.drawRect(0, 0, 142, 241);
            maskShap.graphics.endFill();
            this.mainGroup.addChild(maskShap);
            this.arrawShap = maskShap;

            this.arrowImg.mask = maskShap;

            egret.Tween.get(this.guideGroup).to({alpha:1}, 500).call(()=>{
                this.guideGroup.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_guideGroup, this);
                //箭头动画
                egret.Tween.get(maskShap, {loop:true}).wait(170).to({y:520}, 500).wait(330).call(()=>{
                    maskShap.y = 761;
                });

                //手指动画
                egret.Tween.get(this.handImg, {loop:true}).to({scaleX:1.1, scaleY:1.1}, 100)
                .to({scaleX:1, scaleY:1}, 70).wait(830);
                egret.Tween.get(this.handImg, {loop:true}).wait(170).to({y:533}, 500).to({alpha:0},160).wait(170).call(()=>{
                    this.handImg.y = 739;
                    this.handImg.alpha = 1;

                    this.handImg.scaleX = 0;
                    this.handImg.scaleY = 0;
                });



            });
        }, 800);
    }

    private onTap_guideGroup():void{
        PanelCtrl.instance.btnDelay(this.guideGroup);
        this.guideGroup.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_guideGroup, this);
        egret.Tween.removeTweens(this.handImg);
        if(this.arrawIdx){
            clearTimeout(this.arrawIdx);
        }
        if(this.arrawShap){
            egret.Tween.removeTweens(this.arrawShap);
        }
        egret.Tween.get(this.guideGroup).to({alpha:0}, 200).call(()=>{
            this.guideGroup.visible = false;

            this.startGame();
        })
    }

    //开始游戏入口
    private startGame():void{
        egret.Tween.get(this.moneyGroup).to({y:1144}, 230).to({y:950}, 100).call(()=>{
            this.mainGroup.addChild(this.timeDownSvg);
            this.timeDownSvg.x = 133;
            this.timeDownSvg.y = 290;
            this.timeDownSvg.startAniRange(0, this.timeDownSvg.totalFrames, 1, ()=>{
                egret.Tween.get(this.moneyGroup).to({y:399}, 230).to({y:420}, 100).call(()=>{
                    this.upStrag.x = 330;
                    this.upStrag.y = 339;
                    this.mainGroup.addChild(this.upStrag);

                    this.bgAct();
                    
                    this.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onBegin, this);
                    this.addEventListener(egret.TouchEvent.TOUCH_END, this.onEnd, this);
                });
            });
            
        })
    }

    private mouseY:number;
    private onBegin(e:egret.TouchEvent):void{
        this.mouseY = e.stageY;
    }

    private isfirstShow:boolean;
    private onEnd(e:egret.TouchEvent):void{
        if(this.mouseY - e.stageY > 50){//向上
            this.numGroup0.pushNum();

            // this.bgAct();
            this.moneyAct();
            this.scoreNum += 10;
            this.moveTime += 1;
            this.setScore(this.scoreNum);
            if(window['isOpenMusic']){
                playSound('startBtnSound')
            }

            if(this.maxScore < this.scoreNum && !this.isfirstShow){
                this.isfirstShow = true;
                let bdata1 = DataManager.ins.getData(NetName.BASE_INFO);
                if(bdata1 && bdata1.data){
                    bdata1.data.maxScore = this.scoreNum;
                    this.maxScore = this.scoreNum;
                }

                this.tipsGroup.visible = true;
                this.tipImg0.visible = true;
                this.tipImg1.visible = false;
                this.tipImg0.alpha = 0;
                egret.Tween.get(this.tipImg0).to({alpha:1}, 300).wait(500).to({alpha:1}, 300).call(()=>{
                    this.tipsGroup.visible = false;
                });
            }else{
                if(Math.random() < 0.1){

                    this.tipsGroup.visible = true;
                    this.tipImg0.visible = false;
                    this.tipImg1.visible = true;
                    this.tipImg1.alpha = 0;

                    egret.Tween.get(this.tipImg1).to({alpha:1}, 300).wait(500).to({alpha:1}, 300).call(()=>{
                        this.tipsGroup.visible = false;
                    });
                }
            }
        }else{
            // console.log(6666666);
        }
    }

    private setScore(val:number):void{
        console.log(">>>>>>>>",val)
        let str = val + '';
        str = str.split("").reverse().join("")
        console.log(str)
        
        for(let i = 0; i < str.length; i++){
            this['numLb'+i].text = str[i];
            console.log('numLb=' + i+'=', str[i])

        }
    }

    private iscanMove:boolean;
    private async moneyAct(){
        let getMoneyAct = await PanelCtrl.instance.getSvga('resource/assets/svga/game/getMoneyAct.svga') as SVGA.EgretMovieClip;
        getMoneyAct.x = 10;
        getMoneyAct.startAniRange(0, getMoneyAct.totalFrames, 1, ()=>{
            this.moneyActGroup.removeChild(getMoneyAct);
        });
        this.moneyActGroup.addChild(getMoneyAct);
    }

    private isfirsBgAct:boolean;
    private bgAct():void{
        if(this.isfirsBgAct) return;
        this.isfirsBgAct = true;

        egret.Tween.get(this, {loop:true}).wait(1330).call(async ()=>{
            let diaoluo = await PanelCtrl.instance.getSvga('resource/assets/svga/game/diaoluo0.svga') as SVGA.EgretMovieClip;
            this.actGroup.addChild(diaoluo);
            diaoluo.startAniRange(0, diaoluo.totalFrames, 1, ()=>{
                this.actGroup.removeChild(diaoluo);
                diaoluo = null;
            });
        });

        egret.Tween.get(this, {loop:true}).wait(500).call(async ()=>{
            let diaoluo1 = await PanelCtrl.instance.getSvga('resource/assets/svga/game/diaoluo1.svga') as SVGA.EgretMovieClip;
            this.actGroup.addChild(diaoluo1);
            diaoluo1.startAniRange(0, diaoluo1.totalFrames, 1, ()=>{
                this.actGroup.removeChild(diaoluo1);
                diaoluo1 = null;
            });
        });

        this.timer.start();
    }

    private onTap_soundBtn(){
        console.log(window['isOpenMusic'])
        if(window['isOpenMusic'] == undefined || window['isOpenMusic'] == null || window['isOpenMusic'] == false){
            window['isOpenMusic'] = true;
            this['mImg0'].visible = true;
            this['mImg1'].visible = false;
        }else{
            window['isOpenMusic'] = false;
            this['mImg0'].visible = false;
            this['mImg1'].visible = true;
        }

    }

    private ontimer(): void {
        //预览图片倒计时
        if (this.timeDownNum > 0) {
            this.timeDownNum--;

            this.timeDownLb.textFlow = [
                { text: this.timeDownNum + '', style:{textColor:0xd4381b} },
                { text: 's', style:{textColor:0xb73d13} }
            ];
            
            if (!this.timeDownNum) {
                this.touchEnabled = false;
                this.touchChildren = false;
                this.timer.stop();
                // egret.Tween.removeTweens(this.numGroup0);
                // egret.Tween.removeTweens(this.numGroup1);
                // egret.Tween.removeTweens(this.numGroup2);
                // egret.Tween.removeAllTweens();
                
            //     clearInterval(this.numGroup0.interverIdx)
            //     clearInterval(this.numGroup1.interverIdx)
            //     clearInterval(this.numGroup2.interverIdx)
            //     this['numLb3'].text = Math.floor(this.scoreNum/1000)
            // this['numLb2'].text = Math.floor((this.scoreNum-this['numLb3']*1000)/100)
            // this['numLb1'].text = Math.floor((this.scoreNum-this.scoreNum-this['numLb3']*1000-this.scoreNum-this['numLb2']*100)/10)

                let data = DataManager.ins.getData(NetName.FREE_START);
                if(data && data.data){
                    let free = data.data.free;
                    let startId = '';
                    let token = '';
                    if(free){
                        startId = data.data.startId;
                        token = data.data.token;
                    }else{
                        let data = DataManager.ins.getData(NetName.CREDITS_START);
                        if(data && data.data){
                            startId = data.data.startId;
                            token = data.data.token;
                        }
                    }
                   

                    if(startId){
                        console.log(this.scoreNum);
                        NetManager.ins.submit((isSuccess)=>{
                            // Loading.instace.loadbg.visible = true;
                            if(isSuccess){//597,61
                                let bdata1 = DataManager.ins.getData(NetName.BASE_INFO);
                                let btype;
                                if(bdata1 && bdata1.data){
                                    bdata1.data.participationTimes = bdata1.data.participationTimes - 1;
                                    if(bdata1.data.participationTimes < 1){
                                        btype = 0;
                                    }else{
                                        btype = 1;
                                    }
                                }
                                //出奖
                                let data = DataManager.ins.getData(NetName.SUBMIT);
                                if(data && data.data && data.data.prize){
                                    PanelCtrl.instance.show(ModuleTypes.PRIZE_PANEL, {type:btype});
                                }else{

                                    PanelCtrl.instance.show(ModuleTypes.GAMEOVER_PANEL, {type:btype});
                                }
                            }else{
                                //游戏提交失败
                                TopLayerCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'网络异常，请稍后再试~'});
                                setTimeout(() => {
                                    SceneCtrl.instance.change(ModuleTypes.START_SCENE);
                                }, 300);
                            }
                        },token, this.scoreNum + '', startId, this.moveTime);
                    }else{
                        //为什么没有数据
                        console.log('为什么没有数据')
                    }
                }else{
                    //为什么没有数据
                    console.log('为什么没有数据')
                }
            }
        }

    }


    //打乱数组顺序
    private shuffleArray(array) {
        for (var i = array.length - 1; i > 0; i--) {
            var j = Math.floor(Math.random() * (i + 1));
            var temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
        return array;
    }
}