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";

export default class GameScene extends Scene {
    public enterNextPanel: eui.Group;
    public startActGroup: eui.Label;
    public timeBar: eui.ProgressBar;
    public enterNextTxt: eui.Label;
    public levelTxtImg: eui.Image;
    public gTimeDownLb: eui.Label;
    public startText0: eui.Image;
    public startText1: eui.Image;
    public timeDownLb: eui.Label;
    // public selectImg:eui.Image;
    public endTimeLb: eui.Label;
    public scanGroup: eui.Group;
    public gameGroup: eui.Group;
    public timeTips: eui.Label;
    public skipBtn: eui.Button;
    public ruleBtn: eui.Button;
    public cellsImg: eui.Image;
    public thumbImg: eui.Image;
    public actGroup: eui.Group;
    public moveImg: eui.Image;
    public imgsCon: eui.Group;
    public scanMask: eui.Rect;
    public actMask: eui.Rect;
    public sImgBg: eui.Image;
    public mainbg: eui.Image;
    public sImg: eui.Image;

    private enterNextTimeDown: number;
    private maskActImg: egret.Bitmap;
    private currCellPos: egret.Point;
    private currCell: egret.Bitmap;
    private movePoint: egret.Point;
    private square: egret.Shape
    private pics: egret.Bitmap[];
    private timeDownNum: number;
    private gameTickNum: number;
    private gTickStart: boolean;
    private timer: egret.Timer;
    private isSuccess: boolean;
    private imgCount1: number;
    private currLevel: number;
    private currTouchId: any;
    private imgCount2: number;
    private texture: any;


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

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

