// 主游戏控制类
const {ccclass, property} = cc._decorator;
@ccclass
export default class GameManager extends cc.Component {
    @property(cc.Prefab)
    kuang1_Prefab: cc.Prefab = null;
    @property(cc.Prefab)
    kuang2_Prefab: cc.Prefab = null;
    @property(cc.Node)
    Block: cc.Node = null;
    @property(cc.Label)
    TimeLabel: cc.Label = null;
    @property(cc.Label)
    LevelLabel: cc.Label = null;
    @property(cc.Node)
    Guide: cc.Node = null;

    @property(cc.Sprite)
    progress: cc.Sprite = null; //-95 640
    @property(cc.Node)  
    Top: cc.Node = null;//80 -725

    countTime: number;      //游戏总daojishi
    startTime: number;      //游戏开始时间，时间戳
    pause: boolean ;        //游戏暂停
    gameOver: boolean ;     //游戏结束
    result: number;         //当前小局结束标杆

    outside_Array: any;     //内圈数组
    inside_Array: any;      //外圈数组
    level: number;          //关卡等级
    guide_Level: number;    //引导等级
    guide_State: boolean;    //引导等级
    config: {};             //当前关卡配置
    answerInside: number;   //正确答案位置
    answerOutside: number;  //正确答案位置
    pass: boolean;          //是否通关
    outside: any;           //外圈实际执行数组
    inside: any;            //内圈实际执行数组
    answerInsideTexture: number;  //争取答案图片
    answerOutsideTexture: number;  //争取答案图片
    insideTexture: number[];   //错误答案数组
    outsideTexture: number[];   //错误答案数组
    
  

    onLoad () {
        this.guide_State = false;
        this.level = cc.fx.GameConfig.GM_INFO.level;
        this.guide_Level = cc.fx.GameConfig.GM_INFO.guide_Level;
        this.LevelLabel.string = (this.level+1)+"";
        this.progress.fillRange = cc.fx.GameConfig.GM_INFO.score/24;
        if(this.progress.fillRange>= 0.2) this.Top.getChildByName("star1").active = true;
        if(this.progress.fillRange>= 0.5) this.Top.getChildByName("star2").active = true;
        if(this.progress.fillRange>= 0.8) this.Top.getChildByName("star3").active = true;
        if((this.level == 0 && this.guide_Level == 4) ||
        (this.level == 4 && this.guide_Level == 3) ||
        (this.level == 8 && this.guide_Level == 1)){
            this.openGuide(false);
        }
        else{
            this.LevelLabel.node.active = true;
            this.node.getChildByName("Top").getChildByName("lianxi").getComponent(cc.Label).string = "第        轮";
            this.init();
        }
    }

    init(){
        if(this.level == 4 && this.guide_Level == 2) {
           cc.fx.GameConfig.GM_INFO.guide_Level -= 1;
           this.guide_State = true;
           this.LevelLabel.node.active = false;
           this.node.getChildByName("Top").getChildByName("lianxi").getComponent(cc.Label).string = "练   习";
        //    this.node.getChildByName("tip").active = true;
        }

        this.result = 0;
        this.countTime = 6;
        this.TimeLabel.string =  cc.fx.GameTool.getTimeMargin(this.countTime);
        this.createBlock();
        setTimeout(() => {
            this.createCustom();
        }, 1000);
    }

    openGuide(type){
        this.Guide.active = true;
        this.guide_State = true;
        // this.node.getChildByName("tip").active = true;
        if(!type) cc.fx.GameConfig.GM_INFO.guide_Level -= 1;
        this.Guide.getChildByName("one").active = false;
        this.Guide.getChildByName("two").active = false;
        this.Guide.getChildByName("three").active = false;
        this.Guide.getChildByName("four").active = false;
        let name = "one";
        if(this.level == 0){
            name = "one";
            this.LevelLabel.node.active = false;
            this.node.getChildByName("Top").getChildByName("lianxi").getComponent(cc.Label).string = "练   习";
        }
        else if(this.level == 4){
            name = "two";
            this.LevelLabel.node.active = false;
            this.node.getChildByName("Top").getChildByName("lianxi").getComponent(cc.Label).string = "练   习";
        }
        else if(this.level == 8){
            name = "three";
            this.guide_State = false;
        }
        if(type) name = "four";
        this.Guide.getChildByName(name).active = true;
        cc.tween(this.Guide.getChildByName(name))
        .to(0.5,{opacity:255})
        .start();
    }

    closeGuide(){
        if(this.Guide.getChildByName("four").active){
            this.Guide.active = false;
            cc.director.loadScene("GameScene");
        }
        else{
            this.Guide.active = false;
            this.init();
        }
        // 

    }

