import { Scene } from "../../module/views/Scene";
import { RES } from "../../module/RES";
import resCanvasList from "../../../game/resCanvasList"
import resList from '../../resource/assets';
// import ViewCtrl from '../../../../util/viewCtrl.js'
// import Enum from ',./../../../../util/enum.js'
import { Card } from "../sprite/card";
import { GDispatcher } from "../Main";
import { MSG } from "../common/MyEvent";

export class StartScene extends Scene {
    private curLevel: number;     //当前关卡
    private rows: number[] = [];   //行数
    private cols: number[] = [];   //列数
    private minLevel= 1;     //最小关卡
    private maxLevel= 6;     //最大关卡
    private levelBg: FYGE.Sprite;  //关卡背景
    private levelTitle: FYGE.Sprite;     //关卡标题
    private levelTitleUUidArr: string[] = [];    //关卡标题uuid组
    private countDown: FYGE.Sprite;      //倒计时图片
    private countDownCnt: number = 3;
    private countDownUUidArr: string[] = [];    //倒计时图片uuid组
    private countDownBg: FYGE.Sprite;     //倒计时背景
    private countDownGroup: FYGE.Sprite; //倒计时组
    private guideImg: FYGE.Sprite;   //引导页
    private guideGroup: FYGE.Sprite; //引导组
    private levelGroup: FYGE.Sprite; //关卡组
    private cardGourp: FYGE.Sprite;  //卡牌组
    private stageW: number;
    private stageH: number;
    private offsetX: number[] = [];  //每一关的第一列的卡片起始的X
    private offsetY: number[] = [];  //每一关的第一行的卡片起始的Y
    private offsetX1: number[] = [];   //每一关卡片之间X的距离
    private offsetY1: number[] = [];   //每一关卡片之间Y的距离
    private cardArr: Card[] = [];   //卡牌组
    private changeCardArr:Card[] = [];  //当前正在改变的卡牌组
    private cardSize: any[] = [];    //卡牌大小
    private trueCardCnt: number[] = [];  //每一关正确卡牌的数量
    private levelSizeArr: number[] = []; //每一关卡牌的大小
    private gameBg: FYGE.Sprite;     //游戏背景
    private randomSetPosCnt: number;     //每一关对应的游戏随机生成设置卡牌范围的次数
    private randomCntArr: number[] = []; //每一关对应的游戏随机生成设置卡牌范围的次数组
    private randomCardMoveCnt:number;   //卡牌移动次数随机
    private selectTureCnt:number;   //当前选择的正确的卡牌数量

    //初始化地图数据与地图视觉
    initUi() {
        var that = this;
        that.initData();
        that.initObj();

    }

    //初始化地图数据
    initData() {
        console.log("hahahahTextureCahe",FYGE.TextureCache);
        var that = this;
        that.selectTureCnt = 0;
        that.curLevel = 3;
        that.countDownCnt = 3;
        that.rows = [2, 3, 3, 3, 4, 4];
        that.cols = [2, 3, 3, 3, 4, 4];
        that.cardSize = [{ w: 313, h: 314 }, { w: 206, h: 207 }, { w: 158, h: 158 }]
        that.trueCardCnt = [1, 1, 2, 3, 2, 3]
        that.levelSizeArr = [0, 1, 1, 1, 2, 2]
        that.randomCntArr = [1, 2,3,4,6,6]
        that.offsetX = [20, 18, 18, 18,16,16];
        that.offsetY = [20, 18, 18, 18,12,12];
        that.offsetX1 = [14, 14, 14, 14,6,6]
        that.offsetY1 = [14, 12, 12, 12,8,8]
        that.countDownUUidArr = ["0e10dd45-fa85-4669-ac29-17e15dde29f2", "e92b7807-0c54-400f-930c-a5038126ea71", "9661f715-ac93-4344-b1e1-cdb423b4d58a"];
        that.levelTitleUUidArr = ["d85a2de2-e81f-445a-84b0-a9049a9b1d70", "74f8e671-7638-40eb-bf95-16c04ee92948", "c595ee27-a4e3-4084-8901-a9df5591c769",
            "38f581a2-9d96-4244-bcec-d0536375b8a6", "f0511077-9267-43de-9f09-bef6c7375a04", "9559f83d-9215-4c45-8d4c-030bd7b115d3"];
    }

