// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import { ryw_Event } from "../FrameWork/Event/EventEnum";
import EventMgr from "../FrameWork/Event/EventMgr";
import GameReport, { OUTTYPE } from "../FrameWork/Report/ZyZyReport";
import User from "../FrameWork/User/User";
import AppPlatform from "../FrameWork/Util/AppPlatform";
import Common from "../FrameWork/Util/Common";
import Common5 from "../Platform/th/Common5";
import TTAPI from "../Platform/tt/TTAPI";
import GameFailUI from "../Scripts/GameFailUI";
import GameSuccessUI from "../Scripts/GameSuccessUI";
import MainScene from "./MainSceneScript";

const {ccclass, property} = cc._decorator;

@ccclass
export default class Game extends cc.Component {

    @property(cc.Node)
    backNode: cc.Node = null;

    @property(cc.Node)
    prefabNode: cc.Node = null;
    
    @property(cc.Node)
    maskNode: cc.Node = null;

    @property(cc.Sprite)
    timeSpript: cc.Sprite = null;
    

    @property(cc.Label)
    titleLabel: cc.Label = null;
    @property(cc.Label)
    timeLabel: cc.Label = null;
    @property(cc.Node)
    timeNode: cc.Node = null;
    
    @property(cc.Node)
    addtimeBtn: cc.Node = null;
    
    @property(cc.Node)
    tipAdNode: cc.Node = null;
    @property(cc.Node)
    tipNoAdNode: cc.Node = null;
    @property(cc.Node)
    answerNode: cc.Node = null;
    
    @property(cc.Node)
    guizeNode: cc.Node = null;
    @property(cc.Label)
    guizeLabel: cc.Label = null;
    @property(cc.Node)
    guizeBtnNode: cc.Node = null;
    @property(cc.Node)
    guizeCloseBtnNode: cc.Node = null;

    znzTime = 15;
    targetNode = [];
    isLoading = false;
    oldScale = 1;
    tempGameConfig = null;
    allTargetNum = 0;
    finishTargetNum = 0;
    allTime = 0;
    lefTime = 0;
    isFinish = false;
    playTime = 0;
    tmpUnlockSubLevel = -1;
    finishSub = [];
    // LIFE-CYCLE CALLBACKS:

    // onLoad () {}
    public static ins: Game = null;
    isExitTip =false;
    protected onLoad(): void {
      
        Game.ins = this;
        this.oldScale = this.node.scale;
        console.log(this.oldScale);
        this.node.active = false;
        EventMgr.onEvent_custom(ryw_Event.tooltipClose,()=>{
            this.updateTishiBtn();
        },this)

        
        Common5.playMusic("bg");

        // this.node.getChildByName("mask").height = this.node.getChildByName("mask").height * this.node.width/this.node.getChildByName("mask").width ;
        // this.node.getChildByName("mask").width = this.node.width;
    }
    start () {        
        this.maskNode.getComponent(cc.Widget).updateAlignment();
        // this.prefabNode.getComponent(cc.Widget).updateAlignment();
        this.node.on(cc.Node.EventType.TOUCH_START,(event)=>{
            //console.log(event.getLocation())
            MainScene.ins.showClickEffect(event.getLocation())
        },this,true)
        
        EventMgr.onEvent_custom(ryw_Event.startTimeTick,()=>{
      
            if(Common5.selectGameInfo.isNeedTime){
                this.isFinish = false
                this.schedule(this.refreshTime,1)
            }
          
        },this)
        EventMgr.onEvent_custom(ryw_Event.game_continue,()=>{
            this.isFinish = false
            this.lefTime = Common5.selectGameInfo.timeInit;
            this.allTime = Common5.selectGameInfo.timeInit;
            this.schedule(this.refreshTime,1)
        },this)
        EventMgr.onEvent_custom(ryw_Event.stopTimeTick,()=>{
            this.stopTime();
        },this)
    }
    toolTip(){
        
    }
    closeGuize(){
        this.guizeNode.active = false;
    }
    showGui(){
        //this.guizeNode.active = true;

        EventMgr.emitEvent_custom(ryw_Event.openGuizeLayerEvent)
    }
    setGuizeText(str){
        this.guizeLabel.string = str;
    }
    showSuccess(){
        this.stopTime();
        EventMgr.emitEvent_custom(ryw_Event.finish_game);
        this.playSuccessDadian()
        User.setSuccessLevels(Common5.selectGameNum);
        Common5.getPrefabFromBundle("ZoomGame","prefab/view/GameSuccessView",null,(node)=>{
            // node.getComponent(GameFailUI).setAddTime(Common5.selectGameInfo.timeVideoAdd);
        })
 
    }
    showFail(){
        this.stopTime();
        EventMgr.emitEvent_custom(ryw_Event.finish_game);
        Common5.getPrefabFromBundle("ZoomGame","prefab/view/GameFailView",null,(node)=>{
            // node.getComponent(GameFailUI).setAddTime(Common5.selectGameInfo.timeVideoAdd);
        })

    }

