<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 { MESSAGETYPESV2 } from "@/constants";

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

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

async function onReceiveMessage(msg) {
  if (msg.type === MESSAGETYPESV2.MatchSuccess) {
    matchSuccess.value = true;
    onComplete.value = () => {
      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-battle?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 && !matchSuccess.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 && !matchSuccess.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>
