<script setup>
import { ref, 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, roundsName } from "@/constants";
import websocket from "@/websocket";
const start = ref(false);
const showScore = ref(false);
const scores = ref([]);
const total = 12;
const practiseResult = ref({});
const power = ref(0);

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

  websocket.createWebSocket(token, (content) => {
    const messages = JSON.parse(content).data.updates || [];
    messages.forEach((msg) => {
      if (msg.constructor === MESSAGETYPES.ShootSyncMeArrowID) {
        scores.value.push(msg.target);
        power.value = msg.target.battery;
        if (scores.value.length === total) {
          showScore.value = true;
        }
      }
      if (msg.constructor === MESSAGETYPES.ShootSyncMePracticeID) {
        practiseResult.value = {
          ...msg.practice,
          arrows: JSON.parse(msg.practice.arrows),
        };
      }
    });
  });
};

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

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

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