    //初始化对象图片数据
    initObj() {
        var that = this;
        console.log("初始化")
        that.stageW = that.stage.viewRect.width;
        that.stageH = that.stage.viewRect.height;
        that.gameBg = new FYGE.Sprite(RES.getRes(resCanvasList["47d9b481-e72a-47a9-85d3-0c2e5e79c1e7"].url));
        that.gameBg.x = (that.stageW - that.gameBg.width) >> 1;
        that.gameBg.y = (that.stageH - that.gameBg.height) >> 1;
        that.addChild(that.gameBg);
        that.levelGroup = new FYGE.Sprite();
        that.addChild(that.levelGroup);
        that.countDownGroup = new FYGE.Sprite();
        that.addChild(that.countDownGroup);
        that.countDownGroup.visible = false;
        that.guideGroup = new FYGE.Sprite();
        that.addChild(that.guideGroup);
        that.guideGroup.visible = false;

        that.guideImg = new FYGE.Sprite(RES.getRes(resCanvasList["7e3ac1bd-bbcd-4073-83cf-dbd1268e1dc4"].url))
        that.guideGroup.addChild(that.guideImg);
        that.guideImg.x = (that.stageW - that.guideImg.width) >> 1;
        that.guideImg.y = (that.stageH - that.guideImg.height) >> 1;

        that.countDownBg = new FYGE.Sprite(RES.getRes(resCanvasList["aa29b4ab-e5ba-4156-97e1-28738f2f8453"].url));
        that.countDownBg.alpha = 0.7
        that.countDownGroup.addChild(that.countDownBg);
        that.countDown = new FYGE.Sprite(RES.getRes(resCanvasList[that.countDownUUidArr[0]].url));
        that.countDown.anchorX = that.countDown.width >> 1;
        that.countDown.anchorY = that.countDown.height >> 1;
        that.countDown.x = (that.stage.viewRect.width - that.countDown.width) >> 1;
        that.countDown.y = (that.stage.viewRect.height - that.countDown.height) >> 1;
        that.countDownGroup.addChild(that.countDown);

        that.levelBg = new FYGE.Sprite(RES.getRes(resCanvasList["8a0a8d24-c820-4d8d-9db9-e79c8c548829"].url));
        that.levelBg.x = (that.stage.viewRect.width - that.levelBg.width) * 0.5;
        that.levelBg.y = (that.stage.viewRect.height - that.levelBg.height - 110) * 0.5;
        that.levelGroup.addChild(that.levelBg);
        that.levelTitle = new FYGE.Sprite(RES.getRes(resCanvasList[that.levelTitleUUidArr[0]].url));
        that.levelTitle.x = that.levelBg.x;
        that.levelTitle.y = that.levelBg.y + 100;
        that.levelGroup.addChild(that.levelTitle);
        that.cardGourp = new FYGE.Sprite();
        that.cardGourp.x = that.levelBg.x;
        that.cardGourp.y = that.levelBg.y + 206;
        that.levelGroup.addChild(that.cardGourp);
    
    }

    start(data) {
        super.start()
        var that = this;
        that.curLevel = 0;
        that.initNewLevel();
        // that.setMap();
        let newPlayer =  localStorage.getItem("mrzzNewPlayer");
        if(!newPlayer){
            that.guideGroup.visible = true;
            localStorage.setItem("mrzzNewPlayer","yes");
        }else{
            that.startCountDown();
        }
    }

    /**下一关 */
    nextLevel(){
        console.log("进入新关卡")
        var that = this;
        that.startCountDown();
    }

    /**生成 */
    initNewLevel(){
        var that = this;
        // if(that.curLevel>=that.maxLevel) return;
        that.curLevel ++ ;
        if(that.curLevel>that.maxLevel) return;
        for(let i=0;i<that.cardArr.length;i++){
            that.cardArr[i].parent.removeChild(that.cardArr[i]);
            that.cardArr.splice(i,1);
            i--;
        }
        that.changeCardArr.splice(0);
        that.selectTureCnt = 0;
        that.setMap();
    }

    // clearCardArr(){
        
    // }

