<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import { onLoad, onShow, onHide } from "@dcloudio/uni-app";
import Container from "@/components/Container.vue";
import Matching from "@/components/Matching.vue";
import RoundEndTip from "@/components/RoundEndTip.vue";
import TestDistance from "@/components/TestDistance.vue";
import { matchGameAPI } from "@/apis";
import { MESSAGETYPES } from "@/constants";

const gameType = ref(0);
const teamSize = ref(0);
const onComplete = ref(null);

async function stopMatch() {
  uni.$showHint(3);
}

async function onReceiveMessage(messages = []) {
  messages.forEach((msg) => {
    if (msg.constructor === MESSAGETYPES.WaitForAllReady) {
      if (!onComplete.value) {
        onComplete.value = () => {
          if (msg.groupUserStatus) {
            uni.setStorageSync("red-team", msg.groupUserStatus.redTeam);
            uni.setStorageSync("blue-team", msg.groupUserStatus.blueTeam);
            uni.setStorageSync("melee-players", [
              ...msg.groupUserStatus.redTeam,
              ...msg.groupUserStatus.blueTeam,
            ]);
          }
          uni.removeStorageSync("current-battle");
          if (gameType.value == 1) {
            uni.redirectTo({
              url: `/pages/team-battle?battleId=${msg.id}&gameMode=2`,
            });
          } else if (gameType.value == 2) {
            uni.redirectTo({
              url: `/pages/melee-match?battleId=${msg.id}&gameMode=2`,
            });
          }
        };
      }
    }
  });
}

onLoad(async (options) => {
  if (options.gameType && options.teamSize) {
    gameType.value = options.gameType;
    teamSize.value = options.teamSize;
  }
});

onMounted(() => {
  uni.setKeepScreenOn({
    keepScreenOn: true,
  });
  uni.$on("socket-inbox", onReceiveMessage);
});

onBeforeUnmount(() => {
  uni.setKeepScreenOn({
    keepScreenOn: false,
  });
  uni.$off("socket-inbox", onReceiveMessage);
  if (gameType.value && teamSize.value) {
    matchGameAPI(false, gameType.value, teamSize.value);
  }
});

onShow(async () => {
  if (gameType.value && teamSize.value) {
    matchGameAPI(true, gameType.value, teamSize.value);
  }
});

onHide(() => {
  if (gameType.value && teamSize.value) {
    matchGameAPI(false, gameType.value, teamSize.value);
  }
});
</script>

<template>
  <Container title="搜索对手..." :bgType="1" :onBack="stopMatch">
    <view class="container">
      <Matching :stopMatch="stopMatch" :onComplete="onComplete" />
    </view>
  </Container>
</template>

<style scoped>
.container {
  width: 100%;
  height: 100%;
}
</style>
