<template>
  <div class="h-start-game" v-if="showGameVisible">
    <van-loading color="#fff" vertical v-if="!gameStore.startGameInfo.url">
      Game Loading...
    </van-loading>
    <iframe
      allow="fullscreen"
      id="iframe"
      ref="iframeRef"
      :style="{
        width: gameStore.startGameInfo.y ? '10rem !important' : '100vw',
      }"
      frameborder="0"
    >
    </iframe>

    <div id="id-top">
      <div class="back">
        <h-img type="local"  @click="close" class="back-icon" src="game/game-back.png" />
        <div class="text">Sair do jogo e voltar para a página inicial.</div>
      </div>
      <div id="id-toggle" @click="topToggle">
        <svg
          id="id-arrow"
          t="1729504327853"
          viewBox="0 0 1024 1024"
          version="1.1"
          xmlns="http://www.w3.org/2000/svg"
          p-id="3627"
          xmlns:xlink="http://www.w3.org/1999/xlink"
        >
          <path
            d="M954.176 316.672L894.752 256 512 646.656 129.248 256 69.824 316.672 512 768z"
            fill="#44444455"
            p-id="3628"
          ></path>
        </svg>
      </div>
      <button id="id-game-btn" @click="exit"></button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watchEffect, nextTick, inject } from "vue";
import { useGameStore } from "@/stores/modules/game";
import { useUserStore } from "@/stores/modules/user";
import { useBaseStore } from "@/stores/modules/base";
import emitter from "@/utils/eventBus";
const socket: any = inject("socket");
const iframeRef = ref();

const showGameVisible = ref(false);

const useStore = useUserStore();

const gameStore = useGameStore();

const baseStore = useBaseStore();

// const props = defineProps({
//   modelValue: { type: Boolean, default: false, required: false },
//   modelWidth: { type: Boolean, default: false, required: false },
// });

watchEffect(() => {
  if (gameStore.startGameInfo.url && showGameVisible.value) {
    nextTick(() => {
      iframeRef.value.height = gameStore.startGameInfo.y
        ? baseStore.innerHeight + "px"
        : "100%";
      const b = iframeRef.value.contentDocument;
      b.body.style.background = "#212126";
      let src = gameStore.startGameInfo.url;
      const iframe: HTMLIFrameElement | null = document.getElementById(
        "iframe"
      ) as HTMLIFrameElement;
      if (iframe) {
        iframeRef.value.src = src;
      }
    });
  }
});

// const emit = defineEmits(["update:modelValue", "close"]);

const close = async () => {
  const iframe: HTMLIFrameElement | null = document.getElementById(
    "iframe"
  ) as HTMLIFrameElement;
  iframe.parentNode?.removeChild(iframe);
  console.log(iframe, "iframe销毁");
  showGameVisible.value = false;
  gameStore.clearGameUrl();
  // socket.connectMsg();
  await useStore.getUserInfo();
};

const open = async () => {
  showGameVisible.value = true;
};

emitter.on("closeGame", close);

emitter.on("openGame", open);

let isNative = false;
let exitStr = "quiz_game_exit";

window.addEventListener("resize", function (event) {
  let isY = window.matchMedia("(orientation: portrait)").matches;
  let ele = document.getElementById("id-top");
  let style = window.getComputedStyle(ele);
  if (style.top !== "0px") ele.style.top = `-${isY ? 50 : 60}px`;
});

function topToggle() {
  let topHeight = window.matchMedia("(orientation: portrait)").matches
    ? 50
    : 60;
  let ele = document.getElementById("id-top");
  let style = window.getComputedStyle(ele);

  if (style.top !== `-${topHeight}px` && style.top !== "0px") return;

  let ele1 = document.getElementById("id-arrow");
  let style1 = window.getComputedStyle(ele1);
  let scaleY = style1.transform.split(",")[3];
  ele1.style.transform = `translate(-50%, -50%) scaleY(${-scaleY})`;

  function collapse(value1, value2, setp) {
    if (value1 == value2) return;

    setTimeout(() => {
      value1 += setp;
      ele.style.top = `${value1}px`;
      if (value1 != value2) collapse(value1, value2, setp);
    }, 1);
  }

  if (style.top === `-${topHeight}px` && scaleY == 1) {
    collapse(-topHeight, 0, 1);
  } else {
    collapse(0, -topHeight, -1);
  }
}

function exit() {
  if (isNative) {
    document.location = `quizgame://${exitStr}`;
  } else {
    parent.postMessage(exitStr, "*");
  }
}

