import { asyncDelay, onHomeworkFinish } from "../script/util";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent";
import levelItem from "../script/levelItem";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {

    @property(cc.Label)
    title:cc.Label = null;
    canTouch: boolean = true;
    @property(cc.Node)
    startNode:cc.Node = null;
    level: number;
    @property(cc.Prefab)
    titleCake: cc.Prefab;
    @property(cc.Node)
    titleCakeNode: cc.Node;
    titleCakeNodeArr: Array<levelItem>;
    resultArr:Array<number>;
    @property(cc.Node)
    cakeMoveNode:cc.Node;
    @property(cc.Node)
    cakeNode:cc.Node;
    @property(cc.Node)
    chooseNode:cc.Node;
    @property(cc.Node)
    candleNode:cc.Node;
    @property(cc.Node)
    musicNode:cc.Node;
    isCanTiming:boolean = false;
    gameStage:number;
    @property(cc.Prefab)
    choosePrefab:cc.Prefab;
    @property(dragonBones.ArmatureDisplay)
    chooseRightDragon : dragonBones.ArmatureDisplay=null;
    @property(cc.Label)
    completeWord:cc.Label;
    @property(cc.Node)
    suiCake:cc.Node;
    @property(cc.Node)
    posNode:cc.Node;
    rightQuestion:number = 0;
    @property(cc.Node)
    endNode:cc.Node;
    @property(cc.Node)
    okBtn:cc.Node;
    @property(cc.Node)
    whiteNode:cc.Node;
    @property(dragonBones.ArmatureDisplay)
    endNodeDragon:dragonBones.ArmatureDisplay;
    @property(dragonBones.ArmatureDisplay)
    excellentDragon:dragonBones.ArmatureDisplay;
    @property(cc.Node)
    nicetryNode:cc.Node;
    @property(dragonBones.ArmatureDisplay)
    allWinEnd:dragonBones.ArmatureDisplay;
    @property(cc.Node)
    endNice:cc.Node;
    @property(cc.Node)
    endCome:cc.Node;

    addPreloadImage() {
        // TODO 根据自己的配置预加载图片资源
        this._imageResList.push({ url: this.data.pic_url });
        this._imageResList.push({ url: this.data.pic_url_2 });
    }

    addPreloadAudio() {
        // TODO 根据自己的配置预加载音频资源
        this._audioResList.push({ url: this.data.audio_url });
    }

    addPreloadAnima() {

    }

    onLoadEnd() {
        // TODO 加载完成后的逻辑写在这里, 下面的代码仅供参考
        // this.initData();
        // this.initView();
        // this.initListener();
        this.initFirstView();
    }

    onClickStartGame(){
        if (this.canTouch) {
            this.canTouch = false;
            this.startNode.stopAllActions();
            this.startNode.opacity = 255;
            cc.tween(this.startNode)
                .to(0.5, { opacity: 0 })
                .call(() => {
                    this.startNode.active = false;
                    this.createTitleView();
                    this.startGame();
                })
                .start()
        }
    }

    startGame(){
        this.initQuestionView();
        this.initAnswerView();
        this.moveInCakeNode();
        this.moveInChooseNode();
    }

    createTitleView(){
        if(this.titleCakeNodeArr.length != 0){
            for(let i = 0; i < this.titleCakeNodeArr.length; ++i){
                this.titleCakeNodeArr[i].init(i);
                this.titleCakeNodeArr[i].updateChooseView(this.level);
            }

            return;
        }

        for(let i = 0; i < this.data.questions.length; ++i)
        {
            let item = cc.instantiate(this.titleCake);
            let script = item.getComponent("levelItem");
            script.init(i);
            script.updateChooseView(this.level);
            this.titleCakeNode.addChild(item);
            this.titleCakeNodeArr.push(script);
        }
    }

    initQuestionView(){
        let question = this.data.questions[this.level - 1];
        var reg = new RegExp(question.rightLetter);
        let firstWords = question.text.replace(reg,"");
        
        for(let i = 0; i < 5; ++ i)
        {
            if(i < firstWords.length){
                let cake = this.cakeNode.getChildByName("cake" + (i + 1));
                cake.active = true;
                cake.getChildByName("txt").getComponent(cc.Label).string = firstWords[i];
            }
            else{
                this.cakeNode.getChildByName("cake" + (i + 1)).active = false;
            }
        }

        this.completeWord.string = question.text;
    }

    initAnswerView(){
        this.chooseNode.children[0].getComponent("chooseItem").initView(this.data.questions[this.level - 1].rightLetter);
        this.chooseNode.children[1].getComponent("chooseItem").initView(this.data.questions[this.level - 1].wrongLetter);
    }

    initFirstView(){
        this.level = 1;
        this.titleCakeNodeArr = new Array<levelItem>();
        this.resultArr = new Array<number>();
        this.title.string = this.data.title;
    }

    moveInChooseNode(){
        cc.tween(this.chooseNode)
            .to(0.5, { x: cc.winSize.width/2 })
            .start();
    }

    moveOutChooseNode(){
        cc.tween(this.chooseNode)
            .to(0.5, { x: cc.winSize.width/2 + 400})
            .start();
    }

    moveInCakeNode(){
        this.playLocalAudio("effect_inScene");

        cc.tween(this.cakeMoveNode)
            .to(0.5, { x: 0 })
            .call(()=>{
                this.playAudioByUrl(this.data.questions[this.level - 1].audio, () => {
                    this.moveInMusicBtn();
                    this.moveInCandleNode();
                    this.showGreenCandle();
                    this.gameStage = 1;
                    this.isCanTiming = true;
                })
            })
            .start();
    }

    moveOutCakeNode(cb = null){
        cc.tween(this.cakeMoveNode)
            .to(0.5, { x: -cc.winSize.width/2 - 200 })
            .call(()=>{
                if(cb){
                    cb();
                }
            })
            .start();
    }

    moveInCandleNode(cb = null){
        cc.tween(this.candleNode)
            .to(0.3, { x: -cc.winSize.width/2 + 100 })
            .call(()=>{
                if(cb){
                    cb();
                }
            })
            .start();
    }

    moveOutCandleNode(){
        cc.tween(this.candleNode)
            .to(0.3, { x: -cc.winSize.width/2 - 100 })
            .start();
    }

    moveInMusicBtn(){
        cc.tween(this.musicNode)
            .to(0.3, { x: cc.winSize.width/2 - 100 })
            .start();
    }

    moveOutMusicBtn(){
        cc.tween(this.musicNode)
            .to(0.3, { x: cc.winSize.width/2 + 100 })
            .start();
    }

    moveInPlane(){
        cc.tween(this.endNode)
            .to(0.3, { y: this.cakeMoveNode.position.y })
            .call(()=>{
                let pos = this.cakeMoveNode.position;
                pos.x = cc.winSize.width / 2 + 200;
                this.cakeMoveNode.position = pos;

                this.playDragon();
                this.moveInCandleNode();
                this.showRedCandle();
                this.moveInOkBtn();
                this.startTalking();
                this.gameStage = 2;
                this.isCanTiming = true;
            })
            .start();
    }

    moveOutPlane(){
        cc.tween(this.endNode)
            .to(0.3, { x: -cc.winSize.width / 2 - 400 })
            .call(()=>{
                this.endNode.position = new cc.Vec3(0, cc.winSize.height / 2 + 400, 0);
                this.nextGame();
            })
            .start();
    }

    moveInEndPlane(){
        cc.tween(this.endNode)
            .to(0.3, { y: this.cakeMoveNode.position.y })
            .call(()=>{
                this.gameEnd();
            })
            .start();
    }

    moveOutEndPlane(){
        cc.tween(this.endNode)
            .to(0.3, { x: -cc.winSize.width / 2 - 400 })
            .call(()=>{
                this.level = 1;
                this.endNode.position = new cc.Vec3(0, cc.winSize.height / 2 + 400, 0);
                this.canTouch = true;
                this.startNode.active = true;
                this.startNode.opacity = 255;
            })
            .start();
    }

    moveInOkBtn(){
        cc.tween(this.okBtn)
            .to(0.3, { x: cc.winSize.width / 2 - 100 })
            .start();
    }

    moveOutOkBtn(){
        cc.tween(this.okBtn)
            .to(0.3, { x: cc.winSize.width / 2 + 200 })
            .start();
    }

    showWhiteNode(){

        this.whiteNode.opacity = 0;

        cc.tween(this.whiteNode)
            .to(0.3, { opacity: 255 })
            .start()
    }

    hideWhiteNode(){
        cc.tween(this.whiteNode)
            .to(0.3, { opacity: 0 })
            .start()
    }

    showNicetry(){
        cc.tween(this.nicetryNode)
                .to(0.3, { y: -100 })
                .to(0.1, { y: 0 })
                .delay(1)
                .to(0.3, { y: -cc.winSize.height / 2 - 300})
                .call(() => {
                    this.nicetryNode.position = new cc.Vec3(0,cc.winSize.height/2 + 300,0);
                    this.hideWhiteNode();
                    this.moveOutPlane();
                })
                .start();
    }

    showEndNice(){
        cc.tween(this.endNice)
                .to(0.3, { y: -100 })
                .to(0.1, { y: 0 })
                .delay(1)
                .to(0.3, { y: -cc.winSize.height / 2 - 500})
                .call(() => {
                    this.endNice.position = new cc.Vec3(0,cc.winSize.height/2 + 500,0);
                    this.moveOutEndPlane();
                })
                .start();
    }

    showEndCome(){
        cc.tween(this.endCome)
                .to(0.3, { y: -100 })
                .to(0.1, { y: 0 })
                .delay(1)
                .to(0.3, { y: -cc.winSize.height / 2 - 500})
                .call(() => {
                    this.endCome.position = new cc.Vec3(0,cc.winSize.height/2 + 500,0);
                    this.moveOutEndPlane();
                })
                .start();
    }

    showGreenCandle(){
        this.candleNode.getChildByName("greenCandle").active = true;
        this.candleNode.getChildByName("redCandle").active = false;

        this.candleNode.getChildByName("greenCandle").getComponent("candle").init();
    }

    showRedCandle(){
        this.candleNode.getChildByName("greenCandle").active = false;
        this.candleNode.getChildByName("redCandle").active = true;

        this.candleNode.getChildByName("redCandle").getComponent("candle").init();
    }

    chooseQuestion(str: string, pos: cc.Vec3){
        this.isCanTiming = false;

        if(str == this.data.questions[this.level - 1].rightLetter){
            this.chooseRight(pos);
        }else{
            this.chooseWrong(pos);
        }
    }

    updateCakeRightWords(){
        let sumWord = this.data.questions[this.level - 1].text;

        for(let i = 0; i < 5; ++ i)
        {
            if(i < sumWord.length){
                let cake = this.cakeNode.getChildByName("cake" + (i + 1));
                cake.active = true;
                cake.getChildByName("txt").getComponent(cc.Label).string = sumWord[i];
            }
            else{
                this.cakeNode.getChildByName("cake" + (i + 1)).active = false;
            }
        }
    }

    chooseRight(pos: cc.Vec3){

        let item = cc.instantiate(this.choosePrefab);
        this.node.addChild(item);
        item.getChildByName("choose").active = true;
        item.position = this.node.convertToNodeSpaceAR(pos);

        let rightWord = this.data.questions[this.level - 1].rightLetter;
        let sumWord = this.data.questions[this.level - 1].text;

        let index = sumWord.indexOf(rightWord);

        let cake = this.cakeNode.getChildByName("cake" + (index + 1));
        let pos1 = this.node.convertToNodeSpaceAR(cake.convertToWorldSpaceAR(cc.v2(0,0)));
        let endPos = cc.v3(pos1.x, pos1.y, 0);

        cc.tween(item)
            .to(0.5, {position: endPos})
            .call(()=>{
                item.destroy();
                this.updateCakeRightWords();
                this.showWinCandle();
            })
            .start();
    }

    showWinCandle(){
        this.playLocalAudio("effect_chooseTrue");

        let index = this.data.questions[this.level - 1].text.length;
        this.chooseRightDragon.node.position = this.cakeNode.getChildByName("cake" + index).position ;
        this.chooseRightDragon.node.active = true;
        this.chooseRightDragon.playAnimation("newAnimation",1);

        this.moveOutCandleNode();
        this.moveOutChooseNode();
        this.moveOutMusicBtn();

        this.scheduleOnce(()=>{
            this.moveInPlane();
        },0.3);
    }

    chooseWrong(pos: cc.Vec3){
        let item = cc.instantiate(this.choosePrefab);
        this.node.addChild(item);
        item.position = this.node.convertToNodeSpaceAR(pos);

        cc.tween(item)
        .to(0.3, {position: this.posNode.getChildByName("dropCakePos").position})
        .call(()=>{
            item.destroy();
            this.suiCake.active = true;
            this.moveOutCandleNode();
            this.moveOutChooseNode();
            this.moveOutMusicBtn();
            this.moveOutCakeNode(()=>{
                this.suiCake.active = false;
                let pos = this.cakeMoveNode.position;
                pos.x = cc.winSize.width / 2 + 200;
                this.cakeMoveNode.position = pos;
                this.nextGame();
            })

            this.titleCakeNodeArr[this.level - 1].updateEndView(true);
        })
        .start();

        this.playLocalAudio("effect_wrong");
    }

    nextGame(){
        this.chooseRightDragon.node.active = false;

        this.scheduleOnce(()=>{
            if(this.level < this.data.questions.length){
                this.level++;
                this.titleCakeNodeArr[this.level - 1].updateChooseView(this.level);
                this.startGame();
            }else{
                this.moveInEndPlane();    
            }
        },0.5);
        
    }

    playDragon() {
        this.endNodeDragon.node.active = true;
        let dragonBoneData = this.data.questions[this.level - 1].dragonBoneData;
        this.getDragonBone(this.endNodeDragon, dragonBoneData.texPngData.url, dragonBoneData.skeJsonData.url, dragonBoneData.texJsonData.url)
    }

    onPlaneClick(){
        this.endNodeDragon.node.active = true;
        this.endNodeDragon.playAnimation('newAnimation', 1);
    }

    reviewSuccess(){
        this.rightQuestion += 1;
        this.excellentDragon.node.active = true;
        this.excellentDragon.playAnimation('newAnimation', 1);
        this.playLocalAudio("excellent");
        this.titleCakeNodeArr[this.level - 1].updateEndView(false);

        this.scheduleOnce(()=>{
            this.excellentDragon.node.active = false;
            this.hideWhiteNode();
            this.moveOutPlane();
        },0.3)

        console.log("答对的题目数量" + this.rightQuestion);
    }

    reviewFail(){
        this.playLocalAudio("nicetry");
        this.titleCakeNodeArr[this.level - 1].updateEndView(true);
        this.showNicetry();
    }

    startTalking() {
        // if ((<any>window).courseware && (<any>window).courseware.stopTest) {
        //     (<any>window).courseware.startTest(this.data.questions[this.level - 1].text);
        // }

        window['courseware'].startTest(this.data.questions[this.level - 1].text);
    }

    stopTalking() {
        this.endNodeDragon.node.active = false;
        this.isCanTiming = false;
        this.moveOutCandleNode();
        this.moveOutOkBtn();
        this.showWhiteNode();
      
        window['courseware'].stopTest((res) =>{
            res = JSON.parse(res);
            if (res.result && res.result.overall >= 80) {
                this.reviewSuccess();
            } else {
                this.reviewFail();
            }
        })
        // let timeout = false
        // if ((<any>window).courseware && (<any>window).courseware.stopTest) {
        //         this.scheduleOnce(()=>{
        //             timeout = true;
        //             this.reviewFail();
        //         },3);
        //         (<any>window).courseware.stopTest((res) => {
        //             if(!timeout)
        //             {
        //                 this.unscheduleAllCallbacks();
        //                 res = JSON.parse(res)
        //                 if (res.result && res.result.overall >= 80) {
        //                     this.reviewSuccess();
        //                 } else {
        //                     this.reviewFail();
        //                 }
        //             }
        //         })
        // } else {
        //    this.reviewFail();
        // }
    }

    playLocalAudio(audioName: string){
        const audio = cc.find(`Canvas/res/audio/${audioName}`).getComponent(cc.AudioSource);
        return new Promise((resolve, reject) => {
            const id = cc.audioEngine.playEffect(audio.clip, false);
            cc.audioEngine.setFinishCallback(id, () => {
                resolve(id);
            });
        })
    }

    onOkBtnClick(){
        this.stopTalking();
    }

    onClickMusic() {
        this.musicNode.getComponent(cc.Button).interactable = false
        let animation=this.musicNode.getComponent(cc.Animation);
        animation.play("musicing");

        this.playAudioByUrl(this.data.questions[this.level - 1].audio, () => {
            this.musicNode.getComponent(cc.Button).interactable = true
            animation.stop("musicing");
        })
    }

    gameEnd(){
        console.log("答对的题目数量" + this.rightQuestion);

        if(this.rightQuestion >= this.data.questions.length){
            this.allWinEnd.node.active = true;
            this.allWinEnd.playAnimation('newAnimation', 1);
            this.playLocalAudio("effect_allWin");

            this.scheduleOnce(()=>{
                this.allWinEnd.node.active = false;
                this.moveOutEndPlane();
            },0.5)
        }
        else if(this.rightQuestion >= this.data.questions.length * 0.6){
            this.playLocalAudio("effect_nicetry");
            this.showEndNice();
        }else{
            this.showEndCome();
            this.playLocalAudio("effect_end");
        }

        this.rightQuestion = 0;
    }

    // _cantouch = null;
    // initData() {
    //     // 所有全局变量 默认都是null 
    //     this._cantouch = true;
    // }

    // initView() {
    //     this.initBg();
    //     this.initPic();
    //     this.initBtn();
    //     this.initIcon();
    // }

    // initBg() {
    //     const bgNode = cc.find('Canvas/bg');
    //     bgNode.scale = this._mapScaleMax;
    // }

    // pic1 = null;
    // pic2 = null;
    // initPic() {
    //     const canvas = cc.find('Canvas');
    //     const maxW = canvas.width * 0.7;

    //     this.getSprNodeByUrl(this.data.pic_url, (sprNode) => {
    //         const picNode1 = sprNode;
    //         picNode1.scale = maxW / picNode1.width;
    //         picNode1.baseX = picNode1.x;
    //         canvas.addChild(picNode1);
    //         this.pic1 = picNode1;

    //         const labelNode = new cc.Node();
    //         labelNode.color = cc.Color.YELLOW;
    //         const label = labelNode.addComponent(cc.Label);
    //         label.string = this.data.text;
    //         label.fontSize = 60;
    //         label.lineHeight = 60;
    //         label.font = cc.find('Canvas/res/font/BRLNSDB').getComponent('cc.Label').font;
    //         picNode1.addChild(labelNode);
    //     });

    //     this.getSprNodeByUrl(this.data.pic_url_2, (sprNode) => {
    //         const picNode2 = sprNode;
    //         picNode2.scale = maxW / picNode2.width;
    //         canvas.addChild(picNode2);
    //         picNode2.x = canvas.width;
    //         picNode2.baseX = picNode2.x;
    //         this.pic2 = picNode2;

    //         const labelNode = new cc.Node();
    //         const label = labelNode.addComponent(cc.RichText);
    //         const size = 60
    //         label.font = cc.find('Canvas/res/font/BRLNSDB').getComponent(cc.Label).font;
    //         label.string = `<outline color=#751e00 width=4><size=${size}><color=#ffffff>${this.data.text}</color></size></outline>`
    //         label.lineHeight = size;
    //         picNode2.addChild(labelNode);
    //     });

    // }

    // initIcon() {
    //     const iconNode = this.getSprNode('icon');
    //     iconNode.zIndex = 5;
    //     iconNode.anchorX = 1;
    //     iconNode.anchorY = 1;
    //     iconNode.parent = cc.find('Canvas');
    //     iconNode.x = iconNode.parent.width / 2 - 10;
    //     iconNode.y = iconNode.parent.height / 2 - 10;

    //     iconNode.on(cc.Node.EventType.TOUCH_START, () => {
    //         this.playAudioByUrl(this.data.audio_url);
    //     })
    // }

    // curPage = null;
    // initBtn() {

    //     this.curPage = 0;
    //     const bottomPart = cc.find('Canvas/bottomPart');
    //     bottomPart.zIndex = 5; // 提高层级

    //     bottomPart.x = bottomPart.parent.width / 2;
    //     bottomPart.y = -bottomPart.parent.height / 2;

    //     const leftBtnNode = bottomPart.getChildByName('btn_left');
    //     //节点中添加了button组件 则可以添加click事件监听
    //     leftBtnNode.on('click', () => {
    //         if (!this._cantouch) {
    //             return;
    //         }
    //         if (this.curPage == 0) {
    //             return;
    //         }
    //         this.curPage = 0
    //         this.leftMove();

    //         this.playLocalAudio('btn');
    //     })

    //     const rightBtnNode = bottomPart.getChildByName('btn_right');
    //     //节点中添加了button组件 则可以添加click事件监听
    //     rightBtnNode.on('click', () => {
    //         if (!this._cantouch) {
    //             return;
    //         }
    //         if (this.curPage == 1) {
    //             return;
    //         }

    //         this.curPage = 1
    //         this.rightMove();

    //         // 游戏结束时需要调用这个方法通知系统作业完成
    //         onHomeworkFinish();

    //         this.playLocalAudio('btn');
    //     })
    // }

    // leftMove() {
    //     this._cantouch = false;
    //     const len = this.pic1.parent.width;
    //     cc.tween(this.pic1)
    //         .to(1, { x: this.pic1.baseX }, { easing: 'cubicInOut' })
    //         .start();

    //     cc.tween(this.pic2)
    //         .to(1, { x: this.pic2.baseX }, { easing: 'cubicInOut' })
    //         .call(() => {
    //             this._cantouch = true;
    //         })
    //         .start();
    // }

    // rightMove() {
    //     this._cantouch = false;
    //     const len = this.pic1.parent.width;
    //     cc.tween(this.pic1)
    //         .to(1, { x: this.pic1.baseX - len }, { easing: 'cubicInOut' })
    //         .start();

    //     cc.tween(this.pic2)
    //         .to(1, { x: this.pic2.baseX - len }, { easing: 'cubicInOut' })
    //         .call(() => {
    //             this._cantouch = true;
    //         })
    //         .start();
    // }
    update (dt) {
        if(this.isCanTiming){
            if(this.gameStage == 1){
                let sumTime = this.data.questions[this.level - 1].choosewaitTime;
                let offset = 333 / sumTime * dt;
                let script = this.candleNode.getChildByName("greenCandle").getComponent("candle");
                script.changHeight(offset);

                if(script.isTimeEnd()){
                    this.isCanTiming = false;
                    this.moveOutCandleNode();
                    this.moveOutChooseNode();
                    this.moveOutMusicBtn();
                    this.moveOutCakeNode(()=>{
                        this.suiCake.active = false;
                        let pos = this.cakeMoveNode.position;
                        pos.x = cc.winSize.width / 2 + 200;
                        this.cakeMoveNode.position = pos;
                        this.nextGame();
                    })
                }
            }
            else if(this.gameStage == 2){
                let sumTime = this.data.questions[this.level - 1].choosewaitTime;
                let offset = 333 / sumTime * dt;
                let script = this.candleNode.getChildByName("redCandle").getComponent("candle");
                script.changHeight(offset);

                if(script.isTimeEnd()){
                    this.stopTalking();
                }
            }
        }

    }


    // initListener() {

    // }
}
