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

const { ccclass, property } = cc._decorator;

@ccclass
export default class cake_class_1 extends MyCocosSceneComponent {
    // property()
    @property
    canTouch: boolean = true;
    @property(stickers)
    stickers: stickers = null
    @property(cc.Node)
    candle1: cc.Node = null
    @property(cc.Button)
    musicBtn: cc.Button = null
    @property(cc.SpriteFrame)
    musicIcon: cc.SpriteFrame = null
    spriteFrame
    @property(cc.Node)
    candle2: cc.Node = null
    @property(cc.Node)
    redBtnN: cc.Node = null
    questionIndex: number = 0;
    answerList = [];
    @property(cc.Prefab)
    panel: cc.Prefab = null
    nowPanel = null
    nextPanel = null
    answerTimeOut = null;
    talkTimeOut = null;
    answering: boolean = false;
    talking: boolean = false;


   
    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 });
    }
    getQuestionData() {
        return this.data.questions[this.questionIndex];
    }

    addPreloadAnima() {

    }
    onTouchStart() {
        // this.playLocalAudio("btn")
        if (this.canTouch) {
            this.canTouch = false;
            let bg2N = this.node.getChildByName("bg2");
            bg2N.stopAllActions();
            bg2N.opacity = 255;
            cc.tween(bg2N)
                .to(0.5, { opacity: 0 })
                .call(() => {
                    bg2N.active = false;
                    this.startGame();
                })
                .start()
        }
    }

    initCandle1() {
        this.candle1.x = -850
        let candleS = this.candle1.getComponent("candle")
        let maskNode = this.candle1.getChildByName("mask");
        candleS.dragon1.node.active = true;
        maskNode.height = this.candle1.height = 333
        candleS.dragon3.node.active = false;
    }
    initCandle2() {
        this.candle2.x = -850
        let maskNode = this.candle2.getChildByName("mask");
        maskNode.height = this.candle2.height = 333
        let candleS = this.candle2.getComponent("candle")
        candleS.dragon1.node.active = true;
        candleS.dragon3.node.active = false;
    }
    moveInCandle2() {
        this.initCandle2();
        this.playLocalAudio("in")
        cc.tween(this.candle2)
            .to(0.3, { x: -550 })
            .start();
    }
    moveInCandle1() {
        this.initCandle1();
        this.playLocalAudio("in")
        cc.tween(this.candle1)
            .to(0.3, { x: -550 })
            .start();
    }
    moveOutCandle1(cb = null) {
        cc.tween(this.candle1)
            .to(0.3, { x: -850 })
            .call(() => {
                if (cb) cb();
            })
            .start();
    }
    moveOutCandle2() {
        cc.tween(this.candle2)
            .to(0.3, { x: -850 })
            .start();
    }
    initMusicBtn() {
        this.musicBtn.node.x = 850;
        this.musicBtn.interactable = true;
    }
    initRedBtn() {
        this.redBtnN.x = 850;
    }
    startGame() {
        this.answerList[this.questionIndex] = 0;
        this.initUi();
        this.showPanel();
    }
    showPanel() {
        if (!this.nowPanel) this.nowPanel = this.addPanel();
        cc.tween(this.nowPanel.node)
            .to(0.5, { x: 0 })
            .call(() => {
                this.updateUi();
                this.playAudioByUrl(this.data.questions[this.questionIndex].audio, () => {
                    this.answering = true;
                    this.answerTimeOut = setTimeout(() => {
                        this.changeFalse(true)
                    }, this.data.questions[this.questionIndex].choosewaitTime * 1000)
                    this.initMusicBtn();
                    cc.tween(this.musicBtn.node)
                        .to(0.3, { x: 550 })
                        .start()
                })
                this.moveInCandle1();
            })
            .start();
    }
    startTalking() {
        console.log("startText:", this.data.questions[this.questionIndex].text)
        if ((<any>window).courseware && (<any>window).courseware.stopTest) {
            (<any>window).courseware.startTest(this.data.questions[this.questionIndex].text);
        }
        this.talking = true;
        this.talkTimeOut = setTimeout(() => {
            this.stopTalking()
        }, this.data.questions[this.questionIndex].testWaitTime * 1000)
    }
    stopTalking() {
        console.log("stopTalk======")
        this.talking = false;
        this.initRedBtn();
        this.moveOutCandle2();
        this.nowPanel.showBlock();
        let fail = () => {
            this.answerList[this.questionIndex] = -1
            this.stickers.changOneSticker(this.questionIndex, false)
            this.nowPanel.showResult(false)
        }
        // let stopTestOut=setTimeout(()=>{

        // },3000)
        let timeOut=false;
        if ((<any>window).courseware && (<any>window).courseware.stopTest) {
              let stopTestOut=setTimeout(()=>{
                timeOut=true;
                fail();
              },3000);
                (<any>window).courseware.stopTest((res) => {
                    if(!timeOut){
                        clearTimeout(stopTestOut);
                        res = JSON.parse(res)
                        console.log("res=========", res.scores, res.result)
                        if (res.result&&res.result.overall >= 80) {
                            console.log("语音测评成功")
                            this.answerList[this.questionIndex] = 1
                            this.stickers.changOneSticker(this.questionIndex, true)
                            this.nowPanel.showResult(true)
                        } else {
                            fail();
                        }
                    }
                })
        } else {
            fail();
        }
        this.clearTimeouts()
    }
    onLoadEnd() {
        // TODO 加载完成后的逻辑写在这里, 下面的代码仅供参考
        this.initData();;
        this.initListener();
    }
    start(): void {
        let bgNode=cc.find("bg/bg",this.node);
        let scaleX=cc.winSize.width/bgNode.width;
        let scaleY=cc.winSize.height /bgNode.height;
        if(scaleX>scaleY){
            bgNode.scale=scaleX;
        }else{
            bgNode.scale=scaleY;
        }

        super.start();
    }
    dataCallBack() {
        super.dataCallBack();
        this.stickers.node.active = false;
        this.nowPanel = this.addPanel()
        cc.find("bg/topTittle", this.node).getComponentInChildren(cc.Label).string = this.data.title;

    }
    addPanel() {
        let panel = cc.instantiate(this.panel);
        panel.parent = cc.find("bg/ui", this.node)
        panel.x = panel.width * 3 / 2;
        panel.y=panel.height/2-cc.winSize.height/2
        let panelS = panel.getComponent("panel")
        panelS.initPanel(this.data.questions[this.questionIndex], this)
        panelS.questionIndex = this.questionIndex;
        return panelS;
    }
    initUi() {
        this.stickers.node.active = true;
        this.stickers.initStickers(this.data.questions.length);
        cc.find("bg/topTittle", this.node).getComponentInChildren(cc.Label).string = this.data.title;
        this.updateUi();
    }
    updateUi() {
        this.stickers.updateStickers(this.answerList);
    }
    onClickMusic() {
        this.musicBtn.interactable = false
        let animation=this.musicBtn.getComponent(cc.Animation);
        animation.play("musicing");

        this.playAudioByUrl(this.data.questions[this.questionIndex].audio, () => {
            this.musicBtn.interactable = true
            this.musicBtn.node.getChildByName("icon").getComponent(cc.Sprite).spriteFrame=this.musicIcon;
            animation.stop("musicing");
        })
    }
    changeTrue(panelS) {
        this.answering = false;
        this.clearTimeouts();
        console.log("选择正确")
        this.nowPanel && this.nowPanel.movePices()
    }
    changeEnd(isSuc) {
        this.moveOutCandle1();
        this.clearTimeouts()
        if (isSuc) {
            cc.tween(this.musicBtn.node)
                .to(0.3, { x: 850 })
                .call(() => {

                })
                .start()


        } else {

        }

    }
    changeFalse(timeOut = false) {
        this.clearTimeouts();
        this.answering = false;
        this.answerList[this.questionIndex] = -1
        this.stickers.changOneSticker(this.questionIndex, false);
        this.nowPanel.failPicesAction(timeOut);

        console.log("选择错误")
    }
    clearTimeouts() {
        if (this.answerTimeOut) {
            clearTimeout(this.answerTimeOut);
            this.answerTimeOut = null;
        }
        if (this.talkTimeOut) {
            clearTimeout(this.talkTimeOut);
            this.talkTimeOut = null;
        }
    }

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

    }
    initListener() {

    }
    playLocalAudio(audioName) {
        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);
            });
        })
    }
    protected update(dt: number): void {
        if (this.answering) {
            let allTime = this.data.questions[this.questionIndex].choosewaitTime;
            let maskNode = this.candle1.getChildByName("mask");
            maskNode.height -= 333 / allTime * dt;
            this.candle1.height = maskNode.height
            if (maskNode.height <= 0) maskNode.height = 0;
            let candleS = this.candle1.getComponent("candle");
            candleS.dragon1.node.active = true;
            if (maskNode.height > 333 * 0.2) {
                candleS.dragon1.node.active = true;
                candleS.dragon3.node.active = false;
            } else {
                candleS.dragon1.node.active = false;
                candleS.dragon3.node.active = true;
            }
        }
        if (this.talking) {
            let allTime = this.data.questions[this.questionIndex].testWaitTime;
            let maskNode = this.candle2.getChildByName("mask");
            maskNode.height -= 333 / allTime * dt;
            this.candle2.height = maskNode.height
            if (maskNode.height <= 0) maskNode.height = 0;
            let candleS = this.candle2.getComponent("candle");
            candleS.dragon1.node.active = true;
            if (maskNode.height > 333 * 0.2) {
                candleS.dragon1.node.active = true;
                candleS.dragon3.node.active = false;
            } else {
                candleS.dragon1.node.active = false;
                candleS.dragon3.node.active = true;
            }

        }
    }
    nextQuestion() {
        if (this.questionIndex < (this.data.questions.length - 1)) {
            this.questionIndex++;
            this.nextPanel = this.addPanel();
            this.nextPanel.node.x = this.nextPanel.node.width;
            cc.tween(this.nowPanel.node)
                .to(1, { x: -this.nowPanel.node.width })
                .call((e) => {
                    console.log("e=====", e)
                    e.destroy();

                })
                .start();
            this.nowPanel = this.nextPanel;
            this.answerList[this.questionIndex] = 0;
            this.updateUi()
            this.showPanel();
            cc.tween(this.nowPanel.node)
                .to(1, { x: 0 })
                .call(() => {
                })
                .start();
        } else {
            this.nowPanel.over(this.answerList)
        }

    }
    onDestroy(){
          this.clearTimeouts();

    }
    // 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) {},

}
