<script setup>
import { ref, watch, onMounted, onBeforeUnmount } from "vue";
import { onShow } from "@dcloudio/uni-app";
import { isGamingAPI, getCurrentGameAPI } from "@/apis";
import { debounce } from "@/util";
import useStore from "@/store";
import { storeToRefs } from "pinia";
const store = useStore();
const { user } = storeToRefs(store);
const props = defineProps({
  signin: {
    type: Function,
    default: () => {},
  },
});
const show = ref(false);
onShow(async () => {
  if (user.value.id) {
    const isGaming = await isGamingAPI();
    show.value = isGaming;
  }
});
watch(
  () => user.value,
  async (value) => {
    if (!value.id) {
      show.value = false;
    } else {
      const isGaming = await isGamingAPI();
      show.value = isGaming;
    }
  }
);
const onClick = debounce(async () => {
  const isGaming = await isGamingAPI();
  show.value = isGaming;
  if (isGaming) {
    const result = await getCurrentGameAPI();
  } else {
    uni.showToast({
      title: "比赛已结束",
      icon: "none",
    });
  }
});
const gameOver = () => {
  show.value = false;
};
onMounted(() => {
  uni.$on("game-over", gameOver);
});
onBeforeUnmount(() => {
  uni.$off("game-over", gameOver);
});
</script>

<template>
  <view v-if="show" class="back-to-game" @click="onClick">
    <image src="../static/back-to-game-bg.png" mode="widthFix" />
    <image src="../static/pk-icon.png" mode="widthFix" />
    <text>返回进行中的对局</text>
    <image src="../static/back.png" mode="widthFix" />
  </view>
</template>

<style scoped>
.back-to-game {
  position: fixed;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  width: 56vw;
  left: calc(50% - 28vw);
  top: 12%;
  z-index: 999;
}
.back-to-game > image:first-child {
  position: absolute;
  width: 100%;
}
.back-to-game > image:nth-child(2) {
  position: relative;
  width: 60px;
  height: 60px;
}
.back-to-game > text:nth-child(3) {
  position: relative;
  font-size: 14px;
}
.back-to-game > image:nth-child(4) {
  position: relative;
  width: 15px;
  margin-left: 5px;
  transform: rotate(180deg);
}
</style>