    showFailFuHuo(){
        this.stopTime();
        EventMgr.emitEvent_custom(ryw_Event.finish_game);
        Common5.getPrefabFromBundle("ZoomGame","prefab/view/GameFailView",null,(node)=>{
            node.getComponent(GameFailUI).setFuhuoActive();
        })

    }

    addTick(timeTick){
        return;
        this.lefTime += timeTick;
        this.allTime += timeTick;
    }
    setTimePos(x,y){
        // this.timeNode.setPosition(x,y);
    }
    setTimeScale(scale){
        this.timeNode.scale = scale;
    }
    setTitle(title){
        this.titleLabel.string = title;
    }
    refreshTime(){
        this.playTime++;
        if (this.lefTime <=0){
            if (!this.isFinish){
                console.error("fail++====refreshTime");
                this.finishThisGame();
                EventMgr.emitEvent_custom(ryw_Event.finish_game);
                Common5.getPrefabFromBundle("ZoomGame","prefab/view/GameFailTimeOutView",null,(node)=>{
                    // node.getComponent(GameFailUI).setAddTime(Common5.selectGameInfo.timeVideoAdd);
                })
            }
        }
        else {
            this.lefTime--;
            if (this.lefTime < 10){
                Common5.playEffect("timeTick");
            }
            this.updateTimeProg();
        }
    }
    tipUnlock(subLevel){
        User.unlockWordgameAnswer(Common5.selectGameNum,subLevel,2);
        this.finishSub.push(subLevel);
        this.updateTishiBtn();

    }
    tipAd(){
        let tab = {
            onClose: (finish) => {
                if (finish) {
                    GameReport.ADReport('提示',Common5.selectGameInfo.title2,1)
                    Common5.ReportDY("inLevel", Common5.selectGameInfo.title2 + "-AD-提示");
                    if (Common.Type == 3){
                        let index = 0;
                        let answer = User.getUnlockWordgameAnswer(Common5.selectGameNum)            
                        if (answer){
                            for (let i = 0; i < Common.GameSubTipConfigs.length; i++){
                                if (answer[i]!=2){
                                    index = i;
                                    break;
                                }
                            }
                        }
                        Common.subLevel = index;
                        User.unlockWordgameAnswer(Common5.selectGameNum,index,2);
                        this.tipAdNode.active = false;
                        this.tipNoAdNode.active = true;
                        this.answerNode.active = false;
                        this.showTipAnswer();
                        return;
                    }
                    User.unlockWordgameAnswer(Common5.selectGameNum,Common.subLevel,1);
                    if (Common.Type == 1){
                        User.unlockWordgameAnswer(Common5.selectGameNum,Common.subLevel,2);
                        this.updateTishiBtn();
                    }
                    this.showTipAnswer();
                    return;
                }
                else {
                    GameReport.ADReport('提示',Common5.selectGameInfo.title2,0)
                    Common5.showTips_custom("广告未观看完");
                }
            }, onFailed: () => {
            }
        }
        AppPlatform.playVideo_custom(tab)
    }

