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

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;


    @property(cc.Node)
    btn_audio_off: cc.Node = null;
    @property(cc.Node)
    btn_audio_on: cc.Node = null;

    private isPlayBgAudio: boolean;

    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
    resultQuesitons = [];
    // resultData = {
    //     quesitons:[{
    //       duration: 107,// 用时多久
    //       rightPairNumber: 5, // 正确的对数
    //       wrongPairNumber: 3, // 错误的对数
    //       totalPairNumber: 6,// 总对数
    //     }]
    //   }




    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 });
        this._audioResList.push({ url: this.data.bgAudio });
        this._audioResList.push({ url: this.data.questionTextAudio });
    }

    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 
        // 
        // this.scheduleOnce(()=>{
        // 把听写助手传来的数据 转换为游戏需要的数据
        this.data = this.translateData(this.data);
        this.asyncPlayAudioByUrl(this.data.questionTextAudio)
        // },1)
        cc.find("Canvas/uiP/bg_tip").active = true;
        this.tittleLabel.string = this.data.title;
        this.tipLabel.string = this.data.questionText;
        this.initCards()
        this.initTime();

        if (this.data.bgAudio && this.data.bgAudio != "") {
            this.btn_audio_on.active = true;
        }
        this.btn_audio_off.on(cc.Node.EventType.TOUCH_END, this.onAudioOff, this);
        this.btn_audio_on.on(cc.Node.EventType.TOUCH_END, this.onAudioOn, this);
    }

    // 数据转换 - 把听写助手传进来的数据转换成这个模板需要的游戏数据
    private translateData(data) {
        // 把数组分割为4个一组
        function getQuestionGroupData(list) {
            let len = list.length
            let newList = []
            if (len) {
              var chunk = 4
              for (var i = 0, j = len; i < j; i += chunk) {
                newList.push(list.slice(i, i + chunk))
              }
            }
            console.log(newList)
            return newList
        }

		// 把数据组装为成对数据
		function getPairData(itemData, index) {
            return [
                {
                    pairIdx: index+1,
                    audio: itemData.audio_url,
                    type: "text",
                    text: itemData.text_en
                }, {
                    pairIdx: index+1,
                    audio: itemData.audio_url,
                    type: "text",
                    text: itemData.text_cn
                }
            ]
		}

		// data = [ { "id": 20, "pid": 19, "text_en": "what", "text_cn": "什么", "audio_url": "http://teach.cdn.ireadabc.com/36b5e5d9a5240bff453e95e2d74cece0.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/27a5b4d9525a299e3806ccd991a8e5f9.mp3", "image_url": "[\"http://teach.cdn.ireadabc.com/b9b759a25cafbadc3130201e50cf4f85.jpeg\"]", "phonetic": "[wɒt]", "description": null, "mlk": null, "data": null, "seq": 1, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-10T03:31:34.000Z", "del": 0 }, { "id": 21, "pid": 19, "text_en": "is", "text_cn": "是", "audio_url": "http://teach.cdn.ireadabc.com/d7f9276c7ff13b734c74358d7580a193.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/45100afa502326955d0f03cac87f1a5b.mp3", "image_url": null, "phonetic": "[ɪz]", "description": null, "mlk": null, "data": null, "seq": 2, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-10T03:31:34.000Z", "del": 0 }, { "id": 22, "pid": 19, "text_en": "what’s", "text_cn": "是什么", "audio_url": "http://teach.cdn.ireadabc.com/383082bc329464ae1580fffcd5e85d54.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/244d88fbd98972865959d1c0fe50bdac.mp3", "image_url": null, "phonetic": "[wɒts]", "description": null, "mlk": null, "data": null, "seq": 3, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-10T03:31:34.000Z", "del": 0 }, { "id": 23, "pid": 19, "text_en": "your", "text_cn": "你的", "audio_url": "http://teach.cdn.ireadabc.com/09b268cd4e201e12f4f8af377308689b.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/f723a8c809b4c910b416a9a6c9e34eb8.mp3", "image_url": "[\"http://teach.cdn.ireadabc.com/808504438919f5d2849dff97f7fb0ffd.jpg\",\"http://teach.cdn.ireadabc.com/fc9d5a0d4eba960aecae0d88b0c39acd.jpg\"]", "phonetic": "[jɔː(r)]", "description": null, "mlk": null, "data": null, "seq": 4, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-14T01:48:59.000Z", "del": 0 }, { "id": 24, "pid": 19, "text_en": "name", "text_cn": "名字", "audio_url": "http://teach.cdn.ireadabc.com/60bf983a10741a0796a3a71d1c0b5907.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/0fa9f2cc4c971d870889d7b80976654f.mp3", "image_url": "[\"http://teach.cdn.ireadabc.com/a0d9907a44d617784b533dc920647dee.jpg\"]", "phonetic": "[neɪm]", "description": null, "mlk": null, "data": null, "seq": 5, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-10T03:31:34.000Z", "del": 0 }, { "id": 25, "pid": 19, "text_en": "please", "text_cn": "请", "audio_url": "http://teach.cdn.ireadabc.com/ee1c7821c46b49ba850ebefc598cdb5b.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/ac372008acb6236b6a1428a334c7f0a5.mp3", "image_url": "[\"http://teach.cdn.ireadabc.com/a42594ef6c4fc5b1987d2b073ae675dd.webp\",\"http://teach.cdn.ireadabc.com/7fc1972331756f74dbcf7ae0215a809b.png\"]", "phonetic": "[pliːz]", "description": null, "mlk": null, "data": null, "seq": 6, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-10T03:31:34.000Z", "del": 0 }, { "id": 26, "pid": 19, "text_en": "good", "text_cn": "好的", "audio_url": "http://teach.cdn.ireadabc.com/3aeaf5c3884ad3f00a92900ed478c77e.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/403ba0be9e118b5325e3ae8acbdd3743.mp3", "image_url": "[\"http://teach.cdn.ireadabc.com/42946cef3972cc2ddaded63ba0fc20c1.webp\"]", "phonetic": "[ɡʊd]", "description": null, "mlk": null, "data": null, "seq": 7, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-14T01:49:00.000Z", "del": 0 }, { "id": 27, "pid": 19, "text_en": "morning", "text_cn": "早晨,上午", "audio_url": "http://teach.cdn.ireadabc.com/382d219f6339f5e0980cb9b716dbac8d.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/2c9c57ed86a6ca438c486543bc8bcb88.mp3", "image_url": "[\"http://teach.cdn.ireadabc.com/ffbf1f05334754e42deff6f8f2f96d3e.jpg\",\"http://teach.cdn.ireadabc.com/b8e68519a23841f248a09293a879ffe9.jpg\",\"http://teach.cdn.ireadabc.com/d72d4b2d838e91570a3e777eaa5f9420.jpg\"]", "phonetic": "['mɔːnɪŋ]", "description": null, "mlk": null, "data": null, "seq": 8, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-14T01:49:00.000Z", "del": 0 }, { "id": 28, "pid": 19, "text_en": "Ms.", "text_cn": "女士", "audio_url": "http://teach.cdn.ireadabc.com/81c51b5b602e3687c6b220727c5e5f55.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/5476bff8440fc49bebad504a0bd86eba.mp3", "image_url": null, "phonetic": "[miz]", "description": null, "mlk": "Ms", "data": null, "seq": 9, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-14T07:46:34.000Z", "del": 0 }, { "id": 29, "pid": 19, "text_en": "my", "text_cn": "我的", "audio_url": "http://teach.cdn.ireadabc.com/d4463b448d966353c3c19ae9b9e6ca71.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/cfbc278fb514c0bc9ca690f1c4df0950.mp3", "image_url": "[\"http://teach.cdn.ireadabc.com/a2c2888111d4c18015a7d01d55fe93fb.jpg\",\"http://teach.cdn.ireadabc.com/98aa7a0d3243e8a361fd2973e4563f93.jpg\",\"http://teach.cdn.ireadabc.com/8a8b042372a3304b66495039eb7a92ff.jpg\",\"http://teach.cdn.ireadabc.com/da793b5cf93ae8915574f42d837dbae3.jpg\",\"http://teach.cdn.ireadabc.com/56857caeabb7b5bd49fa3054b2e45a52.webp\"]", "phonetic": "[maɪ]", "description": null, "mlk": null, "data": null, "seq": 10, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-10T03:31:34.000Z", "del": 0 }, { "id": 30, "pid": 19, "text_en": "bird", "text_cn": "鸟", "audio_url": "http://teach.cdn.ireadabc.com/1ef04de98ddc59957edbc709901c60c7.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/fae76ae6e1bcb53d63d6f38838587ae0.mp3", "image_url": "[\"http://teach.cdn.ireadabc.com/7cf3efe3d56e7fe69d6a1809b567d1ae.jpeg\",\"http://teach.cdn.ireadabc.com/64b0eb3286053f0bf7672f61f9e5565a.jpeg\",\"http://teach.cdn.ireadabc.com/deb296c3696ee0940dc91ee18eb68d27.webp\"]", "phonetic": "[bɜːd]", "description": null, "mlk": null, "data": null, "seq": 11, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-10T03:31:34.000Z", "del": 0 }, { "id": 31, "pid": 19, "text_en": "tweet", "text_cn": "小鸟啼叫", "audio_url": "http://teach.cdn.ireadabc.com/db4b0511e318b0725532aeba6181bd51.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/867865f1650f3512adba56c83bcb9f3e.mp3", "image_url": null, "phonetic": "[twi:t]", "description": null, "mlk": null, "data": null, "seq": 12, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-10T03:31:34.000Z", "del": 0 }, { "id": 32, "pid": 19, "text_en": "a(n)", "text_cn": "一个", "audio_url": "http://teach.cdn.ireadabc.com/81eec7df521de5f8b0704fa114bc0aff.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/618b7d333097f2e96b35bb9135231918.mp3", "image_url": null, "phonetic": "[ə][ən]", "description": null, "mlk": null, "data": null, "seq": 13, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-10T03:31:34.000Z", "del": 0 }, { "id": 33, "pid": 19, "text_en": "boy", "text_cn": "男孩", "audio_url": "http://teach.cdn.ireadabc.com/6c60ff7775afbb0b454f23151719e9d0.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/e27330597469d5e81f0037c5846aca48.mp3", "image_url": "[\"http://teach.cdn.ireadabc.com/1f042535eef57f88054d46f903d87e80.jpeg\"]", "phonetic": "[bɔɪ]", "description": null, "mlk": null, "data": null, "seq": 14, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-10T03:31:34.000Z", "del": 0 }, { "id": 34, "pid": 19, "text_en": "girl", "text_cn": "女孩", "audio_url": "http://teach.cdn.ireadabc.com/d038b562b0c7781e718eb08550849143.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/9ad553f6e10ddc1bfeb851082f9f1d25.mp3", "image_url": "[\"http://teach.cdn.ireadabc.com/896d19830863cfc1561553ebf3b6ecbe.webp\",\"http://teach.cdn.ireadabc.com/92354ec729582b3bb2ea05851e9d0806.webp\"]", "phonetic": "[ɡɜːl]", "description": null, "mlk": null, "data": null, "seq": 15, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-10T03:31:34.000Z", "del": 0 }, { "id": 35, "pid": 19, "text_en": "afternoon", "text_cn": "下午", "audio_url": "http://teach.cdn.ireadabc.com/1f70fe441cdca82832cdf7bc286796f7.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/0ab162e708e2ba9991398f10107504ab.mp3", "image_url": "[\"http://teach.cdn.ireadabc.com/e4b9c73c31c47a7441bb6ac04d558c02.jpg\",\"http://teach.cdn.ireadabc.com/d2914aad9ce834ebb057b04400609a17.jpg\",\"http://teach.cdn.ireadabc.com/0ad04d2a371a51af723a2fae92ebbf10.jpg\"]", "phonetic": "[ˌɑːftə'nuːn]", "description": null, "mlk": null, "data": null, "seq": 16, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-10T03:31:34.000Z", "del": 0 }, { "id": 36, "pid": 19, "text_en": "panda", "text_cn": "熊猫", "audio_url": "http://teach.cdn.ireadabc.com/99b59a21ea78955c7e593c2f38ef31de.mp3", "audio_cn_url": "http://teach.cdn.ireadabc.com/a30d8dc936cbe5e1324b293faaa6e3ce.mp3", "image_url": "[\"http://teach.cdn.ireadabc.com/e32c4771a53e118e25fc0c16de7deccb.jpg\",\"http://teach.cdn.ireadabc.com/e79e9d8a7b391b55aabeb54281ccf5a7.jpg\"]", "phonetic": "['pændə]", "description": null, "mlk": null, "data": null, "seq": 17, "has_child": 0, "depth": 4, "created_date": "2023-02-01T10:07:13.000Z", "updated_date": "2023-02-10T03:31:34.000Z", "del": 0 } ];

		// 按照需要的结构进行组装
		const tData = {
            title: "标题标题",
            questionText: "题目说明题目说明题目说明题目说明题目说明题目说明题目说明",
            questionTextAudio: "http://staging-teach.cdn.ireadabc.com/92ddbc65e9af775f7a8450a5bef1a732.mp3",
            bgAudio: "https://staging-teach.cdn.ireadabc.com/ed84c18cc5f696ceaaf488ff98c228fe_l.mp3",
            questions: []
        }

        const groupData = getQuestionGroupData(data);

		groupData.forEach((group, gIndex)=>{
            const qNum = group.length;
            const configItem = {
                watchTime: 5 * qNum, // 看题时间（秒）
                gameTime: 10 * qNum, // 游戏时间（秒）
                options: []
            }
            group.forEach((item, index) => {
                const pairData = getPairData(item, index);
                configItem.options = configItem.options.concat(pairData)
            });
			
			tData.questions.push(configItem);
		})
		return tData;
	}

    private onAudioOn() {
        this.btn_audio_off.active = true;
        this.btn_audio_on.active = false;
        this.isPlayBgAudio = false;
        this.stopBgAudio();
    }
    private onAudioOff() {
        this.btn_audio_on.active = true;
        this.btn_audio_off.active = false;
        this.isPlayBgAudio = true;
        this.playBgAudio();
    }
    private playBgAudio() {
        if (!this.isPlayBgAudio) return;
        cc.audioEngine.resumeMusic();
    }
    private stopBgAudio() {
        cc.audioEngine.pauseMusic();
    }
    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_TXZS_G_002").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_TXZS_G_002").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_TXZS_G_002").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"){

            // }else{
            if (this.gameState == "watching") {
                if (numTime == 3) this.playLocalAudio("suc")
                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()
                }
            } else {
                if (numTime <= 1) {
                    if (numTime == 1) this.playLocalAudio("time1", false)
                } else {
                    this.playLocalAudio("time2", false)
                }
            }
            // }

        }


    }
    onStartClick() {
        this.tipN.active = false;
        cc.audioEngine.stopAll();
        this.playLocalAudio("btn");
        this.playBgAudioByUrl(this.data.bgAudio);
        let children = this.cardParentN.children;
        for (let i = 0; i < children.length; i++) {
            children[i].getComponent("card_TXZS_G_002").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_TXZS_G_002").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.clearntervals();
                this.resultQuesitons.push({
                    duration: this.data.questions[this.questionIndex].gameTime - this.gameTime,// 用时多久
                    rightPairNumber: this.completeNum, // 正确的对数
                    wrongPairNumber: this.data.questions[this.questionIndex].options.length / 2 - this.completeNum, // 错误的对数
                    totalPairNumber: this.data.questions[this.questionIndex].options.length / 2,// 总对数
                })
                if (this.questionIndex < (this.data.questions.length - 1)) {
                    this.nextQuestion();
                } else {
                    this.gameOver(true)
                }
            }
            this.updateTime();

        }, 1000)

    }
    clickCard(node, data) {
        if (this.canTouch) {
            if (!this.clickNode1) {
                this.clickNode1 = node;
                this.clickNodeData1 = data;
                this.clickNode1.getComponent("card_TXZS_G_002").asyncDoFlip()
                this.asyncPlayAudioByUrl(this.clickNodeData1.audio);
                // this.asyncPlayAudioByUrl( this.data.questionTextAudio);

            } else {
                if (this.clickNode1 == node) {
                    return;
                    // this.asyncPlayAudioByUrl( this.clickNodeData1.audio);  
                } else {
                    this.canTouch = false
                    if (this.clickNodeData1.pairIdx == data.pairIdx) {
                        // this.asyncPlayAudioByUrl(data.audio)
                        Promise
                            .all([node.getComponent("card_TXZS_G_002").asyncDoFlip(), this.asyncPlayAudioByUrl(data.audio)])
                            .then(() => {
                                this.playLocalAudio("true")
                                Promise.all([node.getComponent("card_TXZS_G_002").playDragon(), this.clickNode1.getComponent("card_TXZS_G_002").playDragon()])
                                    .then(() => {
                                        Promise.all([node.getComponent("card_TXZS_G_002").doHide(), this.clickNode1.getComponent("card_TXZS_G_002").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();
                                                    this.resultQuesitons.push({
                                                        duration: this.data.questions[this.questionIndex].gameTime - this.gameTime,// 用时多久
                                                        rightPairNumber: this.completeNum, // 正确的对数
                                                        wrongPairNumber: this.data.questions[this.questionIndex].options.length / 2 - this.completeNum, // 错误的对数
                                                        totalPairNumber: this.data.questions[this.questionIndex].options.length / 2,// 总对数
                                                    })
                                                    if (this.questionIndex < (this.data.questions.length - 1)) {
                                                        this.nextQuestion();
                                                    } else {
                                                        this.gameOver(true)
                                                    }
                                                }
                                                console.log("allActionFish=====")
                                            })
                                    })
                            }
                            )
                    } else {
                        Promise
                            .all([node.getComponent("card_TXZS_G_002").asyncDoFlip(), this.asyncPlayAudioByUrl(data.audio)])
                            .then(() => {
                                this.playLocalAudio("false")
                                // Promise.all([this.playLocalAudio("false")])
                                //     .then(() => {
                                Promise.all([node.getComponent("card_TXZS_G_002").asyncDoFlip(), this.clickNode1.getComponent("card_TXZS_G_002").asyncDoFlip()])
                                    .then(() => {
                                        this.canTouch = true;
                                        this.clickNode1 = null
                                        this.clickNodeData1 = null;
                                    })
                                // })
                            }
                            )
                    }

                }

            }

        }

    }
    nextQuestion() {
        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_TXZS_G_002").asyncDoFlip(() => {
                if (i == children.length - 1) this.startWatch();
            })
        }
    };
    clearntervals() {
        // cc.find("Canvas/uiP/top/timeN").active=false;
        if (this.watchInterval) {
            clearInterval(this.watchInterval);
        }
        if (this.gameInterval) {
            clearInterval(this.gameInterval);
        }
    }
    gameOver(isSuc) {
        if (isSuc) {
            this.questionIndex = 0;
            // this.overN.active=true;

            // let sucN=this.overN.getChildByName("suc")
            // let failN=this.overN.getChildByName("fail")
            // sucN.active=true;
            // failN.active=false;
            // this.asyncPlayAudioByUrl("suc")
            onHomeworkFinish({
                quesitons: this.resultQuesitons
            });
        }
    }
    playLocalAudio(audioName, stopAll = true) {
        const audio = cc.find(`Canvas/res/audio/${audioName}`).getComponent(cc.AudioSource);
        return new Promise((resolve, reject) => {
            // if(stopAll)  cc.audioEngine.stopAll();

            const id = cc.audioEngine.playEffect(audio.clip, false);
            cc.audioEngine.setFinishCallback(id, () => {
                resolve(id);
            });
        })
    }
    onClickRestart() {
        this.resultQuesitons = []
        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.asyncPlayAudioByUrl(this.data.audio_url);
    //     })
    // }

    // initBtn() {
    // }

    // // update (dt) {},


    // initListener() {

    // }

}

