<script setup>
import { ref, onMounted, onBeforeUnmount } 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 Avatar from "@/components/Avatar.vue";
import BowPower from "@/components/BowPower.vue";
import TestDistance from "@/components/TestDistance.vue";
import BubbleTip from "@/components/BubbleTip.vue";
import audioManager from "@/audioManager";

import { createPractiseAPI, getPractiseAPI } from "@/apis";
import { sharePractiseData } from "@/canvas";
import { wxShare, debounce } from "@/util";
import { MESSAGETYPES } from "@/constants";

import useStore from "@/store";
import { storeToRefs } from "pinia";
const store = useStore();
const { user } = storeToRefs(store);

const start = ref(false);
const scores = ref([]);
const total = 36;
const practiseResult = ref({});
const practiseId = ref("");
const showGuide = ref(false);

const onReady = async () => {
  const result = await createPractiseAPI(total, 3);
  if (result) practiseId.value = result.id;
  scores.value = [];
  start.value = true;
  setTimeout(() => {
    audioManager.play("练习开始");
  }, 300);
};

const onOver = async () => {
  start.value = false;
  practiseResult.value = await getPractiseAPI(practiseId.value);
};

async function onReceiveMessage(messages = []) {
  messages.forEach((msg) => {
    if (msg.constructor === MESSAGETYPES.ShootSyncMeArrowID) {
      if (scores.value.length < total) {
        scores.value.push(msg.target);
        if (practiseId && scores.value.length === total / 2) {
          showGuide.value = true;
          setTimeout(() => {
            showGuide.value = false;
          }, 3000);
        }
        if (scores.value.length === total) {
          setTimeout(onOver, 1500);
        }
      }
    }
  });
}

async function onComplete() {
  const validArrows = (practiseResult.value.arrows || []).filter(
    (a) => a.x !== -30 && a.y !== -30
  );
  if (validArrows.length === total) {
    uni.navigateBack();
  } else {
    practiseId.value = "";
    practiseResult.value = {};
    start.value = false;
    scores.value = [];
    currentRound.value = 0;
  }
}

const onClickShare = debounce(async () => {
  await sharePractiseData("shareCanvas", 3, user.value, practiseResult.value);
  await wxShare("shareCanvas");
});

onMounted(() => {
  uni.setKeepScreenOn({
    keepScreenOn: true,
  });
  uni.$on("socket-inbox", onReceiveMessage);
  uni.$on("share-image", onClickShare);
});

onBeforeUnmount(() => {
  uni.setKeepScreenOn({
    keepScreenOn: false,
  });
  uni.$off("socket-inbox", onReceiveMessage);
  uni.$off("share-image", onClickShare);
  audioManager.stopAll();
});
</script>

<template>
  <Container :bgType="1" title="日常耐力挑战">
    <view>
      <TestDistance v-if="!practiseId" />
      <block v-if="practiseId">
        <ShootProgress
          :tips="`请连续射${total}支箭`"
          :start="start"
          :total="360"
          :onStop="onOver"
        />
        <view class="user-row">
          <Avatar :src="user.avatar" :size="35" />
          <BubbleTip v-if="showGuide" type="normal2">
            <text>完成过半，胜利</text>
            <text>在望！💪</text>
          </BubbleTip>
          <BowPower />
        </view>
        <BowTarget
          :currentRound="scores.length"
          :totalRound="start ? total : 0"
          :scores="scores"
        />
        <ScorePanel
          v-if="start"
          :scores="scores.map((s) => s.ring)"
          :total="total"
          :rowCount="total / 4"
          :margin="1.5"
          :font-size="20"
        />
        <ScoreResult
          v-if="practiseResult.arrows"
          :total="total"
          :rowCount="9"
          :onClose="onComplete"
          :result="practiseResult"
          :tipSrc="`../static/${
            practiseResult.arrows.filter(
              (arrow) => arrow.x !== -30 && arrow.y !== -30
            ).length < total
              ? '2un'
              : ''
          }finish-tip.png`"
        />
        <canvas class="share-canvas" id="shareCanvas" type="2d"></canvas>
      </block>
    </view>
    <view :style="{ marginBottom: '20px' }">
      <SButton v-if="!start" :onClick="onReady">准备好了，直接开始</SButton>
    </view>
  </Container>
</template>

<style scoped></style>
