<script setup>
import { ref, watch, onMounted, onUnmounted, nextTick } from "vue";
import { onLoad, onShow, onHide } from "@dcloudio/uni-app";
import Container from "@/components/Container.vue";
import PlayerSeats from "@/components/PlayerSeats.vue";
import Guide from "@/components/Guide.vue";
import SButton from "@/components/SButton.vue";
import SModal from "@/components/SModal.vue";
import { getRoomAPI, destroyRoomAPI, exitRoomAPI, startRoomAPI } from "@/apis";
import { MESSAGETYPES } from "@/constants";
import useStore from "@/store";
import { storeToRefs } from "pinia";
const store = useStore();
const { user } = storeToRefs(store);
const room = ref({});
const roomNumber = ref("");
const owner = ref({});
const opponent = ref({});
const players = ref([]);

const showModal = ref(false);
const battleType = ref(0);
const refreshRoomTimer = ref(null);

async function refreshRoomData() {
  if (!roomNumber.value) return;
  const result = await getRoomAPI(roomNumber.value);
  room.value = result;
  battleType.value = result.battleType;
  (result.members || []).some((m) => {
    if (m.userInfo.id === result.creator) {
      owner.value = {
        id: m.userInfo.id,
        name: m.userInfo.name,
        avatar: m.userInfo.avatar,
      };
      return true;
    }
    return false;
  });
  if (result.battleType === 1) {
    if (user.value.id !== owner.value.id) {
      opponent.value = {
        id: user.value.id,
        name: user.value.nickName,
        avatar: user.value.avatar,
      };
    } else if (result.members.length > 1) {
      result.members.some((m) => {
        if (m.userInfo.id !== owner.value.id) {
          opponent.value = {
            id: m.userInfo.id,
            name: m.userInfo.name,
            avatar: m.userInfo.avatar,
          };
          return true;
        }
        return false;
      });
    }
  } else if (result.battleType === 2) {
    players.value = [];
    const ownerIndex = result.members.findIndex(
      (m) => m.userInfo.id === result.creator
    );
    if (ownerIndex !== -1) {
      players.value.push(result.members[ownerIndex].userInfo);
    } else {
      players.value.push({});
    }
    result.members.forEach((m, index) => {
      if (ownerIndex !== index) players.value.push(m.userInfo);
    });
  }
}

const startGame = async () => {
  const result = await startRoomAPI(room.value.number);
};

async function onReceiveMessage(messages = []) {
  messages.forEach((msg) => {
    if (msg.roomNumber === roomNumber.value) {
      if (msg.constructor === MESSAGETYPES.UserEnterRoom) {
        if (battleType.value === 1) {
          if (msg.userId === room.value.creator) {
            owner.value = {
              id: msg.userId,
              name: msg.name,
              avatar: msg.avatar,
            };
          } else {
            opponent.value = {
              id: msg.userId,
              name: msg.name,
              avatar: msg.avatar,
            };
          }
        }
        if (battleType.value === 2) {
          if (room.value.creator === msg.userId) {
            players.value[0] = {
              id: msg.userId,
              name: msg.name,
              avatar: msg.avatar,
            };
          } else {
            players.value.push({
              id: msg.userId,
              name: msg.name,
              avatar: msg.avatar,
            });
          }
        }
      }
      if (msg.constructor === MESSAGETYPES.UserExitRoom) {
        if (battleType.value === 1) {
          if (msg.userId === room.value.creator) {
            owner.value = {
              id: "",
            };
          } else {
            opponent.value = {
              id: "",
            };
          }
        }
        if (battleType.value === 2) {
          players.value = players.value.filter((p) => p.id !== msg.userId);
        }
      }
      if (msg.constructor === MESSAGETYPES.RoomDestroy) {
        uni.showToast({
          title: "房间已解散",
          icon: "none",
        });
        roomNumber.value = "";
        setTimeout(() => {
          uni.navigateBack();
        }, 1000);
      }
    }
    if (msg.constructor === MESSAGETYPES.WaitForAllReady) {
      if (msg.groupUserStatus) {
        uni.setStorageSync("red-team", msg.groupUserStatus.redTeam);
        uni.setStorageSync("blue-team", msg.groupUserStatus.blueTeam);
        uni.setStorageSync("melee-players", [
          ...msg.groupUserStatus.redTeam,
          ...msg.groupUserStatus.blueTeam,
        ]);
        uni.removeStorageSync("current-battle");
        if (msg.groupUserStatus.config.mode == 1) {
          uni.redirectTo({
            url: `/pages/team-match?battleId=${msg.id}&gameMode=1`,
          });
        } else if (msg.groupUserStatus.config.mode == 2) {
          uni.redirectTo({
            url: `/pages/melee-match?battleId=${msg.id}&gameMode=1`,
          });
        }
      }
    }
  });
}

const destroyRoom = async () => {
  if (roomNumber.value) await destroyRoomAPI(roomNumber.value);
};

const exitRoom = async () => {
  uni.navigateBack();
};

const setClipboardData = () => {
  uni.setClipboardData({
    data: roomNumber.value,
    success() {
      uni.showToast({ title: "复制成功" });
    },
  });
};