    updateTishiBtn(){
            if (Common5.selectGameInfo.gameType != "guize"){ 
                this.guizeBtnNode.active = false; 
            }else if (Common5.selectGameInfo.gameType == "guize"){ 
                this.guizeBtnNode.active = true; 
            }
         
                   
            let answer = User.getUnlockWordgameAnswer(Common5.selectGameNum)
            if (Common.Type == 3){
                let index = -1;
                let answer = User.getUnlockWordgameAnswer(Common5.selectGameNum)            
                if (answer){
                    for (let i = 0; i < this.finishSub.length; i++){
                        if (answer[this.finishSub[i]]!=2){
                            this.tipAdNode.active = false;
                            this.tipNoAdNode.active = true;
                            this.answerNode.active = false;
                            Common.subLevel = this.finishSub[i];
                            return;
                        }
                    }
                    for (let i = 0; i < Common.GameSubTipConfigs.length; i++){                       
                        if (answer[i] == 2){
                            let finish = false;
                            for (let j = 0; j < this.finishSub.length; j++){
                                if (this.finishSub[j] == i){
                                    finish = true;
                                    break;
                                }
                            }
                            if (!finish){                                
                                this.tipAdNode.active = false;
                                this.tipNoAdNode.active = true;
                                this.answerNode.active = false;
                                Common.subLevel = this.finishSub[i];
                                return;
                            }
                        }
                    }   
                    for (let i = 0; i < Common.GameSubTipConfigs.length; i++){
                        if (answer[i]!=2){
                            index = i;
                            break;
                        }
                    }                    
                    if (index == -1){                           
                        this.tipAdNode.active = false;
                        this.tipNoAdNode.active = true;
                        this.answerNode.active = false;
                    }
                    else {
                        this.tipAdNode.active = true;
                        this.tipNoAdNode.active = false;
                        this.answerNode.active = false;
                    }
                    if (Common.subLevel == this.tmpUnlockSubLevel){

                    }
                }
                else {
                    this.tipAdNode.active = true;
                    this.tipNoAdNode.active = false;
                    this.answerNode.active = false;
                }
                return;
            }
            
            if (answer){
                let answerIndex = answer[Common.subLevel];

                console.log(answerIndex, Common.subLevel, 'answerIndex+++++++++++++======')
                if (answerIndex == 1){                
                    this.tipAdNode.active = false;
                    this.tipNoAdNode.active = true;
                    this.answerNode.active = false;
                }
                else if(answerIndex == 2) {
                    this.tipAdNode.active = false;
                    this.tipNoAdNode.active = false;
                    this.answerNode.active = true;
                }else{
                    this.tipAdNode.active = true;
                    this.tipNoAdNode.active = false;
                    this.answerNode.active = false; 
                }
            }     
            else{
                this.tipAdNode.active = true;
                this.tipNoAdNode.active = false;
                this.answerNode.active = false;
            }
        
    }
    
