<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import Container from "@/components/Container.vue";
import BattleHeader from "@/components/BattleHeader.vue";
import Guide from "@/components/Guide.vue";
import BowTarget from "@/components/BowTarget.vue";
import ShootProgress from "@/components/ShootProgress.vue";
import PlayersRow from "@/components/PlayersRow.vue";
import Timer from "@/components/Timer.vue";
import BattleFooter from "@/components/BattleFooter.vue";
import ScreenHint from "@/components/ScreenHint.vue";
import SButton from "@/components/SButton.vue";
import Matching from "@/components/Matching.vue";
import { matchGameAPI, readyGameAPI } from "@/apis";
import { MESSAGETYPES, roundsName, getMessageTypeName } from "@/constants";
import useStore from "@/store";
import { storeToRefs } from "pinia";
const store = useStore();
const { user } = storeToRefs(store);
const gameType = ref(0);
const teamSize = ref(0);
const start = ref(false);
const battleId = ref("");
const currentRound = ref(1);
const currentRedPoint = ref(0);
const currentBluePoint = ref(0);
const totalRounds = ref(0);
const power = ref(0);
const scores = ref([]);
const blueScores = ref([]);
const redTeam = ref([]);
const blueTeam = ref([]);
const currentShooterId = ref(0);
const tips = ref("即将开始...");
const seq = ref(0);
const timerSeq = ref(0);
const roundResults = ref([]);
const redPoints = ref(0);
const bluePoints = ref(0);
const showRoundTip = ref(false);
const onComplete = ref(null);

onLoad(async (options) => {
  gameType.value = options.gameType;
  teamSize.value = options.teamSize;
  if (gameType.value && teamSize.value) {
    await matchGameAPI(true, gameType.value, teamSize.value);
  }
});
async function stopMatch() {
  uni.navigateBack();
}
async function readyToGo() {
  if (battleId.value) {
    await readyGameAPI(battleId.value);
    start.value = true;
    timerSeq.value = 0;
  }
}

async function onReceiveMessage(messages = []) {
  messages.forEach((msg) => {
    if (
      !msg.id ||
      (battleId.value && msg.id === battleId.value) ||
      msg.constructor === MESSAGETYPES.WaitForAllReady
    ) {
      console.log("收到消息：", getMessageTypeName(msg.constructor), msg);
    }
    if (!start.value && msg.constructor === MESSAGETYPES.ShootSyncMeArrowID) {
      scores.value.push(msg.target);
      power.value = msg.target.battery;
    }
    if (msg.constructor === MESSAGETYPES.WaitForAllReady) {
      // 这里会掉多次;
      onComplete.value = () => {
        timerSeq.value += 1;
        battleId.value = msg.id;
        redTeam.value = msg.groupUserStatus.redTeam;
        blueTeam.value = msg.groupUserStatus.blueTeam;
      };
    }
    if (msg.id !== battleId.value) return;
    if (msg.constructor === MESSAGETYPES.AllReady) {
      start.value = true;
      timerSeq.value = 0;
      scores.value = [];
      totalRounds.value = msg.groupUserStatus.config.maxRounds;
    }
    if (msg.constructor === MESSAGETYPES.ToSomeoneShoot) {
      scores.value = [];
      blueScores.value = [];
      seq.value += 1;
      currentShooterId.value = msg.userId;
      if (redTeam.value[0].id === currentShooterId.value) {
        tips.value = `请红队射箭-第${roundsName[currentRound.value]}轮`;
      } else {
        tips.value = `请蓝队射箭-第${roundsName[currentRound.value]}轮`;
      }
    }
    if (msg.constructor === MESSAGETYPES.ShootResult) {
      const isRed = redTeam.value.find((item) => item.id === msg.userId);
      if (isRed) {
        scores.value = [msg.target];
      } else {
        blueScores.value = [msg.target];
      }
    }
    if (msg.constructor === MESSAGETYPES.RoundPoint) {
      // bluePoints.value += msg.blueScore;
      // redPoints.value += msg.redScore;
    }
    if (msg.constructor === MESSAGETYPES.CurrentRoundEnded) {
      const result = msg.preRoundResult;
      scores.value = [];
      currentShooterId.value = 0;
      currentBluePoint.value = result.blueScore;
      currentRedPoint.value = result.redScore;
      bluePoints.value += result.blueScore;
      redPoints.value += result.redScore;
      showRoundTip.value = true;
      // 开始下一轮;
      roundResults.value = result.roundResults;
      currentRound.value = result.currentRound + 1;
    }
    if (msg.constructor === MESSAGETYPES.MatchOver) {
      uni.redirectTo({
        url: `/pages/battle-result?battleId=${msg.id}&winner=${msg.endStatus.winner}`,
      });
    }
  });
}
onMounted(() => {
  uni.$on("socket-inbox", onReceiveMessage);
});
onUnmounted(() => {
  uni.$off("socket-inbox", onReceiveMessage);
  if (gameType.value && teamSize.value) {
    matchGameAPI(true, gameType.value, teamSize.value);
  }
});
</script>