    //创建方块地图
    createBlock(){
        this.outside_Array = [];
        this.inside_Array = [];
        this.outside = [];
        this.inside = [];
        for(let i=0; i<16; i++){
            let block = cc.instantiate(this.kuang1_Prefab);
            block.getComponent("Block").setId(i);
            block.parent = this.Block.getChildByName("outside");
            let x,y = 0;
            if(i < 5){
                x = -284 + 142*i; y = 259;
            } 
            else if(i < 9){
                x = 284; y = 259 - (i-4)*142;
            } 
            else if(i < 13){    
                x = 284 - (i-8)*142; y = -309;
            } 
            else if(i < 16){
                x = -284; y = -309 + (i-12)*142;
            } 
            block.setPosition(x,y);
            this.outside_Array.push(block);
        }
        for(let j=3; j<12; j++){
            let block = cc.instantiate(this.kuang2_Prefab);
            block.getComponent("Block").setId(j);
            block.parent = this.Block.getChildByName("inside");
            block.setPosition(-132+j%3*132,239-parseInt(j/3 + "")*132);
            this.inside_Array.push(block);
        }
    }

    //创建关卡
    createCustom(){
        //初始化关卡配置数据
        this.level = cc.fx.GameConfig.GM_INFO.level;
        this.LevelLabel.string = (this.level+1)+"";
        this.config = cc.fx.GameConfig.LEVEL_INFO[this.level];
        if(this.level == 4 && this.guide_Level == 2) {
            this.config = cc.fx.GameConfig.LEVEL_INFO[6];
        }
        this.pass = false;
        //放正确答案和错误答案
        this.answerInsideTexture = Math.floor(Math.random()*14 + 1);
        //内圈错误答案随机
        this.insideTexture = [];
        this.outsideTexture = [];
        for(let k=0; k<14; k++){
            if((k+1) != this.answerInsideTexture){
                this.insideTexture.push(k+1);
            }
        }
        cc.fx.GameTool.shuffleArray(this.insideTexture);
        this.answerOutsideTexture = this.insideTexture[11];

        //分配正确答案和错误答案位置
        if(this.config["inside"] > 0){
            this.result += 1;
            let random = Math.random()*100;
            let arrayTemp = [0,1,2,3,5,6,7,8];
   
            if(this.config["insideType"] == 1){
                if(random >= 50) this.inside =  [0,1,2];
                else this.inside = [6,7,8];
            }
            else if(this.config["insideType"] == 2){
                if(random >= 50) this.inside =  [0,3,6];
                else this.inside = [2,5,8];
            }
            else{
                this.inside = cc.fx.GameTool.shuffleArray(arrayTemp);
                this.inside.splice(this.config["inside"],this.inside.length-this.config["inside"]);
            }
            this.answerInside = this.inside[Math.floor(Math.random()*this.inside.length)];
        }
        //分配外圈正确答案和错误答案位置
        if(this.config["outside"] > 0){
            this.result += 1;
            if(this.config["outsideType"] == 1){
                this.outside = [1,2,3,5,6,7,9,10,11,13,14,15];
            }
            else if(this.config["outsideType"] == 2){
                this.outside = [0,4,8,12];
            }
            else{
                this.outside = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
            }
            cc.fx.GameTool.shuffleArray(this.outside);
            this.answerOutside = this.outside[Math.floor(Math.random()*this.outside.length)];
            if(this.config["outside"] == 2){
                for(let j=0; j<15; j++){
                    this.outsideTexture.push(this.insideTexture[3]);
                }
            }
            else if(this.config["outside"] == 3){
                this.outsideTexture = [this.insideTexture[5],this.insideTexture[6],this.insideTexture[5],this.insideTexture[6],this.insideTexture[5]];
                for(let j=0; j<10; j++){
                    let randomTemp = Math.random()*100;
                    if(randomTemp>50) this.outsideTexture.push(this.insideTexture[5]);
                    else this.outsideTexture.push(this.insideTexture[6]);
                }
                cc.fx.GameTool.shuffleArray(this.outsideTexture);
            }
            else if(this.config["outside"] == 4){
                this.outsideTexture = [this.insideTexture[2],this.insideTexture[4],this.insideTexture[6],
                this.insideTexture[2],this.insideTexture[4],this.insideTexture[6]];
                for(let j=0; j<9; j++){
                    let randomTemp = Math.random()*100;
                    if(randomTemp<33) this.outsideTexture.push(this.insideTexture[2]);
                    else if(randomTemp<66) this.outsideTexture.push(this.insideTexture[4]);
                    else this.outsideTexture.push(this.insideTexture[6]);
                }
                cc.fx.GameTool.shuffleArray(this.outsideTexture);
            }
        }
        this.runBlock();
    }