    /**开始倒计时 */
    startCountDown() {
        var that = this;
        that.guideGroup.visible = false;
        that.countDownGroup.visible = true;
        that.countDownCnt = 3;
        that.countDown.texture = RES.getRes(resCanvasList[that.countDownUUidArr[that.countDownUUidArr.length - that.countDownCnt]].url);
        that.countDown.x = (that.stage.viewRect.width - that.countDown.width) >> 1;
        that.countDown.y = (that.stage.viewRect.height - that.countDown.height) >> 1;
        var timeCnt = setInterval(() => {
            that.countDownCnt--;
            if (that.countDownCnt > 0) {
                that.countDown.texture = RES.getRes(resCanvasList[that.countDownUUidArr[that.countDownUUidArr.length - that.countDownCnt]].url);
                that.countDown.x = (that.stage.viewRect.width - that.countDown.width) >> 1;
                that.countDown.y = (that.stage.viewRect.height - that.countDown.height) >> 1;
            } else {
                that.countDownGroup.visible = false;
                that.randomSetPosCnt = that.randomCntArr[that.curLevel-1];
                GDispatcher.dispatchEvent(MSG.GAMESTART_CHANGECARDSTATUS);
                clearInterval(timeCnt);
            }
        }, 1000)
    }

    /**创建地图 */
    setMap() {
        var that = this;
        var col = that.cols[that.curLevel - 1];
        var row = that.rows[that.curLevel - 1];
        var cnt = col * row;
        var offsetX = that.offsetX[that.curLevel - 1];
        var offsetY = that.offsetY[that.curLevel - 1];
        var offsetX1 = that.offsetX1[that.curLevel - 1]
        var offsetY1 = that.offsetY1[that.curLevel - 1]
        var trueCnt = that.trueCardCnt[that.curLevel - 1];
        var size = that.levelSizeArr[that.curLevel - 1];
        for (var i = 0; i < cnt; i++) {
            if (trueCnt > 0) {
                if (Math.random() < 0.2) {
                    var type = 1
                    trueCnt--;
                } else if (trueCnt == (cnt - i)) {
                    var type = 1;
                    trueCnt--;
                } else {
                    var type = 0;
                }
            } else {
                var type = 0;
            }

            let card = new Card({ id: i, type: type, size: size })
            console.log(type)
            that.cardGourp.addChild(card);
            card.x = offsetX + i % col * (that.cardSize[size].w + offsetX1);
            card.y = offsetY + Math.floor(i / col) * (that.cardSize[size].h + offsetY1)
            that.cardArr.push(card);
        }
        that.cardGourp.mouseChildren = true;
        that.levelTitle.texture = RES.getRes(resCanvasList[that.levelTitleUUidArr[that.curLevel-1]].url);
    }


    initEvents() {
        super.initEvents();
        this.guideGroup.addEventListener(FYGE.MouseEvent.CLICK,this.startCountDown,this);
        GDispatcher.addEventListener(MSG.GAMESTART_CHANGECARDPOS, this.changeCardPos, this);
        GDispatcher.addEventListener(MSG.GAMESTATR_CARDMOVEEND,this.cardMoveEnd,this);
        GDispatcher.addEventListener(MSG.GAME_FAILED,this.gameFailed,this)
        GDispatcher.addEventListener(MSG.GAME_SELETTRUE,this.gameClearLevel,this);
        // document.addEventListener("nextLevel",this.nextLevel,this);
        GDispatcher.addEventListener("nextLevel",this.nextLevel,this);
    }


    removeEvents() {
        super.removeEvents()
        this.guideGroup.removeEventListener(FYGE.MouseEvent.CLICK,this.startCountDown,this);
        GDispatcher.removeEventListener(MSG.GAMESTART_CHANGECARDPOS, this.changeCardPos, this);
        GDispatcher.removeEventListener(MSG.GAMESTATR_CARDMOVEEND,this.cardMoveEnd,this);
        GDispatcher.removeEventListener(MSG.GAME_FAILED,this.gameFailed,this)
        GDispatcher.removeEventListener(MSG.GAME_SELETTRUE,this.gameClearLevel,this);
        GDispatcher.removeEventListener("nextLevel",this.nextLevel,this);
    }