    initEvents() {
        super.initEvents();
        // document.addEventListener('touchcancel', function(){
        //     console.log('touchcancel');
        //     this.onUp_cellImg(null);
        // }.bind(this));
        this.skipBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_skipBtn, this);
        this.ruleBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_ruleBtn, this);
        // this.selectImg.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_selectImg, this);
        this.addEventListener(egret.TouchEvent.TOUCH_MOVE, this.onMove_imgsCon, this);
        // this.addEventListener(egret.TouchEvent.TOUCH_END, this.onUp, this);
        this.timer.addEventListener(egret.TimerEvent.TIMER, this.ontimer, this);
        // this.addEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
        // this.stage.addEventListener(egret.TouchEvent.TOUCH_RELEASE_OUTSIDE, function(){
        //     this.onUp_cellImg(null);
        //     console.log('stage出界TOUCH_RELEASE_OUTSIDE');
        // }, this);

        // this.stage.addEventListener(egret.TouchEvent.TOUCH_CANCEL, function(){
        //     console.log('stage出界TOUCH_CANCEL');
        // }, this);
    }

    removeEvents() {
        super.removeEvents();
        this.removeEvents_cell();
        this.skipBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_skipBtn, this);
        this.ruleBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_ruleBtn, this);
        // this.selectImg.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_selectImg, this);
        this.removeEventListener(egret.TouchEvent.TOUCH_MOVE, this.onMove_imgsCon, this);
        // this.removeEventListener(egret.TouchEvent.TOUCH_END, this.onUp, this);
        this.timer.removeEventListener(egret.TimerEvent.TIMER, this.ontimer, this);
        // this.removeEventListener(egret.Event.ENTER_FRAME, this.onEnterFrame, this);
        this.timer.stop();//停止倒计时

    }

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

        this.mainbg.texture = this.bgtexture;

        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');
        return new Promise(function (resolve, reject) {
            resolve();
        });
    }

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

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

    private initUI(): void {
        this.timeTips.textFlow = [
            { text: '你有' },
            { text: this.timeDownNum + '', style: { 'size': 35 } },
            { text: '秒时间查看原图' }
        ];

        //设置接入下一关panel锚点
        var aX: number = this.actGroup.width * 0.5;
        var aY: number = this.actGroup.height * 0.5;

        this.actGroup.anchorOffsetX = aX;
        this.actGroup.anchorOffsetY = aY;

        this.actGroup.x += aX;
        this.actGroup.y += aY;

        // this.selectImg.visible      = false;
        this.cellsImg.touchEnabled = false;

        //第一关
        this.currLevel = 0;
        this.setScanGroup(0, 3, 3);

    }

    private onClick_skipBtn(): void {
        console.log('跳过查看图片');
        this.timeDownLb.text = '0';
        this.timeDownNum = 0;
        this.startGameAct();
    }

    private onClick_ruleBtn(): void {
        console.log('点击游戏规则按钮');
        this.timer.stop();
        PanelCtrl.instance.show(ModuleTypes.RULE_PANEL, { callback: this.ruleCallBack.bind(this) });
    }

    private ruleCallBack(): void {
        this.timer.start();
    }

    //设置预览动画
    private setScanGroup(level: number, len1: number, len2: number) {
        this.currLevel++;

        this.resetScanUI(level);
        this.resetGameImg(len1, len2, level);

        //初始化倒计时和预览图片
        this.moveImg.texture = this.texture;

        egret.Tween.get(this.levelTxtImg).to({ alpha: 1 }, 400).wait(200).to({ alpha: 0 }, 200).call(function () {
            this.scanMask.visible = false;
            egret.Tween.get(this.timeTips).to({ alpha: 1 }, 200).call(function () {

                this.timeDownLb.visible = true;
                this.skipBtn.visible = true;

                this.timeDownNum = window['tickTips'] ? window['tickTips'] : 5;
                this.timeDownLb.text = this.timeDownNum + '';

                this.timer.start();
            }.bind(this));
        }.bind(this));
    }

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

            this.timeDownLb.text = this.timeDownNum + '';

            if (!this.timeDownNum) {
                this.startGameAct();
            }
        }

        //5s后进入下一关
        if (this.enterNextTimeDown > 0) {
            this.enterNextTimeDown--;

            this.enterNextTxt.textFlow = [
                { text: this.enterNextTimeDown + '', style: { "textColor": 0xf8550d } },
                { text: '秒后进入最终回合' }
            ];

            if (!this.enterNextTimeDown) {
                egret.Tween.get(this.actGroup).to({ scaleX: 0, scaleY: 0 }, 200).call(function () {
                    this.startNextLevel();
                    this.enterNextPanel.visible = false;
                }.bind(this));
            }
        }

        if (this.gTickStart) {
            if (this.gameTickNum > 0) {
                this.gameTickNum--;
                this.refreshGameTickLb();

                if (!this.gameTickNum) {//倒计时结束，如果没拼成功弹出失败框
                    this.gTickStart = false;

                    if (!this.isSuccess) {
                        console.log('时间到拼图失败！');

                        this.showMsg('againBtn',
                            [
                                { text: "啊哦！\n离获胜还有一步之遥~" }
                            ],
                            this.againBtnCallBack, this.againBtnCallBack);

                        // NetManager.ins.gameSubmit(function () { },
                        //     DataManager.ins.doStartData.ticketId,
                        //     0, '[]', DataManager.ins.doStartData.submitToken, ""
                        // );
                    }
                }
            }
        }
    }

    //进入下一关
    private async startNextLevel() {
        Loading.instace.show();
        this.texture = await RES.getResAsync('ptImg' + Math.floor(Math.random() * 9) + '_jpg');
        Loading.instace.hide();
        this.setScanGroup(1, 4, 4);
    }

    //倒计时后的动画
    private startGameAct(): void {
        this.imgsCon.visible = true;
        const scale = 134 / 666;
        //移动预览图片到右下角
        egret.Tween.get(this.moveImg).to({ scaleX: scale, scaleY: scale, x: 587, y: 1061 }, 800, egret.Ease.sineOut).call(function () {
            this.sImg.texture = this.texture;
            this.sImg.visible = true;
            this.sImgBg.visible = true;
            this.scanGroup.visible = false;
            this.gameGroup.visible = true;
            this.startActGroup.visible = true;
            //图片"开始"动效
            egret.Tween.get(this.startText0).to({ scaleX: 1, scaleY: 1, alpha: 1 }, 300, egret.Ease.sineOut).call(function () {
                this.startText1.alpha = 1;
                // egret.Tween.get(this.startText0).to({alpha:0}, 500, egret.Ease.sineOut);
                egret.Tween.get(this.startText1).to({ scaleX: 3, scaleY: 3, alpha: 0 }, 500, egret.Ease.sineOut).call(function () {
                    this.gTickStart = true;//游戏倒计时开始
                    this.ruleBtn.visible = true;
                    this.startText0.visible = false;
                    this.startText1.visible = false;
                    this.gameGroup.touchEnabled = false;
                    this.startActGroup.visible = false;

                    //5秒后右下角小图消失
                    egret.Tween.get(this.startText1).to({ alpha: 1 }, 5000).call(function () {
                        this.sImg.visible = false;
                        this.sImgBg.visible = false;
                    }, this);
                }.bind(this));
            }.bind(this));

        }.bind(this));
    }

    //切图，并打乱
    private resetGameImg(len1: number, len2: number, level: number): void {
        this.imgCount1 = len1;
        this.imgCount2 = len2;

        // this.selectImg.texture  = RES.getRes('selectRect' + level + '_png');
        this.cellsImg.texture = RES.getRes('line' + level + '_png');

        // const aX = this.cellsImg.width * 0.5;
        // const aY = this.cellsImg.width * 0.5;

        // this.cellsImg.anchorOffsetX = aX;
        // this.cellsImg.anchorOffsetY = aY;

        // this.cellsImg.x = 25 + aX;
        // this.cellsImg.y = 296 + aY;

        this.imgsCon.removeChildren();
        this.removeEvents_cell();

        this.pics = [];
        var i: number;
        var j: number;
        // var len1: number = len1;
        // var len2: number = len2;
        var pw: number = Math.floor(666 / len1);
        var ph: number = Math.floor(666 / len2);
        var bigPic: egret.Bitmap = new egret.Bitmap(this.texture);
        for (i = 0; i < len1; i++) {
            for (j = 0; j < len2; j++) {
                var renderTexture: egret.RenderTexture = new egret.RenderTexture();
                var px: number = pw * j;
                var py: number = ph * i;
                renderTexture.drawToTexture(bigPic, new egret.Rectangle(px, py, pw, ph), 1);

                var cellImg: egret.Bitmap = new egret.Bitmap(renderTexture);

                this.pics.push(cellImg);
                cellImg.name = (j + i * len2) + '';

                cellImg.touchEnabled = true;

                cellImg.addEventListener(egret.TouchEvent.TOUCH_RELEASE_OUTSIDE, this.onUp_cellImg, this);
                cellImg.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onUp_cellImg, this);
                cellImg.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onDown_cellImg, this);
            }
        }

        this.pics = this.shuffleArray(this.pics);

        for (i = 0; i < len1; i++) {
            for (j = 0; j < len2; j++) {
                var idx: number = j + i * len2;
                var img: egret.Bitmap = this.pics[idx];

                this.imgsCon.addChildAt(img, 0);
                img.x = pw * j;
                img.y = ph * i;

            }
        }

        this.imgsCon.addChild(this.cellsImg);
        this.imgsCon.setChildIndex(this.cellsImg, this.imgsCon.numChildren);
        // this.imgsCon.addChild(this.selectImg);

    }

    private againBtnCallBack(): void {
        //获取游戏信息
        Loading.instace.show();
        NetManager.ins.getInfo((success: boolean) => {
            // if (success) {
            //     SceneCtrl.instance.change(ModuleTypes.MAIN_SCENE);
            // } else {
            //     //提示用户，返回上一层，重新进入活动？？？？？
            //     this.showMsg('iknowBtn',
            //         [
            //             { text: "网络开小差了\n世界上最遥远的距离莫过于此" }
            //         ]);
            // }
            SceneCtrl.instance.change(ModuleTypes.MAIN_SCENE);
            Loading.instace.hide();
        });
    }
    //this up 监听
    // private onUp(e:egret.TouchEvent):void{
    //     if(!e.target.name){

    //         console.log('tEnd,this');
    //     }
    // }

    //imgsCon move事件
    private onMove_imgsCon(e: egret.TouchEvent): void {
        var ex: number = e.stageX;
        var ey: number = e.stageY;

        if (!this.movePoint) {
            this.movePoint = new egret.Point();
        }

        this.movePoint.x = ex - (this.imgsCon.x - this.imgsCon.width * 0.5);
        this.movePoint.y = ey - (this.imgsCon.y - this.imgsCon.height * 0.5);

        if (this.currCell) {
            this.currCell.x = this.movePoint.x - this.currCell.width * 0.5;
            this.currCell.y = this.movePoint.y - this.currCell.height * 0.5;

            if (e.stageY < 0) {
                console.log('越界了');
                this.currCell.touchEnabled = false;
                this.onUp_cellImg(null);
            }
        }
        // console.log('this.movePoint.x' + this.movePoint.x);
        // console.log('this.movePoint.y' + this.movePoint.y);
        // console.log('e.stageY' + e.stageY);
        // console.log('e.stageX' + e.stageX);
    }
    private onEnterFrame(e: egret.Event): void {
        // if(this.currCell){
        //     var gX:number = this.currCell.y + (this.imgsCon.y - this.imgsCon.height * 0.5) + this.currCell.height * 0.5;
        //     if(gX < 0){

        //     }
        // }
    }

    //cell 手指按下
    private onDown_cellImg(e: egret.TouchEvent): void {
        console.log('TID1=' + e.touchPointID);
        if (!this.currTouchId) {
            this.currTouchId = e.touchPointID;
        }

        if (this.currTouchId != e.touchPointID) {
            return;
        }
        console.log('downname=' + e.target.name);
        this.pics.forEach(element => {
            if (element.name != e.target.name) {
                if (element.touchEnabled) {
                    element.touchEnabled = false;
                }
            }
        });

        this.currCell = e.target;
        this.imgsCon.setChildIndex(this.currCell, this.imgsCon.numChildren);

        if (!this.currCellPos) {
            this.currCellPos = new egret.Point();
        }

        this.currCellPos.x = this.currCell.x;
        this.currCellPos.y = this.currCell.y;
    }

    //cell 手指抬起
    private onUp_cellImg(e: egret.TouchEvent): void {
        if (e) {
            console.log('TID2=' + e.touchPointID);
        }
        this.currTouchId = null;
        if (!this.currCell) {
            console.log('按下时，没有选中可移动元素');
            return;
        }

        this.pics.forEach(element => {
            element.touchEnabled = false;
        });

        var moveCell;
        var targetCell = this.changeCell();

        if (targetCell) {
            this.currCell.x = targetCell.x;
            this.currCell.y = targetCell.y;

            moveCell = targetCell;
            this.imgsCon.setChildIndex(moveCell, this.imgsCon.numChildren);

            //交换数据
            var idx0: number = this.pics.indexOf(this.currCell);
            var idx1: number = this.pics.indexOf(targetCell);

            this.pics[idx0] = targetCell;
            this.pics[idx1] = this.currCell;
        } else {
            moveCell = this.currCell;
        }

        const ax: number = moveCell.x - this.currCellPos.x;
        const ay: number = moveCell.y - this.currCellPos.y;
        const mTime: number = Math.sqrt(ax * ax + ay * ay) * 0.4;

        egret.Tween.get(moveCell).to({ x: this.currCellPos.x, y: this.currCellPos.y }, mTime, egret.Ease.sineIn).call(function () {
            // this.currCell.touchEnabled = true;
            if (this.pics) {
                for (let i = 0; i < this.pics.length; i++) {
                    // if(!this.pics[i].touchEnabled){
                    this.pics[i].touchEnabled = true;
                    //     break;
                    // }
                }
            }
            this.imgsCon.setChildIndex(this.cellsImg, this.imgsCon.numChildren);
        }, this);
        console.log('mTime=' + mTime);

        this.currCell = null;

        // if(this.currCell == e.target){//第二次点击取消选中
        //     this.selectImg.visible = false;
        //     return;
        // }
        // if(!this.currCell){
        //     this.currCell           = e.target;
        //     var img:egret.Bitmap    = this.currCell;
        //     this.selectImg.x        = img.x + (img.width - this.selectImg.width) * 0.5;
        //     this.selectImg.y        = img.y + (img.height - this.selectImg.height) * 0.5;
        //     this.selectImg.visible  = true;
        // }else{
        //     var cell:any    = e.target;
        //     var idx0:number = this.pics.indexOf(this.currCell);
        //     var idx1:number = this.pics.indexOf(cell);

        //     var p:egret.Point = new egret.Point();

        //     p.x             = this.currCell.x;
        //     p.y             = this.currCell.y;
        //     this.currCell.x = cell.x;
        //     this.currCell.y = cell.y;
        //     cell.x          = p.x;
        //     cell.y          = p.y;

        //     this.pics[idx0] = e.target;
        //     this.pics[idx1] = this.currCell;

        //     // this.selectImg.visible  = false;
        //     this.currCell           = null;

        //     if(this.isSuccessComplete()){
        //         console.log('拼图成功');
        //         //成功后的动效
        //         this.showSuccessAct();
        //         //停止倒计时
        //         this.gTickStart = false;
        //         this.isSuccess  = true;
        //     }

        // }

        if (this.isSuccessComplete()) {
            console.log('拼图成功');
            //成功后的动效
            this.showSuccessAct();
            //停止倒计时
            this.gTickStart = false;
            this.isSuccess = true;
        }
    }

    //获取当前移动位置下的图片元素
    private changeCell(): egret.Bitmap {
        var cell = null;
        for (var i = 0; i < this.pics.length; i++) {
            var element = this.pics[i];
            if (element && this.movePoint) {
                if (this.movePoint.x > element.x &&
                    this.movePoint.x < (element.x + element.width) &&
                    this.movePoint.y > element.y &&
                    this.movePoint.y < (element.y + element.height) &&
                    this.currCell.name != element.name) {
                    // console.log('element', element);//这句话会导致,钉钉崩溃
                    cell = element;
                    break;
                }
            }

        }

        return cell;
    }

    private showSuccessAct(): void {
        //成功后的放大图片动效
        // egret.Tween.get(this.cellsImg).to({scaleX:1.055, scaleY:1.055}, 500);
        egret.Tween.get(this.imgsCon).to({ scaleX: 1.055, scaleY: 1.055 }, 500).call(function () {
            //光效
            if (!this.maskActImg) {
                this.square = new egret.Shape();
                this.square.graphics.beginFill(0xff0000);
                this.square.graphics.drawRect(0, 0, this.imgsCon.width, this.imgsCon.height);
                this.square.graphics.endFill();
                this.square.x = 0;
                this.square.y = 0;

                this.maskActImg = new egret.Bitmap(RES.getRes('lightEff_png'));

                // this.maskActImg.anchorOffsetX = 714;//this.maskActImg.width;
                this.maskActImg.anchorOffsetY = 714;//this.maskActImg.height;
            }

            this.maskActImg.x = this.imgsCon.width * 0.4;
            this.maskActImg.y = -this.imgsCon.height * 0.2;

            this.imgsCon.addChild(this.maskActImg);
            this.imgsCon.addChild(this.square);

            this.maskActImg.mask = this.square;

            egret.Tween.get(this.maskActImg).to({ x: -714, y: 714 + this.imgsCon.height + 1300 }, 1000).call(function () {

                if (this.currLevel == 1) {
                    this.enterNextLevel();
                } else {
                    console.log('可以出奖了！');
                    this.gameSubmit();
                }
            }.bind(this));

            this.cellsImg.visible = false;
        }.bind(this));
    }

    // private onClick_selectImg():void{
    //     this.selectImg.visible  = false;
    //     this.currCell           = null;
    // }

    private enterNextLevel(): void {
        this.actGroup.scaleX = 0;
        this.actGroup.scaleY = 0;

        this.enterNextPanel.visible = true;
        //进入下一关panel动画
        egret.Tween.get(this.actGroup).to({ scaleX: 1, scaleY: 1 }, 500, egret.Ease.backInOut).call(function () {
            this.enterNextTimeDown = window['enterNextTime'] ? window['enterNextTime'] : 5;

            this.enterNextTxt.textFlow = [
                { text: this.enterNextTimeDown + '', style: { "textColor": 0xf8550d } },
                { text: '秒后进入最终回合' }
            ];
        }.bind(this));

        this.actMask.alpha = 0;
        egret.Tween.get(this.actMask).to({ alpha: 1 }, 300);
    }

    //判断拼图成功
    private isSuccessComplete(): boolean {
        for (var i = 0; i < this.imgCount1; i++) {
            for (var j = 0; j < this.imgCount2; j++) {
                var idx0: number = (j + i * this.imgCount2);
                var idx1: number = Number(this.pics[idx0].name);

                if (idx0 != idx1) {
                    return false;
                }
            }
        }

        return true;
    }

    //开始播放查看图片时，初始化ui数据
    private resetScanUI(level: number): void {
        // this.cellsImg.scaleX        = 1;
        // this.cellsImg.scaleY        = 1;
        this.timeTips.alpha = 0;
        this.moveImg.scaleX = 1;
        this.moveImg.scaleY = 1;
        this.imgsCon.scaleX = 1;
        this.imgsCon.scaleY = 1;
        this.moveImg.x = 43;
        this.moveImg.y = 314;

        this.startActGroup.visible = false;
        this.timeDownLb.visible = false;
        this.startText0.visible = true;
        this.startText1.visible = true;
        this.scanGroup.visible = true;
        this.gameGroup.visible = false;
        this.scanMask.visible = true;
        this.cellsImg.visible = true;
        this.imgsCon.visible = false;
        this.ruleBtn.visible = false;
        this.skipBtn.visible = false;
        this.sImgBg.visible = false;

        this.levelTxtImg.alpha = 0;
        this.startText0.scaleX = 3;
        this.startText0.scaleY = 3;
        this.startText1.scaleX = 1;
        this.startText1.scaleY = 1;
        this.startText0.alpha = 0;
        this.startText1.alpha = 1;

        this.sImg.texture = null;
        this.gameGroup.touchEnabled = true;
        this.startActGroup.touchEnabled = true;

        this.levelTxtImg.texture = RES.getRes('levelTxt' + level + '_png');// await RES.getResAsync('levelTxt' + level + '_png');
        this.gameTickNum = window['gameTickNum'] ? window['gameTickNum'] : 65;
        this.endTimeLb.text = (window['gameTickNum'] ? window['gameTickNum'] : 65) + 's';

        this.gTickStart = false;
        this.isSuccess = false;

        this.refreshGameTickLb();
    }

    //刷新倒计时显示
    private refreshGameTickLb(): void {
        var maxTime: number = window['gameTickNum'] ? window['gameTickNum'] : 65;
        var val: number = this.gameTickNum / maxTime;
        this.thumbImg.x = 100 + 509 * val;
        this.timeBar.value = val * 100;//Math.floor(val * 100);
        this.gTimeDownLb.text = this.gameTickNum + 's';
    }

    //移除所有cell的touch事件
    private removeEvents_cell(): void {
        if (!this.pics) return;

        for (var i: number = 0; i < this.pics.length; i++) {
            this.pics[i].removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onUp_cellImg, this);
            this.pics[i].removeEventListener(egret.TouchEvent.TOUCH_RELEASE_OUTSIDE, this.onUp_cellImg, this);
            this.pics[i].removeEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onDown_cellImg, this);
        }
    }

    private gameSubmit() {
        Loading.instace.show();
        NetManager.ins.gameSubmit((success: boolean) => {
            if (!success) {//接口失败了。？？？？？？？截图联系海底捞
                Loading.instace.hide();

                this.showMsg('iknowBtn',
                    [
                        { text: "网络竟然崩溃了～\n截图弹窗反馈给“捞小蜜”！" }
                    ],
                    this.againBtnCallBack, this.againBtnCallBack);
                return
            }
            //回调捞结果
            NetManager.ins.getSubmitResult((data) => {//此处处理轮询失败？？？？？？？
                if (data == 'pollingFaild' || !data) {
                    this.showMsg('iknowBtn',
                        [
                            { text: "网络竟然崩溃了～\n奖品发放异常，联系“捞小蜜”了解情况!" }
                        ],
                        this.againBtnCallBack, this.againBtnCallBack);
                } else {
                    this.showPrizePanel();
                }
                Loading.instace.hide();
            },
                DataManager.ins.gameSubmitData.orderId,
                //轮询
                () => {
                    return DataManager.ins.gameGetSubmitResultData.flag;
                });
        },
            DataManager.ins.doStartData.ticketId,
            1,
            '[]',
            DataManager.ins.doStartData.submitToken,
            "",
        )
    }

    private showPrizePanel(): void {
        //处理中奖情况
        if (DataManager.ins.gameGetSubmitResultData && DataManager.ins.gameGetSubmitResultData.lottery) {//中奖了
            PanelCtrl.instance.show(ModuleTypes.PRIZE_PANEL);
        } else {//未中奖,（必中活动未中奖要做容错处理）？？？？？？？、
            this.showMsg('iknowBtn',
                [
                    { text: "奖品发完了～\n截图弹窗反馈给“捞小蜜”！" }
                ],
                this.againBtnCallBack, this.againBtnCallBack);
        }
    }

    //消息弹出框
    private showMsg(bname: string, msgArr: any, callBack?: Function, closeCallBack?: Function): void {
        var msgData: any = {
            btnName: bname,
            fontSize: 35,
            lineCount: 2,
            lineSpace: 15,
            callBack: callBack ? callBack.bind(this) : null,
            closeCallBack: closeCallBack ? closeCallBack.bind(this) : null,
        };
        msgData.msgArr = msgArr;

        PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, msgData);
    }

    //打乱数组顺序
    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;
    }
}