<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 RoundEndTip from "@/components/RoundEndTip.vue";
import TestDistance from "@/components/TestDistance.vue";
import { matchGameAPI } 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 roundResults = ref([]);
const redPoints = ref(0);
const bluePoints = ref(0);
const showRoundTip = ref(false);
const onComplete = ref(null);
const isFinalShoot = ref(false);

onLoad(async (options) => {
  if (options.battleId) {
    const battleInfo = uni.getStorageSync("current-battle");
    console.log("----battleInfo", battleInfo);
    if (battleInfo) {
      battleId.value = battleInfo.id;
      redTeam.value = battleInfo.redTeam;
      blueTeam.value = battleInfo.blueTeam;
      if (battleInfo.status === 0) {
        const readyRemain = Date.now() / 1000 - battleInfo.startTime;
        console.log(`当前局已进行${readyRemain}秒`);
        if (readyRemain > 0) {
          setTimeout(() => {
            uni.$emit("update-timer", 15 - readyRemain);
          }, 200);
        }
      } else {
        start.value = true;
        currentRound.value = battleInfo.currentRound;
        totalRounds.value = battleInfo.maxRound;
        roundResults.value = battleInfo.roundResults;
        battleInfo.roundResults.forEach((round) => {
          if (round.blueTotal && round.redTotal) {
            if (round.blueTotal === round.redTotal) {
              bluePoints.value += 1;
              redPoints.value += 1;
            } else if (round.blueTotal > round.redTotal) {
              bluePoints.value += 2;
            } else {
              redPoints.value += 2;
            }
          }
        });
        setTimeout(() => {
          if (battleInfo.roundResults[battleInfo.roundResults.length - 1]) {
            scores.value = battleInfo.roundResults[
              battleInfo.roundResults.length - 1
            ].redArrows.filter((item) => !!item.playerId);
            blueScores.value = battleInfo.roundResults[
              battleInfo.roundResults.length - 1
            ].blueArrows.filter((item) => !!item.playerId);
          }
        }, 300);
        if (
          battleInfo.redTeam[0].shotHistory[battleInfo.currentRound] ||
          battleInfo.blueTeam[0].shotHistory[battleInfo.currentRound]
        ) {
          roundResults.value.push({
            redArrows: battleInfo.redTeam[0].shotHistory[
              battleInfo.currentRound
            ].filter((item) => !!item.playerId),
            blueArrows: battleInfo.blueTeam[0].shotHistory[
              battleInfo.currentRound
            ].filter((item) => !!item.playerId),
          });
        } else if (battleInfo.currentRound < 5) {
          roundResults.value.push({
            redArrows: [],
            blueArrows: [],
          });
        }
      }
      if (battleInfo.status !== 11) return;
      if (battleInfo.firePlayerIndex) {
        currentShooterId.value = battleInfo.firePlayerIndex;
        if (redTeam.value[0].id === currentShooterId.value) {
          tips.value = `请红队射箭-第${roundsName[currentRound.value]}轮`;
        } else {
          tips.value = `请蓝队射箭-第${roundsName[currentRound.value]}轮`;
        }
      }
      if (battleInfo.fireTime > 0) {
        const remain = Date.now() / 1000 - battleInfo.fireTime;
        console.log(`当前箭已过${remain}秒`);
        if (remain > 0 && remain <= 15) {
          // 等渲染好再通知
          setTimeout(() => {
            uni.$emit("update-ramain", 15 - remain);
          }, 300);
        }
      }
    }
  } else {
    gameType.value = options.gameType;
    teamSize.value = options.teamSize;
    if (gameType.value && teamSize.value) {
      await matchGameAPI(true, gameType.value, teamSize.value);
    }
  }
});
async function stopMatch() {
  uni.$showHint(3);
}

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 (msg.constructor === MESSAGETYPES.WaitForAllReady) {
      // 这里会掉多次;
      onComplete.value = () => {
        battleId.value = msg.id;
        redTeam.value = msg.groupUserStatus.redTeam;
        blueTeam.value = msg.groupUserStatus.blueTeam;
        uni.$hideHint();
      };
    }
    if (msg.id !== battleId.value) return;
    if (msg.constructor === MESSAGETYPES.AllReady) {
      start.value = true;
      totalRounds.value = msg.groupUserStatus.config.maxRounds;
      roundResults.value.push({
        redArrows: [],
        blueArrows: [],
      });
    }
    if (msg.constructor === MESSAGETYPES.ToSomeoneShoot) {
      if (currentShooterId.value !== msg.userId) {
        seq.value += 1;
        currentShooterId.value = msg.userId;
        if (redTeam.value[0].id === currentShooterId.value) {
          tips.value = "请红队射箭-";
        } else {
          tips.value = "请蓝队射箭-";
        }
        if (isFinalShoot.value) {
          tips.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.push(msg.target);
      else blueScores.value.push(msg.target);
      if (roundResults.value[currentRound.value - 1]) {
        if (isRed && roundResults.value[currentRound.value - 1].redArrows) {
          roundResults.value[currentRound.value - 1].redArrows.push(msg.target);
        }
        if (!isRed && roundResults.value[currentRound.value - 1].blueArrows) {
          roundResults.value[currentRound.value - 1].blueArrows.push(
            msg.target
          );
        }
      } else {
        roundResults.value.push({
          redArrows: [],
          blueArrows: [],
        });
      }
    }
    if (msg.constructor === MESSAGETYPES.CurrentRoundEnded) {
      const result = msg.preRoundResult;
      scores.value = [];
      blueScores.value = [];
      currentShooterId.value = 0;
      currentBluePoint.value = result.blueScore;
      currentRedPoint.value = result.redScore;
      bluePoints.value += result.blueScore;
      redPoints.value += result.redScore;
      // roundResults.value = result.roundResults;
      currentRound.value = result.currentRound + 1;
      if (result.currentRound < 5) {
        roundResults.value.push({
          redArrows: [],
          blueArrows: [],
        });
        showRoundTip.value = true;
      }
    }
    if (msg.constructor === MESSAGETYPES.FinalShoot) {
      if (!isFinalShoot.value) {
        isFinalShoot.value = true;
        showRoundTip.value = true;
        tips.value = "准备开始决金箭";
      }
    }
    if (msg.constructor === MESSAGETYPES.MatchOver) {
      uni.setStorageSync("last-battle", msg.endStatus);
      if (msg.endStatus.noSaved) {
        uni.showToast({
          title: "游戏结束",
          icon: "none",
        });
        uni.navigateBack();
      } else {
        uni.redirectTo({
          url: `/pages/battle-result?battleId=${msg.id}`,
        });
      }
    }
  });
}
const onBack = () => {
  if (battleId.value) {
    uni.$showHint(2);
  } else {
    uni.$showHint(3);
  }
};
onMounted(() => {
  uni.setKeepScreenOn({
    keepScreenOn: true,
  });
  uni.$on("socket-inbox", onReceiveMessage);
});
onUnmounted(() => {
  uni.setKeepScreenOn({
    keepScreenOn: false,
  });
  uni.$off("socket-inbox", onReceiveMessage);
  if (gameType.value && teamSize.value && !battleId.value) {
    matchGameAPI(false, gameType.value, teamSize.value);
  }
});
</script>