const onBack = () => {
  showModal.value = true;
};

onLoad(async (options) => {
  if (options.roomNumber) {
    roomNumber.value = options.roomNumber;
    refreshRoomData();
    refreshRoomTimer.value = setInterval(refreshRoomData, 2000);
  }
});

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

onUnmounted(() => {
  if (refreshRoomTimer.value) clearInterval(refreshRoomTimer.value);
  uni.setKeepScreenOn({
    keepScreenOn: false,
  });
  uni.$off("socket-inbox", onReceiveMessage);
  if (roomNumber.value && owner.value.id !== user.value.id) {
    exitRoomAPI(roomNumber.value);
  }
});

onShow(async () => {
  refreshRoomData();
});
onHide(() => {});
</script>

<template>
  <Container :title="`好友约战 - ${roomNumber}`" :onBack="onBack">
    <view class="standby-phase">
      <Guide>
        <view class="battle-guide">
          <view :style="{ display: 'flex', flexDirection: 'column' }">
            <text :style="{ color: '#fed847' }">弓箭手们，人都到齐了吗?</text>
            <text v-if="battleType === 1">1v1比赛即将开始! </text>
            <text v-if="battleType === 2">大乱斗即将开始! </text>
          </view>
          <view @click="setClipboardData">复制房间号</view>
        </view>
      </Guide>
      <view v-if="battleType === 1" class="team-mode">
        <image
          src="https://static.shelingxingqiu.com/attachment/2025-08-05/dbua9nuf5fyeph7cxi.png"
          mode="widthFix"
        />
        <view>
          <view class="player" :style="{ transform: 'translateY(-60px)' }">
            <image
              :src="owner.avatar || '../static/user-icon.png'"
              mode="widthFix"
            />
            <text>{{ owner.name }}</text>
          </view>
          <image src="../static/versus.png" mode="widthFix" />
          <block v-if="opponent.id">
            <view class="player" :style="{ transform: 'translateY(60px)' }">
              <image
                :src="opponent.avatar || '../static/user-icon.png'"
                mode="widthFix"
              />
              <text v-if="opponent.name">{{ opponent.name }}</text>
            </view>
          </block>
          <block v-else>
            <view class="no-player">
              <image src="../static/question-mark.png" mode="widthFix" />
            </view>
          </block>
        </view>
      </view>
      <PlayerSeats
        v-if="battleType === 2"
        :total="room.count || 10"
        :players="players"
      />
      <view>
        <SButton
          v-if="user.id === owner.id && battleType === 1"
          :disabled="!opponent.id"
          :onClick="startGame"
          >进入对战</SButton
        >
        <SButton
          v-if="user.id === owner.id && battleType === 2"
          :disabled="players.length < 3"
          :onClick="startGame"
          >进入大乱斗</SButton
        >
        <SButton v-if="user.id !== owner.id" disabled>等待房主开启对战</SButton>
        <text class="tips">创建者点击下一步，所有人即可进入游戏。</text>
      </view>
    </view>
    <SModal :show="showModal" :onClose="() => (showModal = false)">
      <view class="btns">
        <SButton :onClick="exitRoom" width="200px" :rounded="20">
          暂时离开
        </SButton>
        <block v-if="owner.id === user.id">
          <view :style="{ height: '20px' }"></view>
          <SButton :onClick="destroyRoom" width="200px" :rounded="20">
            解散房间
          </SButton>
        </block>
      </view>
    </SModal>
  </Container>
</template>

<style scoped>
.standby-phase {
  width: 100%;
  height: calc(100% - 40px);
  overflow-x: hidden;
}
.tips {
  color: #fff9;
  width: 100%;
  text-align: center;
  display: block;
  margin-top: 10px;
  font-size: 12px;
}
.player-unknow {
  width: 40px;
  height: 40px;
  margin: 0 10px;
  border: 1px solid #fff3;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #69686866;
}
.player-unknow > image {
  width: 40%;
}
.team-mode {
  width: calc(100vw - 30px);
  height: 125vw;
  margin: 15px;
}
.team-mode > image:first-child {
  position: absolute;
  width: calc(100vw - 30px);
  z-index: -1;
}
.team-mode > view {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 95%;
}
.player {
  width: 70px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  transform: translateY(-60px);
  color: #fff9;
  font-size: 14px;
}
.player > image {
  width: 70px;
  height: 70px;
  border-radius: 50%;
  background-color: #ccc;
  margin-bottom: 5px;
}
.player > text {
  width: 100px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: center;
}
.team-mode > view > image:nth-child(2) {
  width: 120px;
}
.no-player {
  width: 70px;
  height: 70px;
  border-radius: 50%;
  background-color: #ccc;
  display: flex;
  justify-content: center;
  align-items: center;
  transform: translateY(60px);
}
.no-player > image {
  width: 20px;
  margin-right: 2px;
}
.btns {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.battle-guide {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.battle-guide > view:last-child {
  color: #fed847;
  border: 1px solid #fed847;
  margin-right: 10px;
  padding: 5px 12px;
  border-radius: 20px;
  position: relative;
}
</style>
