import {
  asyncDelay,
  asyncPlayDragonBoneAnimation,
  asyncTweenTo,
  onHomeworkFinish,
  RandomInt,
} from "../script/util";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent";
import { NetworkHelper } from "../script/NetworkHelper";
import { GameServer } from "../script/Server";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {
  @property(cc.Prefab)
  loadingLayerPrefab = null; // 等待其他小伙伴加入页面

  @property(cc.Prefab)
  playerOffLineLayerPrefab = null; // 其他人掉线页面

  @property(cc.Prefab)
  endLayerPrefab = null; // 结束页面

  server: GameServer;
  networkHelper: NetworkHelper;
  playerId; // 当前玩家ID
  isRoomOwner; // 是否为房主
  recordWaitCount; // 录音等待倒计时

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

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

  addPreloadAnima() {}

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

  // 初始化数据
  async initData() {
    this.networkHelper = new NetworkHelper();
    this.initNetworkListener();
    do {
      this.playerId = await this.networkHelper.init("l2_boardgame2_tree", 2);
      if (this.playerId === null) {
        console.log("onDestroy");
        this.networkHelper.onDestroy();
      }
      console.log("this.playerId = " + this.playerId);
    } while (this.playerId === null);

    const room = this.networkHelper.room;
    if (this.playerId == room.roomInfo.owner) {
      console.log("房主");
      this.isRoomOwner = true;
      this.server = new GameServer(2, this.networkHelper);
      //   this.server.jumpList = this.getJumpList();
      await this.networkHelper.startFrameSync();
      this.server.addPlayer({
        uuid: this.playerId,
        isAI: false,
      });
      this.server.startMatch();
    }
    await this.initHeadImgAndName();
    this.recordWaitCount = 0;
  }

  // 获取用户头像
  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");
      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,
      playerName: playerInfo.playerName,
      playerHeadUrl: playerInfo.playerHeadUrl,
    });
  }

  // 把卡片数据附加到节点上
  addComponents() {
    // cc.find('Canvas/bg/chessBoard/boardItems').children.forEach(node => {
    //   let itemData = node.getComponent("BoardGame2_ItemData");
    //   if (!itemData) {
    //     itemData = node.addComponent('BoardGame2_ItemData');
    //     let name = node.name;
    //     console.log(name);
    //     if (name == 'start' || name == 'end') {
    //     } else {
    //       let arr = name.split('_');
    //       itemData.letter = arr[1];
    //       itemData.idx = Number(arr[0]);
    //       itemData.word = arr[1];
    //       itemData.jump = 0;
    //     }
    //   }
    // });
  }

  initView() {
    // 初始化界面
    this.initLoadingLayer();
    this.initOfflineLayer();
  }

  // update (dt) {},

  initListener() {
    // 初始化时间监听
  }

  playLocalAudio(audioName) {
    const audio = cc
      .find(`Canvas/res/audio/${audioName}`)
      .getComponent(cc.AudioSource);
    return new Promise((resolve, reject) => {
      const id = cc.audioEngine.playEffect(audio.clip, false);
      cc.audioEngine.setFinishCallback(id, () => {
        resolve(id);
      });
    });
  }

  // 等待游戏开始加入
  loadingLayer;
  initLoadingLayer() {
    cc.log("[Function]initLoadingLayer");
    const loadingLayerBase = cc.find("Canvas/loadingLayerBase");
    const loadingLayerNode = cc.instantiate(this.loadingLayerPrefab);
    loadingLayerBase.addChild(loadingLayerNode);

    this.loadingLayer = loadingLayerNode.getComponent("LoadingLayer");
    this.loadingLayer.setMaxPlayerNumber(2);
    this.loadingLayer.onLoadFinished(() => {});
  }

  // 初始化掉线提示组件
  offlineLayer;
  initOfflineLayer() {
    cc.log("[Function]initOfflineLayer");
    const offlineLayerBase = cc.find("Canvas/offlineLayerBase");
    const offlineLayerNode = cc.instantiate(this.playerOffLineLayerPrefab);
    offlineLayerBase.addChild(offlineLayerNode);

    this.offlineLayer = offlineLayerNode.getComponent("PlayerOffLineLayer");
  }

  // 异步游戏核心事件控制
  allPlayerList;
  initNetworkListener() {
    this.networkHelper.on("playerJoin", (event) => {
      if (this.server) {
        this.server.onPlayerJoin({ data: { joinPlayerId: event.playerId } });
      }
      console.log("playerJoin");
    });
    this.networkHelper.on("playerLeave", (event) => {
      cc.log("playerLeave" + JSON.stringify(event));
      this.offlineLayer.show();
      this.networkHelper.leaveRoom();
    });
    this.networkHelper.on("playerOffLine", (event) => {
      cc.log("playerOffLine" + JSON.stringify(event));
      this.offlineLayer.show();
      this.networkHelper.leaveRoom();
    });
    this.networkHelper.on("gameStart", (event) => {});
    this.networkHelper.on("frameEvent", (event) => {
      cc.log("Frame event");
      event.data.frame.items.forEach(async (item) => {
        if (this.server) {
          this.server.onFrameEvent(item.data);
        }

        if (item.data.type == "SERVER_allPlayerInfo") {
          cc.log(
            "SERVER_allPlayerInfo: " + JSON.stringify(item.data.playerData)
          );
          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") {
          cc.log("SERVER_updateStatus", item.data);
        } else if (item.data.type == "SERVER_playerRoll") {
          cc.log("SERVER_playerRoll", item.data);
        } else if (item.data.type == "SERVER_playerRight") {
          cc.log("SERVER_playerRight");
        } else if (item.data.type == "SERVER_playerWrong") {
          cc.log("SERVER_playerWrong");
        }
      });
    });
  }
}
