
import EndView from "../prefabs/endView/EndView_L5R3_GuessingGame";
import Keyboard from "../prefabs/keyboards/Keyboard_L5R3_GuessingGame";
import LoadingLayer from "../script/LoadingLayer_L5R3_GuessingGame";
import MsgData from "../script/msgDate_L5R3_GuessingGame";
import { MsgType, PlayerData, resultType } from "../script/msgType_L5R3_GuessingGame";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent_L5R3_GuessingGame";
import { NetworkHelper } from "../script/NetworkHelper_L5R3_GuessingGame";
import { GameServer } from "../script/Server_L5R3_GuessingGame";
import { asyncTweenTo, asyncDelay, onHomeworkFinish, asyncPlayDragonBoneAnimation } from "../script/util_L5R3_GuessingGame";

const DOLOG = false;

const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {
    @property(cc.Prefab)
    loadingLayerPrefab = null;
    @property(cc.Prefab)
    keyboardLayerPrefab = null
    @property(cc.Prefab)
    endViewPrefab = null
    @property(cc.Node)
    cat = null
    @property(cc.Node)
    pp = null
    @property(cc.Node)
    btn_record: cc.Node = null
    @property(cc.Node)
    cover = null
    @property(cc.Node)
    recordCat = null
    @property(cc.Node)
    cardRoot = null
    @property(cc.Node)
    myCardRoot = null
    @property(cc.Node)
    inputNode = null
    @property(cc.Node)
    recordNode = null
    @property(cc.SpriteFrame)
    cardList = []

    _gameWordList = [];
    excellent: any;
    _nowData: any;
    private _loadingDone: boolean = false;
    private _loadingCall: Function
    private _recordBefore: boolean = false;
    private _leftTime: number;
    private _keyboard: Keyboard;
    private _blueHeadIcon: cc.Node;
    private _redHeadIcon: cc.Node;
    private _clockNode: any;
    private _clockTime: any;
    private _wordCardRoot: cc.Node;
    private _redLightList: any;
    private _blueLightList: any;
    private _round2WordList: Array<{ word: string, uuid: string }>;
    private _stepWord: string;
    private _redUrl: any;
    private _blueUrl: any;
    private _localAudioRoot: cc.Node;
    private _round: number;
    private _catSpeaking: boolean;
    private _audioNode: cc.Node;
    private _canChosendCard: boolean = true;
    _wordData: any;
    private _otherWord: any;
    private _isRecording: any;
    private _guessWords: any;


    onLoad() {
        super.onLoad();

        this._localAudioRoot = this.node.getChildByName("audio")
        this.addLoadingLayer();
    }
    addLoadingLayer() {
        const loadingLayerNode = cc.instantiate(this.loadingLayerPrefab);
        loadingLayerNode.parent = this.node;
        loadingLayerNode.zIndex = 100;
        this.loadingLayer = loadingLayerNode.getComponent(LoadingLayer);
    }
    addKeyboard() {

        const keyboard = cc.instantiate(this.keyboardLayerPrefab);
        keyboard.parent = this.node;
        keyboard.zIndex = 100;
        this._keyboard = keyboard.getComponent(Keyboard);
        this._keyboard.setNormalData(-cc.winSize.height / 2)
        this._keyboard.InputEndCall = this._inputWords.bind(this);
    }

    _reqestWord() {

        if (!this._guessWords) {
            return;
        }

    }
    _inputWords(word) {
        this._guessWords = word;
        if (!this._guessWords) {
            return;
        }
        this.inputNode.getChildByName("lb").getComponent(cc.Label).string = word;
        this._sendMsg(MsgType.USER_REQ_WOED, { word: this._guessWords, uuid: this.playerId })

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

    addPreloadAudio() {
        // TODO 根据自己的配置预加载音频资源

        //  猫咪读条音频（匹配界面开始匹配前）: audioUrl_loading
        // 猫咪选牌提示音频: audioUrl_start
        // 猫咪选牌超时自动选择音频: audioUrl_auto_chose
        // 开始猜词提示音频: audioUrl_start_guessing
        // 猜词待机提示音频: audioUrl_waiting_guessing
        // 答错还剩两次次机会: audioUrl_tip_wrong1
        // 答错还剩一次机会: audioUrl_tip_wrong2
        // 长时间不提问的提示1: audioUrl_tip1
        // 长时间不提问的提示2: audioUrl_tip2
        // 长时间不提问的提示3: audioUrl_tip3
        // 猫咪胜利结束音频（两轮游戏都结束）: audioUrl_win
        // 猫咪失败结束音频（两轮游戏都结束）: audioUrl_lose



        this._audioResList.push({ url: this.data.audioUrl_loading });
        this._audioResList.push({ url: this.data.audioUrl_start });
        this._audioResList.push({ url: this.data.audioUrl_auto_chose });
        this._audioResList.push({ url: this.data.audioUrl_waiting_guessing });
        this._audioResList.push({ url: this.data.audioUrl_start_guessing });
        this._audioResList.push({ url: this.data.audioUrl_tip_wrong1 });
        this._audioResList.push({ url: this.data.audioUrl_tip1 });
        this._audioResList.push({ url: this.data.audioUrl_tip2 });
        this._audioResList.push({ url: this.data.audioUrl_tip3 });
        this._audioResList.push({ url: this.data.audioUrl_win });
        this._audioResList.push({ url: this.data.audioUrl_lose });

    }

    addPreloadAnima() { }

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

    }
    loadingLayer: LoadingLayer;
    initLoadingLayer() {
        this.loadingLayer.setMaxPlayerNumber(2);
        this.loadingLayer.onLoadFinished(() => {
            // this.playAudioByUrl(this.data.audioUrl_start);
            this._loadingDone = true;
            if (this._loadingCall) {
                this._loadingCall();
                this._loadingCall = null;
            }
        });

        this.playAudioByUrl(this.data.audioUrl_loading);
    }
    initView() {
        this.initProtory();
        this.addKeyboard();
        this.initLoadingLayer();
    }

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

        this.cover.width = cc.winSize.width;
        this.cover.height = cc.winSize.height;
        this.cover.getChildByName("bg").scale = this._mapScaleMax;

        let topRoot = cc.find("Canvas/topRoot");

        this._blueHeadIcon = topRoot.getChildByName("blueHead").getChildByName("blue").getChildByName("headIcon");
        this._redHeadIcon = topRoot.getChildByName("redHead").getChildByName("red").getChildByName("headIcon");

        this._clockNode = this.cat.parent.getChildByName("clock");
        this._clockTime = this._clockNode.getChildByName("lb").getComponent(cc.Label);

        this.cat.getChildByName("btn").on("click", () => {
            if (this._catSpeaking) {
                return;
            }
            if (this._isRecording) {
                return
            }
            this._catSpeaking = true;
            this.catAni();
        })

        this.inputNode.active = false;
        this.inputNode.on("click", this._reqestWord, this);

        this.pp.active = false;
        this.recordNode.scaleY = 0;
        this.recordNode.scalex = 1;

        this.btn_record.active = false;
        this.btn_record.on("click", this.openCoursView, this);

        this.initwordAnswerData();
    }

    loadPlayerHeadImage() {
        this._playerList.forEach((player) => {
            this.getSpriteFrimeByUrl(player.headUrl, (sf) => {
                if (player.side == "Red") {
                    this._redHeadIcon.getComponent(cc.Sprite).spriteFrame = sf;
                    this._redUrl = player.headUrl
                } else {
                    this._blueHeadIcon.getComponent(cc.Sprite).spriteFrame = sf;
                    this._blueUrl = player.headUrl
                }
            });
        });
    }

    catAni() {

        // if (this._round == 1) {
        //     asyncPlayDragonBoneAnimation(this.cat, "begin", 0);
        //     this.playAudioByUrl(this.data.audioUrl_waiting_firstRound, () => {
        //         asyncPlayDragonBoneAnimation(this.cat, "normal", 0);
        //         this._catSpeaking = false;
        //     })

        // } else if (this._round == 2) {
        asyncPlayDragonBoneAnimation(this.cat, "begin", 0);
        this.playAudioByUrl(this.data.audioUrl_waiting_guessing, () => {
            asyncPlayDragonBoneAnimation(this.cat, "normal", 0);
            this._catSpeaking = false;
        })
        // }
    }
    longTimeNoAction() {

        let index = Math.floor(Math.random() * 3);
        let list = [
            this.data.audioUrl_tip1,
            this.data.audioUrl_tip2,
            this.data.audioUrl_tip3]

        cc.audioEngine.stopAllEffects();
        this._catSpeaking = true;
        asyncPlayDragonBoneAnimation(this.cat, "begin", 0);
        this.playAudioByUrl(list[index], () => {
            asyncPlayDragonBoneAnimation(this.cat, "normal", 0);
            this._catSpeaking = false;
        })
        if (index == 0) {
            asyncDelay(1).then(() => {
                this._keyboard.showTips();
            })

        } else if (index == 1) {
            asyncDelay(1).then(() => {

                cc.tween(this.pp).to(0.3, { scale: 1.2 }).to(0.7, { scale: 1 }).start();

            })

        } else {
            asyncDelay(1.5).then(() => {

                cc.tween(this.pp).to(0.3, { scale: 1.2 }).to(0.7, { scale: 1 }).start();

            })
        }
    }

    playerId;
    isRoomOwner;
    server: GameServer;
    networkHelper: NetworkHelper;
    async initNetSever() {

        this._initGameData()

        this.networkHelper = new NetworkHelper();
        this.initNetworkListener();
        do {
            this.playerId = await this.networkHelper.init("op_L5_R3_guessing", 2);
            if (this.playerId === null) {
                this.log("onDestroy");
                this.networkHelper.onDestroy();
            }
            this.log("this.playerId = " + this.playerId);
        } while (this.playerId === null);

        const room = this.networkHelper.room;
        if (this.playerId == room.roomInfo.owner) {
            this.log("房主");
            this.isRoomOwner = true;
            this.server = new GameServer(2, this.networkHelper);

            this.server.wordList = this._gameWordList;

            await this.networkHelper.startFrameSync();

            this.server.startMatch();
        }
        await this.initHeadImgAndName();
    }

    async initHeadImgAndName() {
        const playerInfo: any = {
            playerHeadUrl: "http://staging-teach.cdn.ireadabc.com/0751c28419a0e8ffb1f0e84435b081ce.png",
            playerName: "test",
        };
        const middleLayer = cc.find("middleLayer");
        if (middleLayer) {
            const middleLayerComponent = middleLayer.getComponent("middleLayer");
            middleLayerComponent.log("这里 打log?");
            if (middleLayerComponent.getUserInfo && middleLayerComponent.getHeadUrl) {
                const kidInfo = await middleLayerComponent.getUserInfo();
                const playerHeadUrl = middleLayerComponent.getHeadUrl(kidInfo.avatar_url || kidInfo.id);
                playerInfo.playerHeadUrl = playerHeadUrl;
                playerInfo.playerName = kidInfo.nick_name || '拼读达人';
            }
        }

        let playData: PlayerData = {
            playerId: this.playerId,
            uuid: this.playerId,
            name: playerInfo.playerName,
            headUrl: playerInfo.playerHeadUrl,
            side: "",
            isAI: false,
        };
        this._sendMsg(MsgType.USER_JOIN_ERQ, playData);
    }

    _initGameData() {
        let cards = this.cardRoot.children;
        for (let i = 0; i < this.cardList.length; ++i) {
            let word = this.cardList[i].name;
            let cardIcon = cards[i].getChildByName("card");
            cardIcon.getComponent(cc.Sprite).spriteFrame = this.cardList[i];
            cards[i].getChildByName("word").getComponent(cc.Label).string = word;
            cards[i].getChildByName("finger").active = false;
            cardIcon.scale = Math.min(1, 150 / cardIcon.height);
            this._gameWordList.push(word)
        }
    }
    _sendMsg(type: MsgType, data: any) {
        this.networkHelper.sendFrame({
            type: type,
            data: data
        });
    }
    _isSeverMsgType(type) {
        return type == MsgType.USER_JOIN_ERQ ||
            type == MsgType.USER_REQ_WOED ||
            type == MsgType.USER_REQ_ADD_WOED ||
            type == MsgType.USER_PREPARE_REQ;
    }
    _playerList;
    initNetworkListener() {
        this.networkHelper.on("playerJoin", (event) => {
            // if (this.server) {

            //     this.server.onPlayerJoin({ data: { joinPlayerId: event.playerId } });
            // }
            this.log("playerJoin" + JSON.stringify(event, null, 2));
        });
        this.networkHelper.on("playerLeave", (event) => {
            cc.log("playerLeave" + JSON.stringify(event));
            cc.find("Canvas/PlayerOffLineLayer").active = true;
            this.networkHelper.leaveRoom();
        });
        this.networkHelper.on("playerOffLine", (event) => {
            cc.find("Canvas/PlayerOffLineLayer").active = true;
            this.networkHelper.leaveRoom();
            this.log("playerOffLine" + JSON.stringify(event));
        });
        this.networkHelper.on("gameStart", (event) => { });
        this.networkHelper.on("frameEvent", (event) => {
            event.data.frame.items.forEach(async (item) => {
                let type: MsgType = item.data.type;
                let msgData: MsgData = item.data.data;
                console.log("msg type: " + MsgType[item.data.type]);
                DOLOG && console.log("msg data :\n" + item.data.data);
                DOLOG && this.log("msg type: " + item.data.type);
                DOLOG && this.log("msg data :\n" + item.data.data)
                // 服务器只处理用户消息， 用户只处理广播消息
                if (this.server && this._isSeverMsgType(item.data.type)) {
                    this.server.onFrameEvent(item.data);
                } else {
                    let msg = typeof msgData == "string" ? JSON.parse(msgData) : msgData
                    this._onSeverMsg(type, msg);
                }

            });
        });
    }

    _onSeverMsg(type: MsgType, data: any) {

        if (type == MsgType.USER_JOIN_EV) {
            this._updateUserJoin(new MsgData(data));
        } else if (type == MsgType.ROOM_INIT_DONE) {

            this._doStartGameAni(new MsgData(data));

        } else if (type == MsgType.ROOM_ST) {

            this._updateRootSt(new MsgData(data));
        }
        else if (type == MsgType.ROUND_START_EV) {
            if (data.round == 1) {
                this._round = 1
                this._initCardClickEvent();

            } else {

                this.unschedule(this.longTimeNoAction)
                this.schedule(this.longTimeNoAction, 15, 6, 15);

                console.log("===============");
                console.log(data.list);
                data.list.forEach((val) => {
                    if (val.uuid != this.playerId) {
                        this._otherWord = val.word;
                    }
                })
                console.log("other word= " + this._otherWord);
                console.log("===============");
            }
        }
        else if (type == MsgType.USER_REQ_EV) {
            this.unschedule(this.longTimeNoAction)
            this.schedule(this.longTimeNoAction, 15, 6, 15)
            this._checkUserAnswer(data)
        } else if (type == MsgType.ROUND_END_EV) {
            this._round = -1
            this._roundEndCheck(data);
        }
    }



    _updateUserJoin(data: MsgData) {
        data.PlayerList.forEach((player) => {
            if (!this._playerList) {
                this._playerList = [];
            }

            if (
                !this._playerList.find(
                    (listPlayer) => listPlayer.uuid == player.uuid
                )
            ) {
                this._playerList.push({
                    uuid: player.uuid,
                    name: player.name,
                    side: player.side,
                    headUrl: player.headUrl,
                });
            }

            this.loadPlayerHeadImage();

            this.loadingLayer.addPlayer(
                player.name,
                player.uuid == this.playerId,
                player.headUrl,
                player.uuid
            );
        });
    }
    _doStartGameAni(data: MsgData) {

        this.log("_doStartGameAni")
        this._updateClock(data.Time);

        let aniCall = () => {

            this._sendMsg(MsgType.USER_PREPARE_REQ, {});
            // this.playAudioByUrl(this.data.audioUrl_tip_wrong1)
            // this._keyboard.showIn();

        }

        let doneLoadCall = async () => {


            asyncPlayDragonBoneAnimation(this.cat, "begin", 0)
            this._catSpeaking = true;

            // this.playLocalAudio("gameStartTip", () => {
            //     aniCall();
            //     this._catSpeaking = false;
            //     asyncPlayDragonBoneAnimation(this.cat, "normal", 0)
            // })

            this.playAudioByUrl(this.data.audioUrl_start, () => {
                aniCall();
                this._catSpeaking = false;
                asyncPlayDragonBoneAnimation(this.cat, "normal", 0)
            })

        }

        if (this._loadingDone) {
            doneLoadCall();
        } else {
            this._loadingCall = doneLoadCall;
        }
    }
    _updateRootSt(data: MsgData) {

        this._updateClock(data.Time);
    }
    async _roundEndCheck(data) {

        if (data.round == 1) {

            data = new MsgData(data);
            let aniCall = async () => {

                this._keyboard.showOut();
                this.inputNode.active = true;

                await asyncDelay(0.3)
                this._sendMsg(MsgType.USER_PREPARE_REQ, {});
                // this.btn_record.active = true;
            }

            this._clockTime.string = "0";
            let cards = this.cardRoot.children;
            for (let i = 0; i < this.cardList.length; ++i) {
                let finger = cards[i].getChildByName("finger");
                cc.tween(finger).stop();
                finger.active = false;
            }

            let hasWord = false;
            data.getAnswerList().forEach((val) => {
                if (val.uuid == this.playerId) {
                    hasWord = true;
                }
            })
            if (!hasWord) {
                await this._autoChoseOneWord();
            }

            await this._mixCards();

            asyncPlayDragonBoneAnimation(this.cat, "begin", 0)
            this._catSpeaking = true;
            asyncDelay(3).then(() => {
                this.pp.active = true;
                this.pp.scale = 0;
                cc.tween(this.pp).to(1, { scale: 1 }, { easing: "backOut" }).start();

                this.btn_record.active = true;
                this.btn_record.y = -cc.winSize.height / 2;

                cc.tween(this.btn_record).to(0.3, { y: this.btn_record.height - cc.winSize.height / 2 }).start();

            })

            this.playAudioByUrl(this.data.audioUrl_start_guessing, () => {
                aniCall();
                this._catSpeaking = false;
                asyncPlayDragonBoneAnimation(this.cat, "normal", 0)
            })

        } else if (data.round == 2) {


            this._checkUserAnswer(data)

        }


    }
    _autoChoseOneWord() {
        return new Promise((resolve) => {
            let index = Math.floor(Math.random() * this.cardList.length * 0.99);
            let word = this.cardList[index].name;
            this._sendMsg(
                MsgType.USER_REQ_ADD_WOED,
                {
                    uuid: this.playerId,
                    word: word,
                }
            )
            this._canChosendCard = false;
            asyncPlayDragonBoneAnimation(this.cat, "begin", 0)
            this._catSpeaking = true;
            this.playAudioByUrl(this.data.audioUrl_auto_chose, () => {
                asyncPlayDragonBoneAnimation(this.cat, "normal", 0)
                this._catSpeaking = false;
                let card = this.cardRoot.children[index];
                let cardNode: cc.Node = card.getChildByName("card");
                let pos = this.myCardRoot.convertToNodeSpaceAR(cardNode.convertToWorldSpaceAR(cc.v2(0, 0)))
                this.myCardRoot.getChildByName("card").getComponent(cc.Sprite).spriteFrame = this.cardList[index]
                let myCard = this.myCardRoot.getChildByName("card");
                let pos1 = myCard.position;
                myCard.x = pos.x;
                myCard.y = pos.y;
                cc.tween(myCard).to(1, { x: pos1.x, y: pos1.y }).call(() => {
                    this.myCardRoot.getChildByName("word").getComponent(cc.Label).string = word;
                    resolve("");
                }).start();

            })

        })
    }
    _mixCards() {
        return new Promise(async (resolve) => {
            let cards = this.cardRoot.children;
            for (let i = 0; i < this.cardList.length; ++i) {
                let maskNode = cards[i].getChildByName("mask");
                let lNode = maskNode.getChildByName("l");
                let rNode = maskNode.getChildByName("r");
                cc.tween(lNode).by(1, { x: 100 }).start();
                cc.tween(rNode).by(1, { x: -100 }).start();
            }

            let newwordListIndex = [];
            let indexList = [];
            for (let i = 0; i < 16; ++i) {
                indexList.push(i);
            }
            for (let i = 0; i < 16; ++i) {
                let index = Math.floor(Math.random() * indexList.length * 0.99);
                let keyIndex = indexList[index];
                indexList.splice(index, 1);
                newwordListIndex.push(keyIndex);
            }

            console.log(newwordListIndex)
            await asyncDelay(1);

            for (let i = 0; i < newwordListIndex.length; ++i) {
                let index = newwordListIndex[i];
                let word = this.cardList[index].name;
                cards[i].getChildByName("card").getComponent(cc.Sprite).spriteFrame = this.cardList[index];
                cards[i].getChildByName("word").active = false;
                let maskNode = cards[i].getChildByName("mask");
                let lNode = maskNode.getChildByName("l");
                let rNode = maskNode.getChildByName("r");
                cc.tween(lNode).by(1, { x: -100 }).start();
                cc.tween(rNode).by(1, { x: 100 }).start();
            }

            await asyncDelay(1);
            resolve("");
        })
    }
    _cyclePlayAudio() {
        this.playLocalAudio(this._stepWord);
    }
    _initCardClickEvent() {
        this.cardRoot.children.forEach((card, index) => {
            if (!card.getComponent(cc.Button)) {
                card.addComponent(cc.Button)
            }

            let finger = card.getChildByName("finger")
            finger.active = true;

            cc.tween(finger).hide().delay(3).show().by(1, { scale: 0.8 }).union().repeatForever().start();

            let word = this.cardList[index].name;
            card.on("click", () => {

                if (!this._canChosendCard) {
                    return;
                }
                this._canChosendCard = false;

                this.playLocalAudio("btn")

                let cards = this.cardRoot.children;
                for (let i = 0; i < this.cardList.length; ++i) {
                    let finger = cards[i].getChildByName("finger");
                    cc.tween(finger).stop();
                    finger.active = false;
                }

                this._sendMsg(
                    MsgType.USER_REQ_ADD_WOED,
                    {
                        uuid: this.playerId,
                        word: word,
                    }
                )

                let cardNode: cc.Node = card.getChildByName("card");
                let pos = this.myCardRoot.convertToNodeSpaceAR(cardNode.convertToWorldSpaceAR(cc.v2(0, 0)))
                this.myCardRoot.getChildByName("card").getComponent(cc.Sprite).spriteFrame = this.cardList[index]
                let myCard = this.myCardRoot.getChildByName("card");
                let pos1 = myCard.position;
                myCard.x = pos.x;
                myCard.y = pos.y;
                cc.tween(myCard).to(1, { x: pos1.x, y: pos1.y }).call(() => {
                    this.myCardRoot.getChildByName("word").getComponent(cc.Label).string = word;
                }).start();

            })

        })
    }

    _getSideByUuid(uuid) {
        let side = "";
        this._playerList.forEach((player) => {
            if (player.uuid == uuid) {
                side = player.side
            }
        });
        return side;
    }
    _updateClock(time: number) {

        if (this._leftTime == time) return
        this._leftTime = time;
        this._clockTime.string = "" + Math.round(time);
        cc.tween(this._clockTime.node).to(0.3, { scale: 1.2 }).to(0.7, { scale: 1 }).start();
    }
    _checkUserAnswer(data: { uuid: string, time: number, isWin: boolean, list: Array<any> }) {

        if (data.time) {

            if (this.playerId != data.uuid) return
            let audiourl = "gameTip2"
            if (data.time == 1) {
                audiourl = "gameTip1";
            }
            this.playLocalAudio(audiourl);

            this.unschedule(this.longTimeNoAction)
            this.schedule(this.longTimeNoAction, 15, 6, 15)

        } else {
            let redWord = "";
            let blueWord = "";
            let endview = cc.instantiate(this.endViewPrefab);
            endview.parent = this.node;
            endview.zIndex = 1000;
            let endViewCom: EndView = endview.getComponent(EndView);

            let side = this._getSideByUuid(this.playerId);
            if (side == "Red") {
                data.list.forEach((val) => {
                    if (val.uuid == this.playerId) {
                        redWord = val.word;
                    } else {
                        blueWord = val.word;
                    }
                })
            } else {
                data.list.forEach((val) => {
                    if (val.uuid == this.playerId) {
                        blueWord = val.word;
                    } else {
                        redWord = val.word;
                    }
                })
            }

            let redCard;
            let blueCard;
            for (let i = 0; i < this.cardList.length; ++i) {
                let card = this.cardList[i];
                if (card.name == redWord) {
                    redCard = card;
                }
                if (card.name == blueWord) {
                    blueCard = card;
                }
            }
            this.unschedule(this.longTimeNoAction)
            cc.audioEngine.stopAllEffects();
            this._catSpeaking = false;
            asyncPlayDragonBoneAnimation(this.cat, "begin", 0)
            let youWin = data.isWin && data.uuid == this.playerId
            this.playAudioByUrl(youWin ? this.data.audioUrl_win : this.data.audioUrl_lose, () => {
                asyncPlayDragonBoneAnimation(this.cat, "normal", 0)
                this._catSpeaking = false;
                endViewCom.showView(
                    youWin,
                    redWord,
                    blueWord,
                    redCard,
                    blueCard,
                    this._redUrl,
                    this._blueUrl
                )
            })

            this.finish();
        }
    }

    async openCoursView(node, word) {

        if (this._isRecording) return;
        this._isRecording = true

        this.btn_record.getChildByName("cover").active = true;

        this.recordNode.scalex = 1;
        cc.tween(this.recordNode).to(0.3, { scaleX: 0 }, { easing: "sinOut" }).start();

        cc.audioEngine.stopAllEffects();
        this.unschedule(this.longTimeNoAction)
        this.schedule(this.longTimeNoAction, 15, 6, 15)

        // this.cat.active = false;
        // this._clockNode.active = false;
        let probar = this.cover.getChildByName("bg").getChildByName("probar");
        let pass = this.cover.getChildByName("bg").getChildByName("pass");
        let loss = this.cover.getChildByName("bg").getChildByName("loss");
        this.cover.getChildByName("bg").getChildByName("bar").removeAllChildren();
        pass.active = false;
        loss.active = false;

        probar.getComponent(cc.ProgressBar).unscheduleAllCallbacks();
        let total = 1;
        probar.getComponent(cc.ProgressBar).progress = total;

        // if (!this._recordBefore && this.data.recordWait) {//
        //     this._recordBefore = true;
        //     await new Promise((resolve) => {
        //         this.recordCat.getComponent(dragonBones.ArmatureDisplay).playAnimation("normal", 0);
        //         this.playAudioByUrl(this.data.recordWait, () => {
        //             this.recordCat.getComponent(dragonBones.ArmatureDisplay).playAnimation("record", 0);
        //             console.log("record audio done==============");
        //             resolve("")
        //         });
        //     })
        // } else {
        // this.recordCat.getComponent(dragonBones.ArmatureDisplay).playAnimation("record", 0);
        // }

        this._startCourseware();
        await asyncDelay(0.5);
        // 6s 
        // probar.getComponent(cc.ProgressBar).schedule(() => {
        //     probar.getComponent(cc.ProgressBar).progress = total;
        //     total -= 1 / 20;
        //     if (total < 0) {
        //         probar.getComponent(cc.ProgressBar).unscheduleAllCallbacks();
        //         this._coursewareStoped();
        //     }
        // }, 0.1, 41, 0.1)

        asyncPlayDragonBoneAnimation(this.cat, "record", 0)
        this.scheduleOnce(() => {
            this._coursewareStoped();
            asyncPlayDragonBoneAnimation(this.cat, "normal", 0)
        }, 3.5)
    }

    async _startCourseware() {
        if (!cc.sys.isBrowser && window["courseware"]?.startRecord) {

            this.log("录音开始 识别 句子：");
            window["courseware"]?.startRecord(1);
        } else {

            console.log("web 模拟录音开始");
        }
    }
    async _coursewareStoped() {

        // this.cover.active = false;
        // cc.tween(this.cover).to(0.5, { opacity: 255 }).start();
        // await asyncDelay(0.5);

        if (!cc.sys.isBrowser && window["courseware"]?.startRecord) {
            window["courseware"]?.stopRecord((res, b) => {

                if (typeof res == "string") {
                    res = JSON.parse(res);
                }
                this.log("++++++++++++ _coursewareEnd  +++++++++++++++");
                this.log("发音=== " + res.text);


                this._coursewareEnd(res.text)
            });
        } else {
            // await asyncDelay(3);
            this.log("web 模拟录音评测 结果");
            this._coursewareEnd("test")
        }

    }
    async _coursewareEnd(text: string) {

        this._isRecording = false;
        this.btn_record.getChildByName("cover").active = false;
        this.cover.active = false;
        let strs: Array<string> = this._wordData[this._otherWord];

        console.log("匹配问题？")
        console.log(strs)

        this.recordNode.getChildByName("lb").getComponent(cc.Label).string = "" + text;
        this.recordNode.scaleX = 1;
        this.recordNode.scaleY = 0;
        cc.tween(this.recordNode).to(1, { scaleY: 1 }, { easing: "sineOut" }).start();
        if (strs.indexOf(text) > -1) {
            this.playLocalAudio("right")
        } else {
            this.playLocalAudio("wrong")
        }
    }

    initwordAnswerData() {

        this._wordData = {
            monkey: [
                "is your word monkey",
                "is it brown",
                "is it an animal",
            ],
            tiger: [
                "is your word tiger",
                "is it orange",
                "is it black and orange",
                "is it orange and black",
                "is it an animal",
            ],
            pencil: [
                "is your word pencil",
                "is it yellow",
                "is it an animal",
            ],
            music: [
                "is your word music",
                "is it black",
            ],
            honey: [
                "is your word honey",
                "is it orange",
                "is it yellow",
                "is it brown",
                "can you eat it",
            ],
            baby: [
                "is your word baby",
                "is it bule",
                "is it green",
                "is it an animal"
            ],
            umbrella: [
                "is your word umbrella",
                "is it blue",
            ],
            love: [
                "is your word love",
                "is it red",
            ],
            acorn: [
                "is your word acorn",
                "can you eat it",
                "is it brown",
            ],
            lemon: [
                "is your word lemon",
                "can you eat it",
                "is it a fruit",
                "is it yellow",

            ],
            chicken: [
                "is your word chicken",
                "is it yellow",
                "is it an animal",
                "can you eat it"
            ],
            son: [
                "is your word son",
                "is it orange",
                "is it orange and blue",
                "is it blue and orange",
                "is it an animal",
            ],
            hotel: [
                "is your word hotel",
                "is it green",
            ],
            she: [
                "is your word she",
                "is it pink",
                "is it grey",
                "is it pink and grey",
                "is it grey and pink",
                "is it an animal",
            ],
            uniform: [
                "is your word uniform",
                "is it red",
                "is it yellow",
                "is it yellow and red",
                "is it red and yellow",
            ],
            banana: [
                "is your word banana",
                "can you eat it",
                "is it yellow",
                "is it a fruit",

            ],

        }
    }

    isFinished = false;
    finish() {
        if (this.isFinished) {
            return;
        }
        this.isFinished = true;
        onHomeworkFinish();
    }

    async playLocalAudio(audioName, callBack = null) {

        if (this._audioNode) {
            if (this._audioNode?.getComponent(cc.AudioSource)?.isPlaying) {
                this._audioNode?.getComponent(cc.AudioSource).stop();
            }
        }

        let audioNode = this._localAudioRoot.getChildByName(audioName);
        if (audioNode) {

            this._audioNode = audioNode;
            let realTime = audioNode.getComponent(cc.AudioSource).getDuration();
            audioNode.getComponent(cc.AudioSource).play();

            await asyncDelay(realTime);
            callBack && callBack();

        } else {
            console.warn("no local audio with name " + audioName);
        }


    }
    // 生命周期
    onDestroy() {
        this.networkHelper.onDestroy();
    }
}