    changeCardPos() {
        var that = this;
        for (let i = 0; i < that.cardArr.length; i++) {
            if (!that.cardArr[i].changeStateEnd) return;
        }
        if (that.randomSetPosCnt <= 0) {
            console.log("游戏开始")
            GDispatcher.dispatchEvent(MSG.GAME_START);
            return;
        } else {
            that.randomSetPosCnt--;
        }
        console.log("改变位置")
        var cardArr = that.cardArr;
        var col = that.cols[that.curLevel - 1];
        var row = that.rows[that.curLevel - 1];
        //随机一张卡片index
        var index = Math.floor(Math.random() * that.cardArr.length);
        //随机是朝左还是右
        if (Math.random() > 0.5) {
            var left = fundLeft(index);
            if (!left) {
                var right = fundRight(index);
            }
        } else {
            var right = fundRight(index);
            if (!right) {
                var left = fundLeft(index);
            }
        }
        console.log("aaaa", index, left, right)

        if (Math.random() > 0.5) {
            var up = fundUp(index);
            if (!up) {
                var down = fundDown(index);
            }
        } else {
            var down = fundDown(index);
            if (!down) {
                var up = fundUp(index);
            }
        }
        console.log("bbbb", index, up, down);

        that.setRectRange(index, left, right, up, down);

        //判断左边
        function fundLeft(index) {
            var leftIndex = index - 1;      //左
            if (cardArr[leftIndex] && cardArr[index].y == cardArr[leftIndex].y) {
                var nextLeftIndex = leftIndex - 1;
                if (cardArr[nextLeftIndex] && cardArr[leftIndex].y == cardArr[nextLeftIndex].y) {
                    leftIndex = nextLeftIndex;
                    nextLeftIndex = leftIndex - 1;
                    if (cardArr[nextLeftIndex] && cardArr[leftIndex].y == cardArr[nextLeftIndex].y) {
                        leftIndex = nextLeftIndex;
                        return leftIndex;
                    } else {
                        return leftIndex;
                    }
                } else {
                    return leftIndex;
                }
            } else {        //右
                return undefined
            }
        }
        //判断右边
        function fundRight(index) {
            var rightIndex = index + 1;      //左
            if (cardArr[rightIndex] && cardArr[index].y == cardArr[rightIndex].y) {
                var nextRightIndex = rightIndex + 1;
                if (cardArr[nextRightIndex] && cardArr[rightIndex].y == cardArr[nextRightIndex].y) {
                    rightIndex = nextRightIndex;
                    nextRightIndex = rightIndex + 1;
                    if (cardArr[nextRightIndex] && cardArr[rightIndex].y == cardArr[nextRightIndex].y) {
                        rightIndex = nextRightIndex;
                        return rightIndex;
                    } else {
                        return rightIndex;
                    }
                } else {
                    return rightIndex;
                }
            } else {        //右
                return undefined
            }
        }
        //判断上边
        function fundUp(index) {
            var upIndex = index - col;      //上
            if (cardArr[upIndex] && cardArr[index].x == cardArr[upIndex].x) {
                var nextUpIndex = upIndex - col;
                if (cardArr[nextUpIndex] && cardArr[upIndex].x == cardArr[nextUpIndex].x) {
                    upIndex = nextUpIndex;
                    nextUpIndex = upIndex - col;
                    if (cardArr[nextUpIndex] && cardArr[upIndex].x == cardArr[nextUpIndex].x) {
                        upIndex = nextUpIndex;
                        return upIndex;
                    } else {
                        return upIndex;
                    }
                } else {
                    return upIndex;
                }
            } else {        //下
                return undefined
            }
        }
        //判断右边
        function fundDown(index) {
            var downIndex = index + col;      //上
            if (cardArr[downIndex] && cardArr[index].x == cardArr[downIndex].x) {
                var nextDownIndex = downIndex + col;
                if (cardArr[nextDownIndex] && cardArr[downIndex].x == cardArr[nextDownIndex].x) {
                    downIndex = nextDownIndex;
                    nextDownIndex = downIndex + col;
                    if (cardArr[nextDownIndex] && cardArr[downIndex].x == cardArr[nextDownIndex].x) {
                        downIndex = nextDownIndex;
                        return downIndex;
                    } else {
                        return downIndex;
                    }
                } else {
                    return downIndex;
                }
            } else {        //下
                return undefined
            }
        }

    }