    showTipAnswer(){
        Common5.getPrefabFromBundle("ZoomGame","prefab/view/tipPrefab",null,(node)=>{
        })
    }
    finishThisGame(){
        // this.reset();
        this.isFinish = true;
        // this.node.scale = 0;
    }
    updateTimeProg(){
        this.timeSpript.fillRange = this.lefTime/this.allTime;
        let secondStr = "";
        let second = this.lefTime % 60;
        if (second < 10){
            secondStr = "0" + second;
        }
        else {
            secondStr = second.toString();
        }
        this.timeLabel.string = Math.floor(this.lefTime/60) + ":" + secondStr;
    }
    reset(){
        TTAPI.startRecord_custom();
        Common.SpeTip = "";
        MainScene.ins.levelNode.active = false;
        if (Common5.selectGameInfo.gameTitle && Common5.selectGameInfo.gameTitle!= ""){
            this.titleLabel.string = Common5.selectGameInfo.gameTitle;
            this.titleLabel.node.parent.active = true;
        }
        else {
            this.titleLabel.node.parent.active = false;
        }
        if (Common5.selectGameInfo.isNeedTime){
            this.timeNode.active = true;
            this.addtimeBtn.active = true;
            this.lefTime = Common5.selectGameInfo.timeInit;
            this.allTime = Common5.selectGameInfo.timeInit;
            console.log(this.lefTime,this.allTime)
            this.updateTimeProg();
            this.resetTime();
        }else {
            this.timeNode.active = false;
            this.addtimeBtn.active = false;
            
        }
        this.node.active = true;
        this.updateTishiBtn();
        this.finishSub = [];
        // this.showFail();
        this.preLoadNext();
    }
    preLoadNext(){
        let nextLevel = -1;
        for (let i = 0; i < Common5.gameConfig.GameAllType[Common5.curWordGameType].Levels.length; i++){
            let level = Common5.gameConfig.GameAllType[Common5.curWordGameType].Levels[i];
            if (level == Common5.selectGameNum){
                if (i < (Common5.gameConfig.GameAllType[Common5.curWordGameType].Levels.length-1)){
                    nextLevel = Common5.gameConfig.GameAllType[Common5.curWordGameType].Levels[i+1];
                    break;
                }
            }
        }
        if (nextLevel!=-1){   
            console.log(Common5.gameConfig.zmGameConfig[nextLevel].bundle);
                 
            let bundle = cc.assetManager.loadBundle(Common5.gameConfig.zmGameConfig[nextLevel].bundle,(err,bundle)=>{                
                bundle.load(Common5.gameConfig.zmGameConfig[nextLevel].bundle, cc.Prefab, () => {
                    console.log(nextLevel + "  preloadSuccess!")
                })
            })
            if (Common5.gameConfig.zmGameConfig[nextLevel].subbundle && Common5.gameConfig.zmGameConfig[nextLevel].subbundle!=""){                
                let subbundle = cc.assetManager.loadBundle(Common5.gameConfig.zmGameConfig[nextLevel].subbundle,(err,subbundle)=>{                
                    subbundle.load(Common5.gameConfig.zmGameConfig[nextLevel].suburl, cc.Prefab, () => {
                        console.log(nextLevel + "  subbundle preloadSuccess!")
                    })
                })
            }
            // cc.assetManager.getBundle(Common5.gameConfig.zmGameConfig[nextLevel].bundle);
        }
    }
    resetTime(){
        this.isFinish = false
        this.schedule(this.refreshTime,1)
    }
    stopTime(){
        this.unschedule(this.refreshTime);
    }
    clickBack(event,isReport){
        // this.prefabNode.removeAllChildren();
        // this.node.active = false;
        if(this.isExitTip){
            return
        }
        this.isExitTip = true
        Common5.getPrefabFromBundle("ZoomGame","prefab/view/ExitTip",null, ()=>{
            this.scheduleOnce(()=>{
                this.isExitTip = false
            },0.1)
        });
    }

    clickBackTimeOut(event,isReport){
        // this.prefabNode.removeAllChildren();
        // this.node.active = false;
        Common5.getPrefabFromBundle("ZoomGame","prefab/view/GameFailView");
    }

    exitGame(){
        console.log("1111")
        this.prefabNode.destroyAllChildren();
        this.prefabNode.removeAllChildren();
        this.node.active = false;
        MainScene.ins.levelNode.active = true;
        this.stopTime();
        Common5.stopMusic();
        this.scheduleOnce(()=>{
            Common5.playMusic("bg");
        },0.1)
       
    }
    setAnswerHide(){
        
    }
    addtimeClick(){
        Common5.playEffect("ui");
       
        let tab = {
            onClose: (finish) => {
                if (finish) {
                    GameReport.ADReport('加时',Common5.selectGameInfo.title2,1)

                    if(Common5.selectGameInfo){
                        Common5.ReportDY("inLevel", Common5.selectGameInfo.title2 + "-AD-加时");

                    }
                
                    this.lefTime = this.lefTime +Common5.selectGameInfo.timeVideoAdd;
                    this.allTime += Common5.selectGameInfo.timeVideoAdd;
                    EventMgr.emitEvent_custom(ryw_Event.addTimeSucc);
                    return;
                }
                else {
                    GameReport.ADReport('加时',Common5.selectGameInfo.title2,0)
                    // this.node.removeFromParent();
                    Common5.showTips_custom("广告未观看完");
                }
            }, onFailed: () => {
            }
        }
        AppPlatform.playVideo_custom(tab)
    }