    //块执行图片出现消失动画
    runBlock(){
        if(this.config["inside"] > 0){
            this.inside_Array[4].getComponent("Block").answerShow(this.answerInsideTexture);
            setTimeout(() => {
                let insideNumber = 0;
                for(let i=0; i<this.inside.length;i++){
                    if(this.inside[i] == this.answerInside)
                        this.inside_Array[this.inside[i]].getComponent("Block").show(true,true,this.answerInsideTexture);
                    else{
                        this.inside_Array[this.inside[i]].getComponent("Block").show(false,true,this.insideTexture[insideNumber]);
                        insideNumber += 1;
                    }
                }
            }, this.config["showTime"]*1000);

        }
        if(this.config["outside"] > 0){
            this.outside_Array[this.answerOutside].getComponent("Block").answerShow(this.answerOutsideTexture);
            if(this.config["outside"] > 1){
                let outsideNumber = 0;
                for(let i=0; i<this.outside_Array.length;i++){
                    if(i == this.answerOutside)
                        this.outside_Array[i].getComponent("Block").show(true,false,this.answerOutsideTexture);
                    else {
                        this.outside_Array[i].getComponent("Block").show(false,false,this.outsideTexture[outsideNumber]);
                        outsideNumber += 1;
                    }
                }
            }
            setTimeout(() => {
                let outsideNumber = 0;
                for(let i=0; i<this.outside_Array.length;i++){
                    if(i == this.answerOutside)
                        this.outside_Array[i].getComponent("Block").lockShow(true,false);
                    else {
                        this.outside_Array[i].getComponent("Block").lockShow(false,false);
                        outsideNumber += 1;
                    }
                }
            }, this.config["showTime"]*1000);
        }
        setTimeout(() => {
            if(!this.guide_State){
                this.startTime = cc.fx.GameTool.getTime();
                this.schedule(this.updateCountDownTime,1);
            }
                
        }, this.config["showTime"]*1000);
    }

    //正确
    openResult(result){
        this.result -= 1;
        //非引导状态
        if(!this.guide_State){
            this.flipBlock(result);
            if(this.result == 0){
                this.unschedule(this.updateCountDownTime);
                setTimeout(() => {
                    this.setData(result);
                }, 1000);
                setTimeout(() => {
                    if(cc.fx.GameConfig.GM_INFO.level < cc.fx.GameConfig.LEVEL_INFO.length-1){
                        cc.fx.GameConfig.GM_INFO.level += 1;
                        cc.director.loadScene("GameScene");
                    }
                }, 2000);
            }
        }
        //引导状态下
        else{
            if(result.result){
                this.flipBlock(result);
                setTimeout(() => {
                    if(this.level == 4 && cc.fx.GameConfig.GM_INFO.guide_Level == 2){
                        cc.director.loadScene("GameScene");
                    }
                    else this.openGuide(true);
                }, 1000);
                
            }
        }
  
    }

    //翻转形状变成问号
    flipBlock(result){
        if(result.type){
            let pos = this.changePos(true,result.id);
            if(!this.guide_State) cc.fx.GameConfig.CLICK_DATA.userChoiceInner.push(pos.x,pos.y);
            for(let i=0; i<this.inside.length;i++){
                if(this.inside[i] == this.answerInside){
                    this.inside_Array[4].getChildByName("texture").active = true;
                    this.inside_Array[4].getChildByName("texture").opacity = 255;
                    this.inside_Array[this.inside[i]].getChildByName("yes").active = true;
                    let pos = this.changePos(true,this.inside_Array[this.inside[i]].getComponent("Block")._idNumber);
                    if(!this.guide_State) cc.fx.GameConfig.CLICK_DATA.rightChoiceInner.push(pos.x,pos.y);
                }
                this.inside_Array[this.inside[i]].getComponent("Block")._touch = false;
            }
            if(result.result){
                this.addScore();
            }
        }
        else{
            let pos = this.changePos(false,result.id);
            if(!this.guide_State) cc.fx.GameConfig.CLICK_DATA.userChoiceOuter.push(pos.x,pos.y);
            for(let i=0; i<this.outside_Array.length;i++){
                this.outside_Array[i].getComponent("Block").lockHide();
                this.outside_Array[i].getChildByName("texture").active = true;
                if(i == this.answerOutside){
                    this.outside_Array[i].getChildByName("yes").active = true;
                    this.outside_Array[i].getComponent("Block").show(true,false,this.answerOutsideTexture);
                    let pos = this.changePos(false,this.outside_Array[i].getComponent("Block")._idNumber);
                    if(!this.guide_State) cc.fx.GameConfig.CLICK_DATA.rightChoiceOuter.push(pos.x,pos.y);
                }
            }
            if(result.result){
                this.addScore();
            } 
        }
        
    }