<template>
  <Container
    :title="battleId ? '1V1排位赛' : '搜索对手...'"
    :bgType="1"
    :onBack="onBack"
  >
    <view class="container">
      <block v-if="battleId">
        <BattleHeader
          v-if="!start && redTeam.length && blueTeam.length"
          :redTeam="redTeam"
          :blueTeam="blueTeam"
        />
        <TestDistance v-if="!start" :guide="false" />
        <ShootProgress
          :show="start"
          :tips="tips"
          :seq="seq"
          :total="15"
          :currentRound="currentRound"
          :battleId="battleId"
        />
        <PlayersRow
          v-if="start"
          :currentShooterId="currentShooterId"
          :blueTeam="blueTeam"
          :redTeam="redTeam"
        />
        <BowTarget
          v-if="start"
          mode="team"
          :power="start ? power : 0"
          :currentRound="currentRound"
          :totalRound="totalRounds"
          :scores="scores"
          :blueScores="blueScores"
        />
        <BattleFooter
          v-if="start"
          :roundResults="roundResults"
          :redPoints="redPoints"
          :bluePoints="bluePoints"
        />
        <Timer v-if="!start" />
        <ScreenHint
          :show="showRoundTip"
          :onClose="() => (showRoundTip = false)"
          :mode="isFinalShoot ? 'tall' : 'normal'"
        >
          <RoundEndTip
            :isFinal="isFinalShoot"
            :round="currentRound - 1"
            :bluePoint="currentBluePoint"
            :redPoint="currentRedPoint"
            :roundData="
              roundResults[roundResults.length - 2]
                ? roundResults[roundResults.length - 2]
                : []
            "
            :onAutoClose="() => (showRoundTip = false)"
          />
        </ScreenHint>
      </block>
      <block v-else>
        <Matching
          v-if="!battleId"
          :stopMatch="stopMatch"
          :onComplete="onComplete"
        />
      </block>
    </view>
  </Container>
</template>

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