
import { delayCall } from "../../../form/src/app/play/Unit";
import Keyboard from "../prefabs/keyboards/Keyboard";
import LoadingLayer from "../script/BoardGame_yyh_LoadingLayer";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent";
import { NetworkHelper } from "../script/NetworkHelper";
import { GameServer } from "../script/Server";
import { asyncTweenTo, asyncDelay, onHomeworkFinish } from "../script/util";
import BoardCardItem from "./boardCardItem";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {
    @property(cc.Prefab)
    loadingLayerPrefab = null;
    @property(cc.Prefab)
    keyboardLayerPrefab = null
    @property(cc.Node)
    cat = null
    @property(cc.Node)
    clockNode = null
    @property(cc.Node)
    cover = null
    @property(cc.Node)
    recordCat = null
    @property(cc.Node)
    btn_keyboard = null

    _cardList: Array<cc.Node> = [];

    private _isRolling: any;

    _randomList = [];
    excellent: any;
    _nowData: any;
    private _myData: any;
    private _loadingDone: boolean = false;
    private _playingAudio: boolean;
    private _canClick: any;
    private _recordBefore: boolean = false;
    private _coinNode: cc.Node;
    private _springNode: cc.Node;
    private _leftTime: number;
    private _redLb: cc.Label;
    private _blueLb: cc.Label;
    private _redDot: cc.Node;
    private _blueDot: cc.Node;
    private _lastIndex: any;
    private _checkLast: boolean;
    private _keyboard: any;


    onLoad() {
        super.onLoad();
        // this.addLoadingLayer();
        this.addKeyboard();
    }
    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.btn_keyboard.on("click", this._showKeyboard, this);
    }

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

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

    addPreloadAnima() { }

    onLoadEnd() {
        // TODO 加载完成后的逻辑写在这里, 下面的代码仅供参考

        this.log("onLoadEnd");
        // this.initData();
        // this.initView();
        // this.initListener();

    }
    _status = {
        state: 0,// -1:未开始 0 准备阶段  1 roll 2 判定
        Red: 0,
        Blue: 0,
        RedTime: 0,
        BlueTime: 0,
        step: 0,
        current: "Red",
        time: 0
    };
    playerId;
    isRoomOwner;
    server: GameServer;
    networkHelper: NetworkHelper;
    async initData() {
        // this.initCards();

        this.networkHelper = new NetworkHelper();
        this.initNetworkListener();
        do {
            this.playerId = await this.networkHelper.init("op_L4_R4", 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.randomList = this._randomList;
            this.server.TotalStep = this._cardList.length;
            await this.networkHelper.startFrameSync();
            this.server.addPlayer({
                uuid: this.playerId,
                isAI: false,
            });
            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 || '拼读达人';
            }
        }
        this.networkHelper.sendFrame({
            type: "playerInfo",
            playerId: this.playerId,
            uuid: this.playerId,
            playerName: playerInfo.playerName,
            playerHeadUrl: playerInfo.playerHeadUrl,
        });
    }

    initCards() {

        let cardDatas = [
            {
                id: 1, rJumpId: null, wJumpId: null, word: "cage", url: "",
            },
            {
                id: 2, rJumpId: null, wJumpId: null, word: "cellphone", url: "",
            },
            {
                id: 3, rJumpId: null, wJumpId: null, word: "cheese", url: "",
            },
            {
                id: 4, rJumpId: null, wJumpId: null, word: "city", url: "",
            },
            {
                id: 5, rJumpId: null, wJumpId: null, word: "desk", url: "",
            },
            {
                id: 6, rJumpId: null, wJumpId: null, word: "giant", url: "",
            },
            {
                id: 7, rJumpId: null, wJumpId: null, word: "giraffe", url: "",
            },
            {
                id: 8, rJumpId: null, wJumpId: null, word: "icecream", url: "",
            },
            {
                id: 9, rJumpId: null, wJumpId: null, word: "jeans", url: "",
            },
            {
                id: 10, rJumpId: null, wJumpId: null, word: "legs", url: "",
            },
            {
                id: 11, rJumpId: null, wJumpId: null, word: "orange", url: "",
            },
            {
                id: 12, rJumpId: null, wJumpId: null, word: "rice", url: "",
            },
            {
                id: 13, rJumpId: null, wJumpId: null, word: "rose", url: "",
            },
            {
                id: 14, rJumpId: null, wJumpId: null, word: "scale", url: "",
            },
            {
                id: 15, rJumpId: null, wJumpId: null, word: "school", url: "",
            },
            {
                id: 16, rJumpId: null, wJumpId: null, word: "skunk", url: "",
            },
            {
                id: 17, rJumpId: null, wJumpId: null, word: "splash", url: "",
            },
            {
                id: 18, rJumpId: null, wJumpId: null, word: "splint", url: "",
            },
            {
                id: 19, rJumpId: null, wJumpId: null, word: "spray", url: "",
            },
            {
                id: 20, rJumpId: null, wJumpId: null, word: "spring", url: "",
            },
            {
                id: 21, rJumpId: null, wJumpId: null, word: "square", url: "",
            },
            {
                id: 22, rJumpId: null, wJumpId: null, word: "squid", url: "",
            },
            {
                id: 23, rJumpId: null, wJumpId: null, word: "string", url: "",
            },
            {
                id: 24, rJumpId: null, wJumpId: null, word: "strong", url: "",
            },
        ]
        this._cardList = cc.find("Canvas/road/root/wordCards").children;
        let list = cardDatas;
        for (let i = 0; i < this._cardList.length; ++i) {
            let data = list[i];
            let com = this._cardList[i].addComponent(BoardCardItem);
            com.cardData = data;
            this._randomList.push(i);
        }

    }
    initView() {
        this.initBg();
        this.initLoadingLayer();
    }

    getJumpList() {
        const jumpList = [];
        this._cardList.forEach(node => {
            const itemData = node.getComponent(BoardCardItem);
            if (itemData.rjumpId || itemData.wjumpId) {
                const from = itemData.Id;
                const rto = itemData.rjumpId;
                const wto = itemData.wjumpId;
                jumpList.push({ from, rto, wto });
            }
        });

        this.log(jumpList);
        return jumpList;
    }

    getForceWrongList() {

        const forceWrongList = [];
        this._cardList.forEach((node, index) => {
            const itemData = node.getComponent(BoardCardItem);
            if (!itemData.word) {
                forceWrongList.push(itemData.Id);
            }
        });
        this.log(forceWrongList);
        return forceWrongList;
    }

    initBg() {
        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;

        const endRoot = cc.find("Canvas/endRoot")
        endRoot.scale = this._mapScaleMax;


        this._redDot = cc.find("Canvas/redDot");
        this._redDot.active = false;
        this._blueDot = cc.find("Canvas/blueDot");
        this._blueDot.active = false;

        this._coinNode = cc.find("Canvas/road/board/coinRoot");
        this._coinNode.getChildByName("coinA").active = true;
        this._coinNode.getChildByName("coinB").active = false;

        const blueHead = cc.find("Canvas/road/blueHead");
        const redHead = cc.find("Canvas/road/redHead");
        this._redLb = redHead.getChildByName("lb").getComponent(cc.Label)
        this._blueLb = blueHead.getChildByName("lb").getComponent(cc.Label)

        this._springNode = cc.find("Canvas/road/board/btn");


        this.cat.getComponent(dragonBones.ArmatureDisplay).addEventListener(dragonBones.EventObject.COMPLETE, () => {

            console.log("ani complite");
            this.catAni();
        });

        this.cat.getChildByName("btn").on("click", () => {

            if (this._playingAudio) {
                return;
            }
            this._playingAudio = true;
            this.catAni(true);

        })
    }

    catAni(playAudio?) {
        let state = this._status.state

        if (this._checkLast) {
            this._checkLast = false
            this.cat.getComponent(dragonBones.ArmatureDisplay).playAnimation("normal", 0);
            return
        }
        if (!this.isMySide) {
            this.cat.getComponent(dragonBones.ArmatureDisplay).playAnimation("begin", 0);

            playAudio && this.playAudioByUrl(this.data.waitingTurn, () => {
                this.cat.getComponent(dragonBones.ArmatureDisplay).playAnimation("normal", 0);
                this._playingAudio = false;
            })
            return
        }
        if (state == -1) {
            this.cat.getComponent(dragonBones.ArmatureDisplay).playAnimation("normal", 0);
            this._playingAudio = false;
        } else if (state == 0) {
            this.cat.getComponent(dragonBones.ArmatureDisplay).playAnimation("begin", 0);
            playAudio && this.playAudioByUrl(this.data.waitingWheel, () => {
                this.cat.getComponent(dragonBones.ArmatureDisplay).playAnimation("normal", 0);
                this._playingAudio = false;
            })
        } else if (state == 1) {
            playAudio && this.playAudioByUrl(this.data.waitingPiece, () => {
                this._playingAudio = false;
            })
        }
        else if (state == 2) {
            this._playingAudio = false;
        }
    }

    async updateStatus(status = null) {

        if (!this._loadingDone) return;

        let state = this._status.state;

        switch (state) {
            case -1:
                break;
            case 0:
                if (this.isMySide) {
                    this.normaltheDice();
                    this._canClick = false;
                    await this.showYourTurn();
                    this.blinkTheDice();
                    this._canClick = true;
                } else {
                    this.greyDice();
                    asyncDelay(0.2).then(() => {
                        this.playLocalAudio("otherturn")
                    })
                }

                this._redLb.string = `${this._status.Red}/10`;
                this._blueLb.string = `${this._status.Blue}/10`;

                let costTime = this._status.current == "Red" ? this._status.RedTime : this._status.BlueTime;
                this._leftTime = 150 - (+costTime)

                break;
            case 1:
                if (this.isMySide) {

                } else {
                    this.greyDice();
                }

                break;
            case 2:
                if (this.isMySide) {

                } else {
                    this.greyDice();
                }
                this._leftTime = -1;
                break;

        }

        const blueFrame = cc.find("Canvas/road/blueHead/icon");
        const redFrame = cc.find("Canvas/road/redHead/icon");
        let blinkFrame: cc.Node, stopBlinkFrame: cc.Node;
        if (this._status.current == "Red") {
            blinkFrame = redFrame;
            stopBlinkFrame = blueFrame;
        } else {
            blinkFrame = blueFrame;
            stopBlinkFrame = redFrame;
        }
        blinkFrame.getComponent(cc.Button).interactable = true;
        stopBlinkFrame.getComponent(cc.Button).interactable = false;
    }

    loadingLayer;
    initLoadingLayer() {


        this.loadingLayer.setMaxPlayerNumber(2);
        this.loadingLayer.onLoadFinished(() => {
            this.playAudioByUrl(this.data.gameStartAudio);
            this._loadingDone = true;
            this.updateStatus();
        });

        this.playAudioByUrl(this.data.gameLoadingAudio);
    }

    blinkTheDice() {

        let finger = cc.find("Canvas/road/board/finger")
        finger.zIndex = 10;
        finger.active = true;
        cc.tween(finger)
            .set({ scale: 3 })
            .to(0.2, { scale: 3.3 })
            .to(0.2, { scale: 3.0 })
            .union()
            .repeatForever()
            .start();

    }

    normaltheDice() {

        let finger = cc.find("Canvas/road/board/finger")
        finger.active = false;

        // cc.find("Canvas/road/board").children.forEach((node) => {
        //     node.stopAllActions();
        //     node.color = cc.color(250, 250, 250);
        // });
    }

    greyDice() {

        let finger = cc.find("Canvas/road/board/finger")
        finger.active = false;

        // cc.find("Canvas/road/board").children.forEach((node) => {
        //     node.color = cc.color(150, 150, 150);
        // });
    }


    initListener() {
        // this.boardBtn.on("click", () => {
        if (!this.isMySide || this._status.state != 0 || !this._canClick) {
            return;
        }
        this.playLocalAudio("btn");
        this.normaltheDice();
        this.networkHelper.sendFrame({
            type: "roll",
            uuid: this.myData.uuid,
        });
        // });


    }


    backCoin(right = false) {



        let board = cc.find("Canvas/road/board")
        this._coinNode.parent = board;
        this._coinNode.position = cc.v3(-80, 184);
        this._coinNode.getChildByName("coinA").active = true;
        this._coinNode.getChildByName("coinB").active = false;

        if (right) {
            let point = this._cardList[this._lastIndex].getChildByName("p");
            let dot = this._redDot;
            if (this._status.current == "Blue") {
                dot = this._blueDot;
            }
            let dotNode = cc.instantiate(dot);
            dotNode.active = true;
            dotNode.parent = point;
            dotNode.position = cc.Vec3.ZERO;
        }


    }



    jumpBlock(idx) {

        const targetNode = this._cardList[idx];
        return targetNode;
    }

    getNextRightIdx() {

        const startIdx = this._status[this._status.current];
    }

    async peaceJumpAndSpeak() {
        // let node = cc.find(`Canvas/road/root/piece${this._status.current}`);
        // let nowIdx = this._status[this._status.current];
        // let nextIdx = nowIdx + this._status.step;
        this.playLocalAudio("piece");
        let word = this._cardList[this._status.step].getComponent(BoardCardItem)._word
        if (this.isMySide) {
            let card = this._cardList[this._status.step];
            await asyncDelay(0.5);
            this.openCoursView(card, word);

        }

    }

    async peaceJumpAndBack() {
        let node = cc.find(`Canvas/road/root/piece${this._status.current}`);
        let nowIdx = this._status[this._status.current];
        let nextIdx = nowIdx + this._status.step;
        this.playLocalAudio("piece");
        await this.pieceMove();
        //todo 
        this.playLocalAudio("wrong");
        await this.pieceGoBack();

    }

    async openCoursView(node, word) {
        this.cover.active = true;
        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();
        let icon = cc.instantiate(node);
        icon.parent = this.cover.getChildByName("bg").getChildByName("bar");
        icon.x = 0;
        icon.y = 0;
        icon.scale = Math.min(600 / icon.width, 600 / icon.height);
        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(word);
        await asyncDelay(0.5);
        // 6s 
        probar.getComponent(cc.ProgressBar).schedule(() => {
            probar.getComponent(cc.ProgressBar).progress = total;
            total -= 1 / 30;
            if (total < 0) {
                probar.getComponent(cc.ProgressBar).unscheduleAllCallbacks();
                this._coursewareStoped();
            }
        }, 0.1, 61, 0.1)
    }

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

            this.log("录音开始 单词：" + word);
            window["courseware"]?.startTest(word);
        } 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"]?.stopTest) {
            window["courseware"]?.stopTest((res, b) => {

                if (typeof res == "string") {
                    res = JSON.parse(res);
                }
                this.log("++++++++++++ _coursewareEnd  +++++++++++++++");
                this.log("发音分数： pronunciation=== " + res.result?.pronunciation);
                this._coursewareEnd(res.result?.pronunciation || 0,)
            });
        } else {
            await asyncDelay(3);
            this.log("web 模拟录音评测 结果");
            this._coursewareEnd(Math.random() > 0.7 ? 90 : 60)
        }

    }
    async _coursewareEnd(score: number) {

        // if (this._status.Blue + this._status.step > 4 || this._status.Red + this._status.step > 4) {
        //     score = 50
        // }

        this.log("测评分数：" + score);
        if (score >= 70) {

            let pass = this.cover.getChildByName("bg").getChildByName("pass");
            pass.active = true;
            pass.scale = 0;
            cc.tween(pass).to(0.3, { scale: 0.5 }, { easing: "cubicIn" }).start();
            this.playLocalAudio("right");
            await asyncDelay(1);

            this.cover.active = false;
            this.cat.active = true;
            this.clockNode.active = true;
            this.log("====评测通过=====");
            this.networkHelper.sendFrame({
                type: "right",
                uuid: this.myData.uuid,
            });


        } else {

            let loss = this.cover.getChildByName("bg").getChildByName("loss");
            loss.active = true;
            loss.scale = 0;
            cc.tween(loss).to(0.3, { scale: 0.5 }, { easing: "cubicIn" }).start();
            this.playLocalAudio("wrong");
            await asyncDelay(1);
            this.cover.active = false;
            this.cat.active = true;
            this.clockNode.active = true;
            this.log("====评测不通过=====");
            this.networkHelper.sendFrame({
                type: "wrong",
                uuid: this.myData.uuid,
            });

        }

    }


    roundEndCheck(isRight?) {

        const blueHead = cc.find("Canvas/road/blueHead");
        const redHead = cc.find("Canvas/road/redHead");

        blueHead.getChildByName("tree").getComponent(cc.ProgressBar).progress = this._status.Blue / 10;
        redHead.getChildByName("tree").getComponent(cc.ProgressBar).progress = this._status.Red / 10;

        if (isRight) {

            if (this.isMySide) {
                this._checkLast = true
                this.cat.getComponent(dragonBones.ArmatureDisplay).playAnimation("right", 1);
            }

            if (this._status.current == "Red") {
                redHead.getChildByName("spine").getComponent(dragonBones.ArmatureDisplay).playAnimation("normal", 1);
            } else {
                blueHead.getChildByName("spine").getComponent(dragonBones.ArmatureDisplay).playAnimation("normal", 1)
            }
        } else {

            if (this.isMySide) {
                this._checkLast = true
                this.cat.getComponent(dragonBones.ArmatureDisplay).playAnimation("wrong", 1);
            }
        }


        this.networkHelper.sendFrame({
            type: "stateUpdate",
            uuid: this.myData.uuid,
        });
    }



    getCurrentPiece() {
        if (this._status.current == "Red") {
            return cc.find("Canvas/road/root/pieceRed");
        } else {
            return cc.find("Canvas/road/root/pieceBlue");
        }
    }

    changeSide() {
        // if (this._status.current == "Red") {
        //     this._status.current = "Blue";
        //     console.log("changeSide Blue");
        // } else {
        //     this._status.current = "Red";
        //     console.log("changeSide Red");
        // }
    }

    showYourTurn() {

        this.log("=====showYourTurn===========");
        return new Promise((resolve, reject) => {
            const yourTurn = cc.find("Canvas/yourturn");
            yourTurn.active = true;
            this.playLocalAudio("youturnTip")
            cc.tween(yourTurn)
                .set({ opacity: 0, scale: 5 })
                .to(1, { opacity: 255, scale: 2 })
                .delay(0.5)
                .to(0.5, { opacity: 0 })
                .call(() => {
                    resolve(null);
                })
                .start();
        });
    }



    async fixStep() {

    }


    get isMySide() {

        const playerMe = this.allPlayerList.find(
            (player) => player.uuid == this.playerId
        );
        return playerMe.color == this._status.current

    }
    get myData() {

        if (!this._myData) {
            const playerMe = this.allPlayerList.find(
                (player) => player.uuid == this.playerId
            );
            this._myData = playerMe;
        }

        return this._myData;
    }


    allPlayerList;
    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) => {
                if (this.server) {
                    this.server.onFrameEvent(item.data);
                }

                console.log("event type " + item.data.type);
                console.log("event data" + JSON.stringify(item.data.status));
                if (item.data.type == "SERVER_allPlayerInfo") {
                    this.log(
                        "SERVER_allPlayerInfo: " + JSON.stringify(item.data.playerData, null, 2)
                    );
                    item.data.playerData.forEach((player) => {
                        if (!this.allPlayerList) {
                            this.allPlayerList = [];
                        }

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

                        this.loadPlayerHeadImage();

                        this.loadingLayer.addPlayer(
                            player.name,
                            player.uuid == this.playerId,
                            player.headUrl,
                            player.uuid
                        );
                    });
                } else if (item.data.type == "SERVER_updateStatus") {
                    this._status = JSON.parse(JSON.stringify(item.data.status));
                    this.updateStatus();
                } else if (item.data.type == "SERVER_playerRoll") {
                    this._status = JSON.parse(JSON.stringify(item.data.status));

                    if (this.isMySide) {
                        this.normaltheDice();
                    } else {
                        this.greyDice();
                    }

                    let rollNum = this._status.step
                    this._lastIndex = rollNum;
                    await this.rollTheDice(rollNum);
                    this.log("rollTheDice done");


                    await this.peaceJumpAndSpeak();
                    this.log("peaceJumpAndSpeak done");
                    this.roundEndCheck();

                }
                else if (item.data.type == "SERVER_playerRight") {

                    this._leftTime = -1;
                    !this.isMySide && this.playLocalAudio("right");
                    this._status = JSON.parse(JSON.stringify(item.data.status));
                    this.backCoin(true)
                    await asyncDelay(2);
                    this.roundEndCheck(true);

                } else if (item.data.type == "SERVER_playerWrong") {

                    this._leftTime = -1;
                    !this.isMySide && this.playLocalAudio("wrong");
                    this._status = JSON.parse(JSON.stringify(item.data.status));
                    this.backCoin()
                    await asyncDelay(2);
                    this.roundEndCheck();
                } else if (item.data.type == "SERVER_playerWin") {
                    this._leftTime = -1;
                    this._status = JSON.parse(JSON.stringify(item.data.status));
                    const node = cc.find(
                        `Canvas/road/root/piece${this._status.current}`
                    );
                    await this.fixStep();
                    await this.toEnd()
                    if (this.isMySide) {
                        this.showWin();
                        onHomeworkFinish({ isWin: true });
                    } else {
                        this.showLoss();
                        onHomeworkFinish({ isWin: false });
                    }
                }
            });
        });
    }

    update(dt) {
        if (this._leftTime > 0) {
            this._leftTime -= dt;

            this.clockNode.getChildByName("lb").getComponent(cc.Label).string = "" + Math.round(this._leftTime);

            this.clockNode.getChildByName("lb").color = this._status.current == "Red" ? cc.Color.RED : cc.Color.BLUE;
        }

    }

    pieceGoBack() {

        this.backCoin();

    }

    pieceMove() { }

    async toEnd() {


        const blueHead = cc.find("Canvas/road/blueHead");
        const redHead = cc.find("Canvas/road/redHead");
        blueHead.getChildByName("tree").getComponent(cc.ProgressBar).progress = this._status.Blue / 10;
        redHead.getChildByName("tree").getComponent(cc.ProgressBar).progress = this._status.Red / 10;

        this._redLb.string = `${this._status.Red}/10`;
        this._blueLb.string = `${this._status.Blue}/10`;

        let node = cc.find(`Canvas/road/root/piece${this._status.current}`);
        // let pos = this._bluePointRoot.getChildByName("19").position;

        // if (this._status.current == "Red") {
        //     pos = this._redPointRoot.getChildByName("19").position;
        // }

        // await asyncTweenTo(
        //     node,
        //     0.7,
        //     { x: pos.x, y: pos.y },
        //     { easing: "cubicOut" }
        // );
        if (this.isMySide) {
            this.cat.getComponent(dragonBones.ArmatureDisplay).playAnimation("finish", 1);
        } else {

        }
        await asyncDelay(0.2);

    }

    showWin() {
        let endRoot = cc.find("Canvas/endRoot")
        endRoot.active = true;
        endRoot.opacity = 0;
        cc.tween(endRoot).to(1, { opacity: 255 }).start();
        const win = cc.find("Canvas/endRoot/win");
        win.active = true;
        this.playLocalAudio("win");
    }
    showLoss() {
        let endRoot = cc.find("Canvas/endRoot")
        endRoot.active = true;
        endRoot.opacity = 0;
        cc.tween(endRoot).to(1, { opacity: 255 }).start();
        const loss = cc.find("Canvas/endRoot/loss");
        loss.active = true;
        this.playLocalAudio("loss");
    }

    loadPlayerHeadImage() {
        const red = cc.find("Canvas/road/redHead/icon");
        const blue = cc.find("Canvas/road/blueHead/icon");
        this.allPlayerList.forEach((player) => {
            this.getSpriteFrimeByUrl(player.headUrl, (sf) => {
                if (player.color == "Red") {
                    red.getComponent(cc.Sprite).spriteFrame = sf;

                } else {
                    blue.getComponent(cc.Sprite).spriteFrame = sf;

                }
            });
        });
    }



    finish() {
        // onHomeworkFinish();
    }

    async rollTheDice(num) {
        if (this._isRolling) {
            return;
        }

        this._springNode.getComponent(cc.Animation).play();

        cc.tween(this._coinNode).by(0.14, { y: -10 }).start();

        await asyncDelay(0.14);
        this._coinNode.getChildByName("coinA").active = false;
        this._coinNode.getChildByName("coinB").active = true;

        cc.tween(this._coinNode).by(0.5, { y: 400 }).start();
        await asyncDelay(0.5);
        this._coinNode.parent = this._cardList[num].parent;
        this._coinNode.position = cc.v3(this._cardList[num].x, this._cardList[num].y + 1000, 0)

        cc.tween(this._coinNode).by(0.5, { y: -1000 }, { easing: cc.easeBounceIn.name }).start();
        await asyncDelay(0.5);
        this._coinNode.getChildByName("coinA").active = true;
        this._coinNode.getChildByName("coinB").active = false;
        return Promise.resolve();
    }

    playLocalAudio(audioName) {
        this.node.getChildByName("audio").getChildByName(audioName).getComponent(cc.AudioSource).play();
    }



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

