<script setup>
import { ref, watch, onMounted, onBeforeUnmount } from "vue";
import audioManager from "@/audioManager";
import { MESSAGETYPES } from "@/constants";
import useStore from "@/store";
import { storeToRefs } from "pinia";
const store = useStore();
const { user } = storeToRefs(store);

const tips = ref("");
const melee = ref(false);
const timer = ref(null);
const sound = ref(true);
const currentSound = ref("");
const currentRound = ref(0);
const currentRoundEnded = ref(false);
const ended = ref(false);
const halfTime = ref(false);
const currentShot = ref(0);
const totalShot = ref(0);

watch(
  () => tips.value,
  (newVal) => {
    let key = "";
    if (newVal.includes("重回")) return;
    if (newVal.includes("红队")) key = "请红方射箭";
    if (newVal.includes("蓝队")) key = "请蓝方射箭";
    if (!sound.value) return;
    if (currentRoundEnded.value) {
      currentRound.value += 1;
      // 播放当前轮次语音
      audioManager.play(
        `第${["一", "二", "三", "四", "五"][currentRound.value - 1]}轮`
      );
    }
    // 延迟播放队伍提示音
    setTimeout(
      () => {
        if (key) audioManager.play(newVal.includes("你") ? "轮到你了" : key);
        currentRoundEnded.value = false;
      },
      currentRoundEnded.value ? 1000 : 0
    );
  }
);

const updateSound = () => {
  sound.value = !sound.value;
  if (!sound.value) audioManager.stop(currentSound.value);
};

async function onReceiveMessage(messages = []) {
  if (!sound.value || ended.value) return;
  messages.forEach((msg) => {
    if (msg.constructor === MESSAGETYPES.ShootResult) {
      if (melee.value && msg.userId !== user.value.id) return;
      if (msg.userId === user.value.id) currentShot.value++;
      if (msg.battleInfo && msg.userId === user.value.id) {
        const players = [
          ...(msg.battleInfo.blueTeam || []),
          ...(msg.battleInfo.redTeam || []),
        ];
        const currentPlayer = players.find((p) => p.id === msg.userId);
        currentShot.value = 0;
        try {
          if (
            currentPlayer &&
            currentPlayer.shotHistory &&
            currentPlayer.shotHistory[msg.battleInfo.currentRound]
          ) {
            currentShot.value =
              currentPlayer.shotHistory[msg.battleInfo.currentRound].length;
          }
        } catch (_) {}
      }
      if (!halfTime.value && msg.target) {
        currentSound.value = msg.target.ring
          ? `${msg.target.ring}环`
          : "未上靶";
        audioManager.play(currentSound.value);
      }
    } else if (msg.constructor === MESSAGETYPES.InvalidShot) {
      if (msg.userId === user.value.id) {
        uni.showToast({
          title: "距离不足，无效",
          icon: "none",
        });
        audioManager.play("射击无效");
      }
    } else if (msg.constructor === MESSAGETYPES.AllReady) {
      const { config } = msg.groupUserStatus;
      if (config && config.mode === 1) {
        totalShot.value = config.teamSize === 2 ? 3 : 2;
      }
      currentRoundEnded.value = true;
      audioManager.play("比赛开始");
    } else if (msg.constructor === MESSAGETYPES.MeleeAllReady) {
      melee.value = true;
      halfTime.value = false;
      audioManager.play("比赛开始");
    } else if (msg.constructor === MESSAGETYPES.CurrentRoundEnded) {
      currentShot.value = 0;
      if (msg.preRoundResult && msg.preRoundResult.currentRound) {
        currentRound.value = msg.preRoundResult.currentRound;
        currentRoundEnded.value = true;
      }
    } else if (msg.constructor === MESSAGETYPES.HalfTimeOver) {
      halfTime.value = true;
      audioManager.play("中场休息");
    } else if (msg.constructor === MESSAGETYPES.MatchOver) {
      audioManager.play("比赛结束");
    } else if (msg.constructor === MESSAGETYPES.FinalShoot) {
      totalShot.value = 0;
      audioManager.play("决金箭轮");
      tips.value = "即将开始...";
      currentRoundEnded.value = false;
    } else if (msg.constructor === MESSAGETYPES.MatchOver) {
      ended.value = true;
    } else if (msg.constructor === MESSAGETYPES.BackToGame) {
      if (msg.battleInfo) {
        melee.value = msg.battleInfo.config.mode === 2;
      }
    }
  });
}

const playSound = (key) => {
  currentSound.value = key;
  audioManager.play(key);
};

const onUpdateTips = (newVal) => {
  tips.value = newVal;
};

const onUpdateTotalShot = (newVal) => {
  currentShot.value = newVal.currentShot;
  totalShot.value = newVal.totalShot;
};

onMounted(() => {
  uni.$on("update-shot", onUpdateTotalShot);
  uni.$on("update-tips", onUpdateTips);
  uni.$on("socket-inbox", onReceiveMessage);
  uni.$on("play-sound", playSound);
});

onBeforeUnmount(() => {
  uni.$off("update-shot", onUpdateTotalShot);
  uni.$off("socket-inbox", onReceiveMessage);
  uni.$off("play-sound", playSound);
  if (timer.value) clearInterval(timer.value);
});
</script>

<template>
  <view class="container">
    <text>{{ (tips || "").replace(/你/g, "").replace(/重回/g, "") }}</text>
    <text v-if="totalShot > 0"> ({{ currentShot }}/{{ totalShot }}) </text>
    <button v-if="!!tips" hover-class="none" @click="updateSound">
      <image
        :src="`../static/sound${sound ? '' : '-off'}-yellow.png`"
        mode="widthFix"
      />
    </button>
  </view>
</template>

<style scoped>
.container {
  width: 50vw;
  color: #fed847;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 500;
}
.container > button:last-child {
  width: 36px;
  height: 36px;
}
.container > button:last-child > image {
  width: 36px;
  min-height: 36px;
}
</style>
