<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import AppBackground from "@/components/AppBackground.vue";
import Header from "@/components/Header.vue";
import ShootProgress from "@/components/ShootProgress.vue";
import BowTarget from "@/components/BowTarget.vue";
import ScorePanel2 from "@/components/ScorePanel2.vue";
import ScoreResult from "@/components/ScoreResult.vue";
import SButton from "@/components/SButton.vue";
import { createPractiseAPI } from "@/apis";
import { MESSAGETYPES } from "@/constants";
import websocket from "@/websocket";
const start = ref(false);
const showScore = ref(false);
const scores = ref([]);

const onReady = async () => {
  const result = await createPractiseAPI(12);
  console.log("result", result);
  start.value = true;
  const token = uni.getStorageSync("token");

  websocket.createWebSocket(token, (result) => {
    const messages = JSON.parse(result).data.updates || [];
    messages.forEach((msg) => {
      if (msg.constructor === MESSAGETYPES.ShootSyncMeArrowID) {
        scores.value.push(msg.target);
        console.log("msg:", msg.target);
        if (scores.value.length === 12) {
          showScore.value = true;
          websocket.closeWebSocket();
        }
      }
    });
  });
};

onUnmounted(() => {
  websocket.closeWebSocket();
});
</script>

<template>
  <view class="container">
    <AppBackground :type="1" />
    <Header title="个人单组练习" />
    <ShootProgress tips="请开始射箭第一轮" :start="start" :total="120" />
    <BowTarget
      :totalRound="12"
      :currentRound="scores.length + 1"
      avatar="../static/avatar.png"
      :power="45"
      :scores="scores"
    />
    <ScorePanel2 v-if="start" :scores="scores.map((s) => s.ring)" />
    <ScoreResult
      :total="12"
      :rowCount="6"
      :show="showScore"
      :onClose="() => (showScore = false)"
      :scores="scores.map((s) => s.ring)"
    />
    <SButton v-if="!start" :onClick="onReady">准备好了，直接开始</SButton>
  </view>
</template>

<style scoped>
.container {
  position: relative;
}
</style>