window.onload = function () {
  let search = window.location.search;
  if (search.includes("n=true")) isNative = true;
  let match = search.match(/^.*?\?n=\S{4,5}&url=(.*)/);
  let iframe = document.getElementById("id-game-frame");
  if (match[1]) iframe.src = match[1];

  setTimeout(() => {
    topToggle();
  }, 1000);
  setTimeout(() => {
    topToggle();
  }, 1500);
};

// function initIframe() {
//   const deviceWidth = document.body.clientWidth;
//   // const deviceHeight = document.body.clientHeight;
//   iframeRef.value!.scrollTop = 0;
//   iframeRef.value!.style.width = Number(deviceWidth) + "px";
//   // iframeRef.value!.style.height = Number(deviceHeight) + "px";
// }

// function forceLandscapeScreenHandle() {
//   const html = document.getElementsByTagName("html")[0];
//   const width = html.clientWidth;
//   const height = html.clientHeight;
//   console.log(width, height);
//   const max = width > height ? width : height;
//   const min = width > height ? height : width;
//   console.log(min, max);
//   iframeRef.value.style.width = min + "px";
//   iframeRef.value.style.height = max + "px";
// }

// function onWindowSizeChanged() {
//   window.addEventListener("resize", forceLandscapeScreenHandle);
// }

// function init() {
//   forceLandscapeScreenHandle();

//   // 这里监控
//   onWindowSizeChanged();
// }

// watch(props, () => {
//   if (props.modelValue) {
//     setTimeout(() => {
//       init();
//     }, 1000);
//   }
// });
// defineExpose({
//   initIframe,
// });
</script>

<style lang="scss" scoped>
.h-start-game {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  z-index: 2147483641;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #212126;
  #iframe {
    position: absolute;
    top: 0;
    z-index: 2;
  }
  .back {
    position: fixed;
    top: 0.1rem;
    left: 0.1rem;
    z-index: 5;
    cursor: pointer;
    &-icon {
      width: 1rem;
      height: 1rem;
    }
  }
}
// @media screen and (orientation: landscape) {
//   /*竖屏样式*/
//   .h-iframe {
//     transform-origin: 0 0;
//     transform: rotateZ(90deg) translateY(-100%);
//   }
// }
* {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

body {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background-color: black;
  overflow: hidden;
}

#id-top {
  position: fixed;
  top: -60px;
  left: 0px;
  right: 0px;
  width: 100%;
  height: 60px;
  background-color: rgba(255, 255, 255, 0.4);
  z-index: 1000;
}

#id-top .back {
  position: absolute;
  display: flex;
  margin: 0 auto;
  left: 0;
  right: 0;
  justify-content: center;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
}

#id-toggle {
  position: relative;
  top: 60px;
  left: 50%;
  transform: translate(-50%);
  width: 100px;
  height: 30px;
  border-bottom-left-radius: 18px;
  border-bottom-right-radius: 18px;
  background-color: rgba(255, 255, 255, 0.4);
}

#id-toggle svg {
  position: relative;
  top: 50%;
  left: 50%;
  writing-mode: vertical-rl;
  transform: translate(-50%, -50%) scaleY(1);
}

#id-game-btn {
  position: relative;
  background: url("01.png") repeat;
  background-size: cover;
  border-style: none;
  top: -22px;
  left: 10px;
  width: 52px;
  height: 42px;
}

#id-game-btn:active {
  transform: scale(0.9);
}

#id-arrow {
  width: 22px;
  height: 22px;
}

@media only screen and (orientation: portrait) {
  #id-top {
    position: fixed;
    top: -50px;
    left: 0px;
    right: 0px;
    width: 100%;
    height: 50px;
    background-color: rgba(255, 255, 255, 0.4);
    z-index: 1000;
  }

  #id-toggle {
    position: relative;
    top: 50px;
    left: 50%;
    transform: translate(-50%);
    width: 80px;
    height: 20px;
    border-bottom-left-radius: 12px;
    border-bottom-right-radius: 12px;
    background-color: rgba(255, 255, 255, 0.4);
  }

  #id-game-btn {
    position: relative;
    background: url("01.png") no-repeat;
    background-size: cover;
    border-style: none;
    top: -13px;
    left: 5px;
    width: 32px;
    height: 28px;
  }

  #id-arrow {
    width: 16px;
    height: 16px;
  }
}

.full {
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
}
</style>