    setGameTitle(gameTitle){
        this.titleLabel.node.parent.active = true;
        this.titleLabel.string = gameTitle;
    }


    playSuccessDadian() {
        let title = Common5.selectGameInfo.title2

        console.log(title + "-成功通关")
        Common5.ReportDY("inLevel", title + "-成功通关");

    }
    onRestartCallFunc(){
        if (Common5.selectGameInfo.subbundle !="" && Common5.selectGameInfo.subbundle != undefined){
                
            let subbundle = cc.assetManager.loadBundle(Common5.selectGameInfo.subbundle,(err,subbundle)=>{                
                cc.assetManager.loadBundle(Common5.selectGameInfo.bundle, function (err: Error, bundle: cc.AssetManager.Bundle) {
                    MainScene.ins.GameNode.getChildByName("mask").getChildByName("prefabNode").destroyAllChildren();
                    MainScene.ins.GameNode.getChildByName("mask").getChildByName("prefabNode").removeAllChildren();
                    Common5.getPrefabFromBundle(Common5.selectGameInfo.bundle,Common5.selectGameInfo.url,MainScene.ins.GameNode.getChildByName("mask").getChildByName("prefabNode"),(prefab)=>{
                        // prefab.width = Game.ins.maskNode.width;
                        // prefab.height = Game.ins.maskNode.width;
                        if (Common5.selectGameNum != 0){                        
                            User.setFirstIn(false);
                        }
                        
                        if (Common5.selectGameInfo.isTer){
                            Common5.getPrefabFromBundle("ZoomGame","prefab/view/TerrTip");
                        }
                        User.setLeveNum_custom(Common5.selectGameNum);
                        // prefab.scale = Game.ins.maskNode.width/prefab.width;
                        // prefab.setPosition(0,0);
                        // console.log("prefab.width",prefab.width,prefab.height,prefab.position,MainScene.ins.GameNode.getChildByName("mask").getChildByName("prefabNode").position)
                        Common5.hideTips_custom();
                        Game.ins.reset();
                        MainScene.ins.isLoading = false;
                    })
                });
            })
        }
        else {
            
            cc.assetManager.loadBundle(Common5.selectGameInfo.bundle, function (err: Error, bundle: cc.AssetManager.Bundle) {
                MainScene.ins.GameNode.getChildByName("mask").getChildByName("prefabNode").destroyAllChildren();
                MainScene.ins.GameNode.getChildByName("mask").getChildByName("prefabNode").removeAllChildren();
              
                Common5.getPrefabFromBundle(Common5.selectGameInfo.bundle,Common5.selectGameInfo.url,MainScene.ins.GameNode.getChildByName("mask").getChildByName("prefabNode"),(prefab)=>{
                    // prefab.width = Game.ins.maskNode.width;
                    // prefab.height = Game.ins.maskNode.width;
                    if (Common5.selectGameNum != 0){                        
                        User.setFirstIn(false);
                    }
                    
                    if (Common5.selectGameInfo.isTer){
                        Common5.getPrefabFromBundle("ZoomGame","prefab/view/TerrTip");
                    }
                    User.setLeveNum_custom(Common5.selectGameNum);
                    // prefab.scale = Game.ins.maskNode.width/prefab.width;
                    // prefab.setPosition(0,0);
                    // console.log("prefab.width",prefab.width,prefab.height,prefab.position,MainScene.ins.GameNode.getChildByName("mask").getChildByName("prefabNode").position)
                    Common5.hideTips_custom();
                    Game.ins.reset();
                    MainScene.ins.isLoading = false;
                })
            });
        }
    }

    // update (dt) {}
}