<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 ScorePanel from "@/components/ScorePanel.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 total = 36;

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);
        if (scores.value.length === total) {
          showScore.value = true;
          websocket.closeWebSocket();
        }
      }
    });
  });
};

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

<template>
  <view class="container">
    <AppBackground type="1" />
    <Header title="个人耐力挑战" />
    <ShootProgress :tips="`请连续射箭${total}支`" total="120" />
    <BowTarget
      :totalRound="total"
      :currentRound="scores.length + 1"
      avatar="../static/avatar.png"
      :power="45"
      :scores="scores"
    />
    <ScorePanel
      v-if="start"
      :scores="scores.map((s) => s.ring)"
      :total="total"
      :rowCount="total / 4"
    />
    <ScoreResult
      :total="total"
      :rowCount="9"
      :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>
