
import EndLayer from "../script/layers/endLayer_PK_Game";
import GameLayer from "../script/layers/gameLayer_PK_Game";
import HomeLayer from "../script/layers/homeLayer_PK_Game";
import MatchLayer from "../script/layers/matchLayer_PK_Game";
import MyInfo from "../script/layers/myInfo_PK_Game";
import RankLayer from "../script/layers/rankLayer_PK_Game";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent_PK_Game";
import { NetworkHelper } from "../script/NetworkHelper_PK_Game";
import { GameServer } from "../script/Server_PK_Game";
import { asyncDelay, getLv } from "../script/util_PK_Game";


const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {


    @property(cc.Node)
    homeLayer = null;
    @property(cc.Node)
    matchLayer = null;
    @property(cc.Node)
    gameLayer = null;
    @property(cc.Node)
    endLayer = null;
    @property(cc.Node)
    rankLayer = null;
    @property(cc.Node)
    myInfoNode = null;

    @property(cc.Button)
    btn_back = null;
    @property(cc.Button)
    btn_rule = null;
    @property(cc.Button)
    btn_single = null;
    private _status: any;
    homeLayerCom: HomeLayer;
    matchLayerCom: MatchLayer;
    gameLayerCom: GameLayer;
    endLayerCom: EndLayer;
    rankLayerCom: RankLayer;
    myInfoCom: MyInfo;
    layerIndex: number;

    headUrl: "http://staging-teach.cdn.ireadabc.com/0751c28419a0e8ffb1f0e84435b081ce.png"
    userName: "test"
    otherData: any;
    rankData: any;
    myrank: number;

    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 加载完成后的逻辑写在这里, 下面的代码仅供参考

        cc.log("============")
        cc.log(this.data);
        this.log("onLoadEnd");
        this.initData();
        this.initView();
        this.initListener();

    }

    //------------
    initData() {
        this.data.url = this.data.url || this.headUrl;
        this.data.name = this.data.name || this.userName;
        this.rankData = this.data.rank;
        let localScore = cc.sys.localStorage.getItem("mySocre");
        cc.log("localScore = " + localScore)
        this.data.myInfo.score = localScore || this.data.myInfo.score;
        cc.sys.localStorage.setItem("mySocre", this.data.myInfo.score);
        this.rankData.sort((a, b) => {
            return b.score - a.score;
        })

    }
    initView() {
        const bgNode = cc.find('Canvas/bg');
        bgNode.scale = this._mapScaleMax;
        // this.node.getChildByName("cover").scale = this._mapScaleMin;

        this.homeLayerCom = this.homeLayer.getComponent(HomeLayer);
        this.matchLayerCom = this.matchLayer.getComponent(MatchLayer);
        this.gameLayerCom = this.gameLayer.getComponent(GameLayer);
        this.endLayerCom = this.endLayer.getComponent(EndLayer);
        this.rankLayerCom = this.rankLayer.getComponent(RankLayer);
        this.myInfoCom = this.myInfoNode.getComponent(MyInfo);

        this.gameLayerCom.mainCom = this;
        this.endLayerCom.mainCom = this;
        this.rankLayerCom.mainCom = this;
        this.homeLayer.active = true;
        this.matchLayer.active = false;
        this.gameLayer.active = false;
        this.endLayer.active = false;
        this.rankLayer.active = false;
        this.myInfoNode.active = true;

        this.myInfoCom.mainCom = this;

        this.layerIndex = 0;
        this.rankLayerCom.init(this.rankData);
        this.data.myInfo.rank = this.rankLayerCom.setMyInfo(this.data.myInfo)
        this.myInfoCom.init(this.data.myInfo)

        this.homeLayerCom.initCup(this.data.myInfo.score)
        this.homeLayerCom.startCallBack = this.onStartGame.bind(this);

        // this.btn_back.node.on("click", this.onClickBack, this)

        // this.btn_rule.node.on("click", this.onClickBack, this)

        // this.btn_single.node.on("click", this.onClickBack, this)

    }

    onClickBack() {
        this.playLocalAudio("btn")
        switch (this.layerIndex) {
            case 0:
                // 推到大厅
                break;
            case 1:
                // 推到home 界面
                this.myInfoCom.show()
                this.homeLayer.active = true;
                this.matchLayer.active = false;


                break;
            case 2:
                break;

        }

    }


    backHome() {

        this.homeLayer.active = true;
        this.matchLayer.active = false;
        this.gameLayer.active = false;
        this.endLayer.active = false;
        this.rankLayer.active = false;
        this.myInfoCom.show();
    }

    async onStartGame() {

        this.layerIndex = 1;
        this.playLocalAudio("btn")
        this.homeLayer.active = false;
        this.matchLayer.active = true;
        this.myInfoCom.hide()
        this.matchLayerCom.startMatch(this.data.myInfo);
        await asyncDelay(1)
        this.openNetSever();

    }

    openGameLayer() {
        this.layerIndex = 2;


        this.homeLayer.active = false;
        this.matchLayer.active = false;
        this.gameLayer.active = true;

        this.gameLayerCom.init(this.data.myInfo, this.otherData, () => {
            this.networkHelper.sendFrame({
                type: "gamePrepare",
                uuid: this.playerId,
            });
        });
    }

    showRank() {

        this.playLocalAudio("btn")
        this.myInfoCom.openMask();
        this.rankLayer.active = true;
        this.rankLayerCom.show();
    }
    hideRank() {
        this.playLocalAudio("btn")
        this.myInfoCom.hideMask();
    }

    showRish() {


    }

    initListener() {




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


        this.networkHelper = new NetworkHelper();
        this.initNetworkListener();
        do {
            this.playerId = await this.networkHelper.init("pk_game", 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.jumpList = this.getJumpList();
            // this.server.randomList = this._randomList;
            // this.server.TotalStep = this._cardList.length;

            await this.networkHelper.startFrameSync();
            this.server.addPlayer({
                uuid: this.playerId,
                isAI: false,
                lv: this.data.myInfo.lv,
                score: this.data.myInfo.score,
                rank: this.data.myInfo.rank,
            });
            this.server.initQuestion(this.data.question);
            let lv = getLv(this.data.myInfo.score)
            this.server.startMatch(lv);
        }
        await this.initHeadImgAndName();
    }

    async initHeadImgAndName() {
        const playerInfo: any = {
            playerHeadUrl: this.data.url || this.headUrl,
            playerName: this.data.name || this.userName,
        };
        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,
        // });
    }



    roundEndCheck(isRight?) {



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






    get myData() {


        return
    }


    allPlayerList;
    initNetworkListener() {
        this.networkHelper.on("playerJoin", (event) => {
            if (this.server) {
                this.server.onPlayerJoin(
                    {
                        data:
                        {
                            joinPlayerId: event.playerId,
                            lv: event.lv,
                            score: event.score,
                            rank: event.rank,
                        }
                    });
            }
            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.otherData = player;

                            this.playLocalAudio("match")
                            this.matchLayerCom.addOther(this.otherData, this.openGameLayer.bind(this));
                        }

                    });
                } else if (item.data.type == "SERVER_updateStatus") {
                    this._status = JSON.parse(JSON.stringify(item.data.status));
                    // this.updateStatus();
                } else if (item.data.type == "SERVER_gameEv") {
                    this._status = JSON.parse(JSON.stringify(item.data.status));
                    if (this._status?.state == 1) {
                        let question = JSON.parse(JSON.stringify(item.data.question));
                        this.gameLayerCom.initQuestion(question, this._status?.index);
                    }

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

                    this.gameLayerCom.settle(item.data)

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


                    let localScore = cc.sys.localStorage.getItem("mySocre");
                    this.data.myInfo.score = localScore || this.data.myInfo.score;
                    cc.sys.localStorage.setItem("mySocre", this.data.myInfo.score);
                    this.data.myInfo.rank = this.rankLayerCom.setMyInfo(this.data.myInfo)

                    this.gameLayerCom.hide()
                    this.myInfoCom.init(this.data.myInfo);
                    this.myInfoCom.show();
                    this.endLayer.active = true;
                    this.endLayerCom.init(item.data, this.data.myInfo, this.otherData);

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

                }
            });
        });
    }

    async toEnd() {


    }

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



    onCloseCover() {

        this.node.getChildByName("cover").active = false;

    }

    finish() {
        // onHomeworkFinish();
    }


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



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