    setRectRange(index: number, left: number, right: number, up: number, down: number) {
        console.log(left, right, up, down);
        var that = this;
        var x;
        var y;
        var w;
        var h;
        // var that.cardArr = that.that.cardArr;
        if (left >= 0) {
            x = that.cardArr[left].x;
            w = Math.abs(that.cardArr[index].x - that.cardArr[left].x);
            console.log("left", left)
        } else {
            x = that.cardArr[index].x;
            w = Math.abs(that.cardArr[index].x - that.cardArr[right].x)
            console.log("right", right)
        }

        if (up >= 0) {
            y = that.cardArr[up].y;
            h = Math.abs(that.cardArr[index].y - that.cardArr[up].y)
            console.log("up", up)
        } else {
            y = that.cardArr[index].y;
            h = Math.abs(that.cardArr[index].y - that.cardArr[down].y)
            console.log("down", down)
        }
        console.log(x, y, w, h)
        var offsetX1 = that.offsetX1[that.curLevel - 1]
        var offsetY1 = that.offsetY1[that.curLevel - 1]
        var size = that.levelSizeArr[that.curLevel - 1];
        var col = that.cols[that.curLevel - 1];
        var row = that.rows[that.curLevel - 1];
        that.changeCardArr=[];
        that.randomCardMoveCnt = Math.floor(Math.random() * 3) + 2;
        for (let i = 0; i < that.cardArr.length; i++) {
            if((that.cardArr[i].x <= (x + w) && that.cardArr[i].x >= x && that.cardArr[i].y >= y && that.cardArr[i].y <= (y + h))
             &&(that.cardArr[i].x == x || that.cardArr[i].x == (x + w) || that.cardArr[i].y == y || that.cardArr[i].y == (y+ h))){
                that.cardArr[i].isMoveCard = true;
                that.changeCardArr.push(that.cardArr[i]);
                that.cardArr[i].setMoveStatus(x, y, w, h, col,row,that.cardSize[size].w + offsetX1,that.cardSize[size].h + offsetY1);
                that.cardArr.splice(i,1);
                i--;
            }else{
                that.cardArr[i].isMoveCard = false;
            }
        }
        GDispatcher.dispatchEvent(MSG.GAMESTART_CARDMOVE)
    }

    /**所有需要移动的卡牌移动一次结束 */
    cardMoveEnd(){
        for(var i=0;i<this.changeCardArr.length;i++){
            if(this.changeCardArr[i].isMoving){
                return;
            }
        }
        // this.changeCardArr.sort((a,b)=>{return (a.x-b.x)})
        // this.changeCardArr.sort((a,b)=>{return (a.y-b.y)})
        console.log("变换前卡牌",this.cardArr);
        this.randomCardMoveCnt --;
        if(this.randomCardMoveCnt<=0){
            this.cardArr = this.cardArr.concat(this.changeCardArr);
            this.cardArr.sort((a,b)=>{return a.id-b.id})    
            console.log("变换后的卡牌",this.cardArr);
            this.changeCardPos();
        }else{
            GDispatcher.dispatchEvent(MSG.GAMESTART_CARDMOVE)
        }
        
    }

    /**闯关失败 */
    gameFailed(){
        console.log("选错啦，失败啦")
        let e = new Event("GAME_FAILED")
        document.dispatchEvent(e);
    }

    /**是否通过当前关或当前关 */
    gameClearLevel(){
        var that = this;
        that.selectTureCnt ++ ;
        var trueCnt = that.trueCardCnt[that.curLevel - 1];
        if(that.selectTureCnt >= trueCnt){
            that.selectTureCnt = 0;
            that.initNewLevel();
            if((that.curLevel-1)>=that.maxLevel){
                console.log("通过所有关卡")
                let e = new Event("GAME_SUCCESS")
                document.dispatchEvent(e);
            }else{
                console.log("通过当前关卡") 
                let level = that.curLevel -1;
                let event = new CustomEvent("GAME_CLEARCURLEVEL", { detail: { level:level } });
                document.dispatchEvent(event)
            }
        }
    }
}