    //加分 加进度条，加星星
    addScore(){
        if(!this.guide_State){
            cc.fx.GameConfig.GM_INFO.score += 1;
            var progress = cc.fx.GameConfig.GM_INFO.score/24;
            if(progress >= 1) progress = 1;
            cc.tween(this.progress)
            .to(0.2,{fillRange:progress})
            .call(()=>{
                if(this.Top.getChildByName("star1").active == false && progress>= 0.2){
                    this.Top.getChildByName("star1").active = true;
                    this.Top.getChildByName("star1").opacity = 0; this.Top.getChildByName("star1").scale = 0.1;
                    cc.tween(this.Top.getChildByName("star1"))
                    .to(0.3,{opacity:255,scale:1.1})
                    .to(0.1,{opacity:255,scale:0.9})
                    .to(0.1,{opacity:255,scale:1})
                    .start();
                }
                if(this.Top.getChildByName("star2").active == false && progress>= 0.5){
                    this.Top.getChildByName("star2").active = true;
                    this.Top.getChildByName("star2").opacity = 0; this.Top.getChildByName("star2").scale = 0.1;
                    cc.tween(this.Top.getChildByName("star2"))
                    .to(0.3,{opacity:255,scale:1.1})
                    .to(0.1,{opacity:255,scale:0.9})
                    .to(0.1,{opacity:255,scale:1})
                    .start();
                }
                if(this.Top.getChildByName("star3").active == false && progress>= 0.8){
                    this.Top.getChildByName("star3").active = true;
                    this.Top.getChildByName("star3").opacity = 0; this.Top.getChildByName("star3").scale = 0.1;
                    cc.tween(this.Top.getChildByName("star3"))
                    .to(0.3,{opacity:255,scale:1.1})
                    .to(0.1,{opacity:255,scale:0.9})
                    .to(0.1,{opacity:255,scale:1})
                    .start();
                }
            })
            .start();
        }
    }

    //返回首页
    backScene(){
        cc.director.loadScene("LoadScene");
    }
    //重新开始
    reStart(){

    }
    //获取时间戳
    getTime(){
        var timestamp = new Date().getTime();
        return timestamp;
    }
    //获胜
    passLevel(){

    }
    //失败
    loseLevel(type){
        
    }

    changePos(type,num){
        var x = 0; var y = 0;
        //内部
        if(type){
            y = parseInt(num/3+"");
            x = num%3;
        }
        //外部
        else{
            if(num < 5){
                y=0; x=num;
            } 
            else if(num < 9){
                x=5; y=num-4;
            } 
            else if(num < 13){    
                y=4; x=12-num;
            } 
            else if(num < 16){
                x=0; y=16-num;
            } 
        }
        var jg = cc.v2(x,y);
        return jg;
    }
    //如果是倒计时 调用此方法
    updateCountDownTime () {
        if (this.countTime > 0) {
            this.countTime -= 1;
            // this.TimeLabel.string =this.countTime + "";
            this.TimeLabel.string =  cc.fx.GameTool.getTimeMargin(this.countTime);
            if(this.countTime <= 0){
                this.unschedule(this.updateCountDownTime);
                this.node.getChildByName("Mask").active = true;
                let data = {"result":false,"type":true,"id":null};
                if(this.config["inside"] > 0) cc.fx.Notifications.emit("result",data);
                let data2 = {"result":false,"type":false,"id":null};
                if(this.config["outside"] > 0) cc.fx.Notifications.emit("result",data2);
            }
        }
    }
    //上传每次操作数据
    setData(result){
        cc.fx.GameConfig.CLICK_DATA.success = result.result;
        cc.fx.GameConfig.CLICK_DATA.round = (cc.fx.GameConfig.GM_INFO.level + 1);
        cc.fx.GameConfig.CLICK_DATA.duration = new Date().getTime() - this.startTime - 1000;
        cc.fx.GameTool.setGameData();
    }

    onEnable () {
        cc.fx.Notifications.on("result", this.openResult, this);

    }
    onDisable () {
        cc.fx.Notifications.off("result", this.openResult, this);
    }
    update (dt) {

    }
}
