<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import Container from "@/components/Container.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 useStore from "@/store";
import { storeToRefs } from "pinia";
const store = useStore();
const { user } = storeToRefs(store);
const start = ref(false);
const showScore = ref(false);
const scores = ref([]);
const total = 36;
const practiseResult = ref({});
const power = ref(0);

const onReady = async () => {
  await createPractiseAPI(total);
  start.value = true;
};

async function onReceiveMessage(content) {
  const messages = JSON.parse(content).data.updates || [];
  messages.forEach((msg) => {
    if (start.value && msg.constructor === MESSAGETYPES.ShootSyncMeArrowID) {
      scores.value.push(msg.target);
      if (scores.value.length === total) {
        showScore.value = true;
      }
    }
    if (msg.constructor === MESSAGETYPES.ShootSyncMePracticeID) {
      practiseResult.value = {
        ...msg.practice,
        arrows: JSON.parse(msg.practice.arrows),
      };
    }
  });
}

function onComplete() {
  uni.navigateBack();
  showScore.value = false;
}

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

onUnmounted(() => {
  uni.$off("socket-inbox", onReceiveMessage);
});
</script>

<template>
  <Container :bgType="1" title="个人单组练习">
    <view>
      <ShootProgress :tips="`请连续射箭${total}支`" :total="120" />
      <BowTarget
        :totalRound="total"
        :currentRound="scores.length + 1"
        :avatar="user.avatarUrl"
        :power="power"
        :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="onComplete"
        :result="practiseResult"
      />
    </view>
    <view :style="{ marginBottom: '10px' }">
      <SButton v-if="!start" :onClick="onReady">准备好了，直接开始</SButton>
    </view>
  </Container>
</template>

<style scoped></style>
