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

const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {
    @property(cc.Node)
    cardParentN: cc.Node = null
    @property(cc.Prefab)
    cardP: cc.Prefab = null
    @property(cc.Label)
    tittleLabel: cc.Label = null
    @property(cc.Label)
    tipLabel: cc.Label = null
    @property(cc.Node)
    tipN: cc.Node = null
    @property(cc.Node)
    countDown: cc.Node = null;
    questionIndex = 0;
    gameState = "watching"
    watchInterval = null;
    gameInterval = null;
    watchTime = null;
    gameTime = null;
    clickNode1: cc.Node = null;
    clickNodeData1 = null
    canTouch = false
    completeNum = 0;
    @property(cc.Node)
    overN: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 加载完成后的逻辑写在这里, 下面的代码仅供参考

    }
    start(): void {
        this.cardParentN.removeAllChildren();
        cc.find("Canvas/uiP/bg_tip").active=false;
        super.start();
        this.log('initBg:');
        this.initBg();
        // this.initData();
        // cc.find("Canvas/uiP/top/timeN").active=false;
    }

    _cantouch = null;
    initData() {
        this.log('initData:');
        // 所有全局变量 默认都是null 
        cc.find("Canvas/uiP/bg_tip").active=true;
        this.tittleLabel.string = this.data.title;
        this.tipLabel.string = this.data.questionText;
        this.initCards()
        this.initTime();


    }
    initGameData(){
        this.clickNode1 = null;
        this.clickNodeData1 = null
        this.canTouch = false
        this.completeNum = 0;
    }
    initBg() {
        const bgNode = cc.find('Canvas/bg');
        bgNode.scale = this._mapScaleMax;
        cc.find('Canvas/uiP').scale = this._mapScaleMin;
        // cc.find('Canvas/uiP/top').y=this._frameSize.height/4;
    }
    initCards() {
        let data = this.getRandomCardData();
        console.log("getRandomCardData==========", data)
        let num = data.length;
        this.cardParentN.removeAllChildren();
        let col = Math.ceil(num / 2);
        let width = 1250;
        console.log("getRandomCardData==========col", col,num)
        if (num <= 8) width = 1050
        if (col > 2) {
            for (let i = 0; i < num; i++) {
                let card = cc.instantiate(this.cardP);
                this.cardParentN.addChild(card)
                let indexCol = Math.floor(i / 2);
                let space = width / col;
                card.x = -width / 2 + space * (indexCol + 1 / 2);
                if (i % 2 == 1) {
                    card.y = -card.height / 2 - 10
                } else {
                    card.y = +card.height / 2 + 10
                }
                card.getComponent("card").initData(data[i], this)
            }

        } else if (col == 2) {
            for (let i = 0; i < num; i++) {
                let card = cc.instantiate(this.cardP);
                this.cardParentN.addChild(card)

                if (Math.floor(i / 2) > 0) {
                    card.x = -180
                } else {
                    card.x = 180
                }

                if (i % 2 == 1) {
                    card.y = -card.height / 2 - 10
                } else {
                    card.y = +card.height / 2 + 10
                }
                card.getComponent("card").initData(data[i], this)
            }
        } else {

            for (let i = 0; i < num; i++) {
                let card = cc.instantiate(this.cardP);
                this.cardParentN.addChild(card)
                card.x = 0
                if (i % 2 == 1) {
                    card.y = -card.height / 2 - 10
                } else {
                    card.y = +card.height / 2 + 10
                }
                card.getComponent("card").initData(data[i], this)
            }
        }
        console.log(" this.cardParentN=====", this.cardParentN)
    }
    getRandomCardData() {
        let data = this.data.questions[this.questionIndex].options;
        for (let i = 0; i < data.length; i++) {
            let a = Math.floor(Math.random() * (i + 1));
            let b = Math.floor(Math.random() * (i + 1));
            let data1 = data[a];
            let data2 = data[b];
            data[a] = data2;
            data[b] = data1
        }

        return data
    }
    initTime() {
        // cc.find("Canvas/uiP/top/timeN").active=true;
        let timeN = cc.find("Canvas/uiP/top/timeN/bg_time");
        let timeN1 = cc.find("Canvas/uiP/top/timeN/bg_time2");
        this.watchTime = this.data.questions[this.questionIndex].watchTime;
        this.gameTime = this.data.questions[this.questionIndex].gameTime;
        let numTime = this.watchTime;
        if (this.gameState == "game") numTime = this.gameTime;
        console.log("numTime=======",numTime)
        timeN.getComponentInChildren(cc.Label).string = numTime;
        timeN1.getComponentInChildren(cc.Label).string = numTime;
        timeN.active = false;
        timeN1.active = false;
        if(numTime>5){
            timeN.active = true;
        }else{
            timeN.active = false;
        }
    }
    updateTime() {
        let timeN = cc.find("Canvas/uiP/top/timeN/bg_time");
        let timeN1 = cc.find("Canvas/uiP/top/timeN/bg_time2");
        let numTime = this.watchTime;
        if (this.gameState == "game") numTime = this.gameTime;
        timeN.getComponentInChildren(cc.Label).string = numTime;
        timeN1.getComponentInChildren(cc.Label).string = numTime;
        timeN.active = true;
        timeN1.active = false;
        if (numTime <= 5) {
            timeN.active = false;
            timeN1.active = true;
            // if(this.gameState=="game"){
            if (numTime <= 1) {
                if (numTime == 1) this.playLocalAudio("time1")
            } else {
                this.playLocalAudio("time2")
            }
            // }else{
            if (this.gameState == "watching") {
                if (numTime == 1 || numTime == 2 || numTime == 3) {
                    this.countDown.active = true;
                    this.countDown.stopAllActions();
                    this.countDown.scale = 1;
                    this.getSprforNode(numTime, this.countDown);
                    cc.tween(this.countDown)
                        .to(0.8, { scale: 0.7 })
                        .call(() => {
                            this.countDown.active = false;
                        })
                        .start()
                }
            }
            // }

        }


    }
    onStartClick() {
        this.tipN.active = false;
        this.playLocalAudio("btn");
        let children = this.cardParentN.children;
        for (let i = 0; i < children.length; i++) {
            children[i].getComponent("card").asyncDoFlip(() => {
                if (i == children.length - 1) this.startWatch();
            })
        }

    }
    startWatch() {
        this.canTouch = false
        this.gameState = "watching"
        this.clearntervals();
        this.initTime();
        this.watchInterval = setInterval(() => {
            this.watchTime--;
            console.log("watchtime=====", this.watchTime)
            if (this.watchTime <= 0) {
                this.clearntervals();
                let children = this.cardParentN.children;
                for (let i = 0; i < children.length; i++) {
                    children[i].getComponent("card").asyncDoFlip(() => {
                        if (i == children.length - 1) this.startGame();
                    })
                }
            }
            this.updateTime();

        }, 1000)

    };
    startGame() {
        this.canTouch = true;
        this.gameState = "game"
        this.clearntervals();
        this.initTime();
        this.gameInterval = setInterval(() => {
            this.gameTime--;
            console.log("gametime=====", this.gameTime)
            if (this.gameTime <= 0) {
                this.gameOver(false);
                this.clearntervals();
            }
            this.updateTime();

        }, 1000)

    }
    clickCard(node, data) {
        if (this.canTouch) {
            if (!this.clickNode1) {
                this.clickNode1 = node;
                this.clickNodeData1 = data;
                this.clickNode1.getComponent("card").asyncDoFlip()
                this.playAudioByUrl(this.clickNodeData1.audio);
            } else {
                if (this.clickNode1 == node) {
                    return;
                    // this.playAudioByUrl( this.clickNodeData1.audio);  
                } else {
                    this.canTouch = false
                    if (this.clickNodeData1.pairIdx == data.pairIdx) {
                        Promise
                            .all([node.getComponent("card").asyncDoFlip(), this.playAudioByUrl(data.audio)])
                            .then(() => {
                                Promise.all([node.getComponent("card").playDragon(), this.clickNode1.getComponent("card").playDragon(), this.playLocalAudio("true")])
                                    .then(() => {
                                        Promise.all([node.getComponent("card").doHide(), this.clickNode1.getComponent("card").doHide()])
                                            .then(() => {
                                                this.canTouch = true;
                                                this.clickNode1 = null
                                                this.clickNodeData1 = null;
                                                this.completeNum++
                                                if (this.completeNum == this.data.questions[this.questionIndex].options.length / 2) {
                                                    console.log("allTrue===")
                                                    this.clearntervals();
                                                    if(this.questionIndex<(this.data.questions.length-1)){
                                                        this.questionIndex++
                                                        this.overN.active=false;
                                                        this.initGameData();
                                                        this.initCards();
                                                        this.tipN.active = false;
                                                        let children = this.cardParentN.children;
                                                        for (let i = 0; i < children.length; i++) {
                                                            children[i].getComponent("card").asyncDoFlip(() => {
                                                                if (i == children.length - 1) this.startWatch();
                                                            })
                                                        }
                                                    }else{
                                                        this.gameOver(true)
                                                    }
                                                }
                                                console.log("allActionFish=====")
                                            })
                                    })
                            }
                            )
                    } else {
                        Promise
                            .all([node.getComponent("card").asyncDoFlip(), this.playAudioByUrl(data.audio)])
                            .then(() => {
                                Promise.all([this.playLocalAudio("false")])
                                    .then(() => {
                                        Promise.all([node.getComponent("card").asyncDoFlip(), this.clickNode1.getComponent("card").asyncDoFlip()])
                                            .then(() => {
                                                this.canTouch = true;
                                                this.clickNode1 = null
                                                this.clickNodeData1 = null;
                                            })
                                    })
                            }
                            )
                    }

                }

            }

        }

    }
    clearntervals() {
        // cc.find("Canvas/uiP/top/timeN").active=false;
        if (this.watchInterval) {
            clearInterval(this.watchInterval);
        }
        if (this.gameInterval) {
            clearInterval(this.gameInterval);
        }
    }
    gameOver(isSuc){
        this.questionIndex=0;
        this.overN.active=true;

        let sucN=this.overN.getChildByName("suc")
        let failN=this.overN.getChildByName("fail")
        if(isSuc){
            sucN.active=true;
            failN.active=false;
            this.playAudioByUrl("suc")
            onHomeworkFinish();
        }else{
            sucN.active=false;
            failN.active=true;
        }

    }
    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);
            });
        })
    }
    onClickRestart(){
        this.overN.active=false;
        this.initGameData();
        this.initCards();
        this.onStartClick();
    }
    onDestroy(){
        this.clearntervals();
    }

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



    // 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);
    //     })
    // }

    // initBtn() {
    // }

    // // update (dt) {},


    // initListener() {

    // }

}
