<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 ScorePanel2 from "@/components/ScorePanel2.vue";
import ScoreResult from "@/components/ScoreResult.vue";
import SButton from "@/components/SButton.vue";
import Avatar from "@/components/Avatar.vue";
import BowPower from "@/components/BowPower.vue";
import StartCountdown from "@/components/StartCountdown.vue";
import { createPractiseAPI, getHomeData } from "@/apis";
import { MESSAGETYPES, roundsName } from "@/constants";
import useStore from "@/store";
import { storeToRefs } from "pinia";
const store = useStore();
const { user } = storeToRefs(store);
const { updateUser } = store;
const startCount = ref(false);
const start = ref(false);
const showScore = ref(false);
const scores = ref([]);
const total = 12;
const currentRound = ref(0);
const practiseResult = ref({});
const power = ref(0);

const onReady = async () => {
  await createPractiseAPI(total);
  currentRound.value = 0;
  scores.value = [];
  startCount.value = true;
};

const onStart = () => {
  start.value = true;
  scores.value = [];
  currentRound.value = 0;
};

async function onReceiveMessage(messages = []) {
  messages.forEach((msg) => {
    if (msg.constructor === MESSAGETYPES.ShootSyncMeArrowID) {
      scores.value.push(msg.target);
      currentRound.value += 1;
      if (currentRound.value === 4) {
        currentRound.value = 1;
      }
      power.value = msg.target.battery;
      if (scores.value.length === total) {
        showScore.value = true;
      }
    }
    if (msg.constructor === MESSAGETYPES.ShootSyncMePracticeID) {
      start.value = false;
      practiseResult.value = {
        ...msg.practice,
        arrows: JSON.parse(msg.practice.arrows),
      };
    }
  });
}

async function onComplete() {
  const result = await getHomeData();
  if (result.user) updateUser(result.user);
  uni.navigateBack();
}

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

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

<template>
  <Container :bgType="1" title="个人单组练习">
    <view>
      <ShootProgress
        :tips="`${
          !start || scores.length === 12
            ? ''
            : `请开始射箭第${roundsName[Math.ceil((scores.length + 1) / 3)]}轮`
        }`"
        :start="start"
        :total="120"
      />
      <view class="infos">
        <Avatar :src="user.avatar" :size="35" />
        <BowPower :power="power" />
      </view>
      <BowTarget
        :totalRound="start ? total / 4 : 0"
        :currentRound="currentRound"
        :scores="scores"
        :tips="
          !start && scores.length > 0
            ? `本次射程${scores[scores.length - 1].dst / 100}米，${
                scores[scores.length - 1].dst / 100 >= 5 ? '已' : '未'
              }达到距离要求`
            : ''
        "
      />
      <ScorePanel2 v-if="start" :scores="scores.map((s) => s.ring)" />
      <ScoreResult
        :total="total"
        :rowCount="6"
        :show="showScore"
        :onClose="onComplete"
        :result="practiseResult"
        :dataType="2"
      />
      <StartCountdown :start="startCount" :onFinish="onStart" />
    </view>
    <view :style="{ marginBottom: '20px' }">
      <SButton v-if="!startCount" :onClick="onReady">
        准备好了，直接开始
      </SButton>
    </view>
  </Container>
</template>

<style scoped>
.infos {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 15px;
  padding-top: 15px;
}
</style>
