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

export default class GameScene extends Scene {
    // public enterNextPanel: eui.Group;
    public startActGroup: eui.Label;
    public enterNextTxt: eui.Label;
    public levelTxtImg: eui.Image;
    public gTimeDownLb: eui.Label;
    public startText0: eui.Image;
    public startText1: eui.Image;
    // 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 moveImg: eui.Image;
    public imgsCon: eui.Group;
    public scanMask: eui.Rect;
    public actMask: eui.Rect;
    public titleImg:eui.Image;
    public barGroup:eui.Group;
    public mainbg: eui.Image;
    public barImg:eui.Image;
    public endImg:eui.Image;
    public perLb:eui.Label;
    public list:eui.List;

    private enterNextTimeDown: number;
    private endMaskShap:egret.Shape;
    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;
    private picIdxs:number[];
    private currIdx:number;
    public soundBtn:eui.Group;

    private imgname:string;

    private listData:eui.ArrayCollection;
    private selectItem:ItemCell1;


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

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

    initEvents() {
        super.initEvents();
        this.skipBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_skipBtn, this);
        this.ruleBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_ruleBtn, this);
        this.addEventListener(egret.TouchEvent.TOUCH_MOVE, this.onMove_imgsCon, this);
        this.soundBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_soundBtn, this);
        this.timer.addEventListener(egret.TimerEvent.TIMER, this.ontimer, this);
        this.stage.addEventListener(egret.TouchEvent.TOUCH_END, this. onTap, this);

        GDispatcher.addEvent('dragStart', this.dragStart, this);
    }

    private onTap(e:egret.TouchEvent):void{
        
        if(e.currentTarget == this.stage){
            if(this.itemDragData){
                this.touchEnabled = false;
                this.touchChildren = false;
                egret.Tween.removeTweens(this.selectItem);
                egret.Tween.get(this.selectItem).to({x:this.itemDragData.ox, y:this.itemDragData.oy}, 200).call(()=>{
                    this.itemDragData.callback();
                    this.selectItem.visible = false;
                    this.selectItem.candrag = false;
    
                    this.itemDragData = null;
    
                    this.touchEnabled = true;
                    this.touchChildren = true;
                });
            }
        }
    }

    removeEvents() {
        super.removeEvents();
        this.removeEvents_cell();
        GDispatcher.removeEvent('dragStart', this.dragStart, this);
        this.selectItem.removeEventListener(egret.TouchEvent.TOUCH_END, this.onTap_selectItem, this);
        this.skipBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_skipBtn, this);
        this.ruleBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onClick_ruleBtn, this);
        this.soundBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_soundBtn, this);
        this.removeEventListener(egret.TouchEvent.TOUCH_MOVE, this.onMove_imgsCon, this);
        this.timer.removeEventListener(egret.TimerEvent.TIMER, this.ontimer, this);
        this.stage.removeEventListener(egret.TouchEvent.TOUCH_END, this. onTap, 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.picIdxs = [0, 1, 2, 3, 4];
        this.picIdxs = this.shuffleArray(this.picIdxs);
        this.currIdx = this.picIdxs.pop();
        window['conmpleteImgArr'].push(this.currIdx);
        //加载背景并设置背景图片
        this.imgname = 'ptImg' + this.currIdx + '_jpg';
        this.texture = await RES.getResAsync(this.imgname);
        
        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;
        window['conmpleteImgArr'] = [];
        this.percentHeight = 100;
        this.listData = new eui.ArrayCollection();
        this.timeDownNum = window['tickTips'] ? window['tickTips'] : 5;
        // this.pics = [null, null, null, null, null, null, null, null, null];
    }

    private onLoad(): void {

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

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

        this.endMaskShap = new egret.Shape();
        this.endMaskShap.graphics.beginFill(0);
        this.endMaskShap.graphics.drawRoundRect(0, 0, 585, 585,50);
        this.endMaskShap.graphics.endFill();
        this.imgsCon.addChild(this.endMaskShap);
        this.endImg.mask = this.endMaskShap;
        
        this.endImg.source = this.imgname;
        this.gameTickNum = window['gameTickNum'] ? window['gameTickNum'] : 55;
        this.endTimeLb.text = (window['gameTickNum'] ? window['gameTickNum'] : 55) + 's';

        this.selectItem = new ItemCell1();
        this.addChild(this.selectItem);
        this.selectItem.x = -300;
        this.selectItem.anchorOffsetX = 68;
        this.selectItem.anchorOffsetY = 68;

        this.selectItem.addEventListener(egret.TouchEvent.TOUCH_END, this.onTap_selectItem, this);
        // this.selectItem.addEventListener(egret.TouchEvent.TOUCH_RELEASE_OUTSIDE, this.onTap_selectItem, this);

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

        this.perLb.text = window['conmpleteImgArr'].length + '/5';
        //第一关
        this.currLevel = 0;
        this.setScanGroup(0, 3, 3);

    }

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

    }

    private maskShap:egret.Shape;
    private setMask():void{

        this.maskShap = new egret.Shape();
        this.maskShap.x = 5;
        this.maskShap.y = 3;
        this.barGroup.addChild(this.maskShap);

        this.maskShap.graphics.beginFill(0xe6844e, 1);
        this.maskShap.graphics.drawRoundRect(0, 0, 530, 32,50)  //宽度0到443
        this.maskShap.graphics.endFill();
        this.barImg.mask = this.maskShap;

        // this.maskShap.x = -582;
    }

    private onClick_skipBtn(): void {
        console.log('跳过查看图片');
        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.titleImg.y = 60;
        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.skipBtn.visible = true;

                this.timeDownNum = window['tickTips'] ? window['tickTips'] : 5;
                this.timeTips.textFlow = [
                    { text: '你有  ' },
                    { text: this.timeDownNum + 's', style: { 'size': 50 } },
                    { text: '  秒时间查看原图' }
                ];

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

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

            this.timeTips.textFlow = [
                { text: '你有  ' },
                { text: this.timeDownNum + 's', style: { 'size': 50 } },
                { text: '  秒时间查看原图' }
            ];

            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(async function () {
        //             await this.startNextLevel();
        //             // this.enterNextPanel.visible = false;
        //         }.bind(this));
        //     }
        // }

        if (this.gTickStart) {
            if (this.gameTickNum > 0) {
                this.gameTickNum--;
                // console.log('this.gameTickNum', this.gameTickNum);
                this.refreshGameTickLb();

                let mx = this.maskShap.x - 530/(window['gameTickNum'] ? window['gameTickNum'] : 55);
                egret.Tween.get(this.maskShap).to({x:mx}, 100);

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

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

                        PanelCtrl.instance.show(ModuleTypes.GAMEOVER_PANEL);
                    }
                }
            }
        }
    }

    //进入下一关
    private async startNextLevel() {
        Loading.instace.show();
        
        this.currIdx = this.picIdxs.pop();
        window['conmpleteImgArr'].push(this.currIdx);
        this.perLb.text = window['conmpleteImgArr'].length + '/5';
        let imgname = 'ptImg' + this.currIdx + '_jpg';
        this.texture = await RES.getResAsync(imgname);
        this.endImg.source = imgname;
        Loading.instace.hide();
        this.setScanGroup(1, 3, 3);
    }

    //倒计时后的动画
    private startGameAct(): void {
        egret.Tween.get(this.titleImg).to({y:29}, 500);
        this.imgsCon.visible = true;
        const scale = 134 / 585;

        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 () {
                playSound('startBtnSound');
                this.gTickStart = true;//游戏倒计时开始
                
                this.ruleBtn.visible = true;
                this.startText0.visible = false;
                this.startText1.visible = false;
                this.gameGroup.touchEnabled = false;
                this.startActGroup.visible = false;
            }.bind(this));
        }.bind(this));
    }

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

        this.cellsImg.source =  'line' + 0 + '_png';///RES.getRes();

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

        this.pics = [null, null, null, null, null, null, null, null, null];
        var i: number;
        var j: number;
        
        var pw: number = 195;//Math.floor(620 / len1);
        var ph: number = 195;//Math.floor(620 / 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);
                this.listData.addItem({texture:renderTexture, idx:(j + i * len2) + ''});
            }
        }

        //打乱图片位置
        this.listData.source = this.shuffleArray(this.listData.source);

        // 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.list.itemRenderer = ItemCell1;
        this.list.dataProvider = this.listData;

        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.START_SCENE);
            Loading.instace.hide();
        });
    }
    //this up 监听
    // private onUp(e:egret.TouchEvent):void{
    //     if(!e.target.name){

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

    //点到了list某一项
    private itemDragData:any;
    private dragStart(dragData:any):void{
        // e.target
        this.selectItem.data = dragData.pic;
        this.selectItem.dataChanged();
        this.selectItem.visible = true;

        this.selectItem.candrag = true;

        this.selectItem.x = dragData.ox;
        this.selectItem.y = dragData.oy;

        this.itemDragData = dragData;
    }

    //拖动元素抬起。
    private onTap_selectItem(e:egret.TouchEvent):void{
        console.log('e.stageX',e.stageX);
        console.log('e.stageY',e.stageY);
        let p = this.getPoint(e.stageX - 82.5, e.stageY - 377.5);
        let idx = this.selectItem.pic.idx;
        if(p){
            if(!this.pics[p.idx]){
                var cellImg: egret.Bitmap = new egret.Bitmap(this.selectItem.pic.texture);
                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.imgsCon.addChildAt(cellImg, 0);
        
                cellImg.touchEnabled = true;
                this.pics[p.idx] = cellImg;

                //删除list项目
                this.listData.removeItemAt(this.removeListItem(idx));
                this.list.dataProviderRefreshed();

            }else{

                let tture = this.pics[p.idx].texture;
                this.pics[p.idx].texture = this.selectItem.pic.texture;

                this.itemDragData.callback();
                let didx = this.removeListItem(idx);
                let ldata = this.listData.getItemAt(didx);
                ldata.texture = tture;
                ldata.idx = this.pics[p.idx].name;
                this.listData.itemUpdated(ldata);

                this.itemDragData = null;

            }
            
            this.pics[p.idx].x = p.x;
            this.pics[p.idx].y = p.y + 1;
            this.pics[p.idx].name = idx;

            this.selectItem.visible = false;
            this.selectItem.candrag = false;

            playSound('dragSound');
        }else{
            this.touchEnabled = false;
            this.touchChildren = false;
            egret.Tween.removeTweens(this.selectItem);
            egret.Tween.get(this.selectItem).to({x:this.itemDragData.ox, y:this.itemDragData.oy}, 200).call(()=>{

                this.touchEnabled = true;
                this.touchChildren = true;
                this.itemDragData.callback();
                this.selectItem.visible = false;
                this.selectItem.candrag = false;

                this.itemDragData = null;
            })
        }

        //判断是否拼图成功
        if(!this.listData.length){
            if (this.isSuccessComplete()) {
                this.imgsCon.addChild(this.endImg);
                this.imgsCon.addChild(this.endMaskShap);
                this.endImg.visible = true;

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

    //删除list中的项
    private removeListItem(idx:string):number{
        for(let i = 0; i < this.listData.length; i++){
            let item = this.listData.getItemAt(i);
            if(item.idx == idx){
                return i;
            }
        }

        return 0;
    }

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

        if(this.selectItem.candrag){
            this.selectItem.x = ex;
            this.selectItem.y = ey;

            if (e.stageY < 100 || e.stageY > 1200 || e.stageX < 0 || e.stageX > 750) {
                console.log('越界了1');
                // this.selectItem.touchEnabled = false;
                this.onTap_selectItem(e);
            }
        }else{
            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 && (element.name != e.target.name)) {
                if (element.touchEnabled) {
                    element.touchEnabled = false;
                }
            }
        });

        this.currCell = e.target;
        console.log('this.currCell',this.currCell)
        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 => {
            if(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;

                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]){
                                this.pics[i].touchEnabled = true;
                            //     break;
                            }
                        }
                    }
                    this.imgsCon.setChildIndex(this.cellsImg, this.imgsCon.numChildren);

                    if (this.isSuccessComplete()) {
                        this.imgsCon.addChild(this.endImg);
                        this.imgsCon.addChild(this.endMaskShap);
                        this.endImg.visible = true;

                        console.log('拼图成功222222');
                        //成功后的动效
                        this.showSuccessAct();
                        //停止倒计时
                        this.gTickStart = false;
                        this.isSuccess = true;
                    }
                }, this);
                playSound('dragSound');
                // console.log('mTime=' + mTime);
        } else {
            moveCell = this.currCell;
            let p;
            if(e){
               p = this.getPoint(e.stageX - 82.5, e.stageY - 377.5);
            }
            if(p){
                if (this.pics) {
                    for (let i = 0; i < this.pics.length; i++) {
                        if(this.pics[i]){
                            this.pics[i].touchEnabled = true;
                        //     break;
                        }
                    }
                }
                this.imgsCon.setChildIndex(this.cellsImg, this.imgsCon.numChildren);

                this.currCell.x = p.x;
                this.currCell.y = p.y;
                var idx0: number = this.pics.indexOf(this.currCell);
                this.pics[idx0] = null;
                this.pics[p.idx] = this.currCell;
                playSound('dragSound');

            }else{
                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]){
                                this.pics[i].touchEnabled = true;
                            //     break;
                            }
                        }
                    }
                    this.imgsCon.setChildIndex(this.cellsImg, this.imgsCon.numChildren);
                }, this);
                // console.log('mTime=' + mTime);

            }
        }

        this.currCell = null;
        this.movePoint = null;

    }

    //获取当前移动位置下的图片元素
    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;
                    return cell;
                }
            }

        }

        return cell;
    }

    //获取当前左边下批图小图的位置
    private getPoint(x:number, y:number):any{
        let p;
        var space = 195;
        for(let i = 0; i < 9; i++){//4
            let row = Math.floor(i / 3);
            let col = i % 3;
            if((x >= col * space && x < (col + 1) * space) && (y >= row * space && y < (row + 1) * space)){
                p = {x:col * space, y:row * space, idx:i};
                return p;
            }
        }

        return p;
    }

    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 eui.Image();
                this.maskActImg.source = 'lightEff_png';// = 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 () {

                PanelCtrl.instance.show(ModuleTypes.PRIZE_PANEL, {callback:async ()=>{
                    //进入下一关
                        if(this.picIdxs.length > 0){
                            await this.startNextLevel();
                            // egret.Tween.get(this.actGroup).to({ scaleX: 0, scaleY: 0 }, 200).call(async function () {
                            //     await this.startNextLevel();
                            // }.bind(this));
                        }else{
                            //已经通关5关
        
                        }
                    }, idx:this.currIdx});


                // if (this.currLevel == 1) {
                //     // this.enterNextLevel();
                //     egret.Tween.get(this.actGroup).to({ scaleX: 0, scaleY: 0 }, 200).call(async function () {
                //         await this.startNextLevel();
                //         // this.enterNextPanel.visible = false;
                //     }.bind(this));

                // } 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 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);
                if(!this.pics[idx0]){
                    return false;
                }
                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.imgsCon.scaleX = 1;
        this.imgsCon.scaleY = 1;

        this.startActGroup.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.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.gameGroup.touchEnabled = true;
        this.startActGroup.touchEnabled = true;

        this.levelTxtImg.texture = RES.getRes('levelTxt' + level + '_png');// await RES.getResAsync('levelTxt' + level + '_png');

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

        this.refreshGameTickLb();
    }

    //刷新倒计时显示
    private refreshGameTickLb(): void {
        this.gTimeDownLb.text = 'TIME : ' + this.gameTickNum + 's';
    }

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

        for (var i: number = 0; i < this.pics.length; i++) {
            if(this.pics[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();
    }


    //消息弹出框
    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;
    }
}