<template>
  <Container :title="battleId ? '1V1排位赛' : '搜索对手...'" :bgType="1">
    <view class="container">
      <block v-if="battleId">
        <BattleHeader
          v-if="!start && redTeam.length && blueTeam.length"
          :redTeam="redTeam"
          :blueTeam="blueTeam"
        />
        <Guide noBg v-if="!start">
          <view :style="{ display: 'flex', justifyContent: 'space-between' }">
            <view :style="{ display: 'flex', flexDirection: 'column' }">
              <text :style="{ color: '#fed847' }">请预先射几箭测试</text>
              <text>请确保射击距离只有5米</text>
            </view>
            <BowPower :power="45" />
          </view>
        </Guide>
        <ShootProgress v-if="start" :tips="tips" :seq="seq" :total="15" />
        <PlayersRow
          v-if="start"
          :currentShooterId="currentShooterId"
          :blueTeam="blueTeam"
          :redTeam="redTeam"
        />
        <BowTarget
          mode="team"
          :showE="start && user.id === currentShooterId"
          :power="start ? power : 0"
          :currentRound="currentRound"
          :totalRound="totalRounds"
          :scores="scores"
          :blueScores="blueScores"
          :tips="
            !start && scores.length > 0
              ? `本次射程${scores[scores.length - 1].dst / 100}米，${
                  scores[scores.length - 1].dst / 100 >= 5 ? '已' : '未'
                }达到距离要求`
              : ''
          "
        />
        <BattleFooter
          v-if="start"
          :roundResults="roundResults"
          :redPoints="redPoints"
          :bluePoints="bluePoints"
        />
        <Timer :seq="timerSeq" :callBack="readyToGo" />
        <ScreenHint
          :show="showRoundTip"
          :onClose="() => (showRoundTip = false)"
        >
          <view class="round-end-tip">
            <text>第{{ currentRound - 1 }}轮射击结束</text>
            <view>
              <text>蓝队</text>
              <text>{{ currentBluePoint }}</text>
              <text>分，红队</text>
              <text>{{ currentRedPoint }}</text>
              <text>分</text>
            </view>
            <!-- <text>同分僵局！最后一箭定江山</text>
          <text>10 秒后蓝红双方 决金箭 一箭决胜负</text> -->
          </view>
        </ScreenHint>
      </block>
      <block v-else>
        <Matching
          v-if="!battleId"
          :stopMatch="stopMatch"
          :onComplete="onComplete"
        />
      </block>
    </view>
    <view :style="{ marginBottom: '20px' }">
      <SButton v-if="battleId && !start" :onClick="readyToGo">准备完毕</SButton>
    </view>
  </Container>
</template>

<style scoped>
.container {
  width: 100%;
  height: 100%;
}
</style>
