<template>
  <div class="screen-wrapper" ref="screenRef">
    <div class="screen" id="screen">
      <slot></slot>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted } from "vue";
const screenRef = ref();
const props = defineProps({
  isFoolScreen: {
    type: Boolean,
    default: true,
  },
});
onMounted(() => {
  // 初始化自适应-在刚显示的时候就开始适配一次
  handleScreenAuto(); // 绑定自适应函数-防止浏览器栏变化后不再适配(这里可做节流优化)
  window.onresize = () => dbScreenAuto();
});

const handleScreenAuto = () => {
  const w = 1920; // 设计稿的宽度
  const h = 960; // 设计稿的高度
  const clientWidth = screenRef.value.clientWidth;
  const clientHeight = screenRef.value.clientHeight; // 计算宽高缩放比例
  const scaleW = clientWidth / w;
  const scaleH = clientHeight / h;

  let transformScale;
  // 是否全屏显示
  if (props.isFoolScreen) {
    // 不考虑比例，直接拉伸 (全屏)
    transformScale = `scale(${scaleW}, ${scaleH}) translate(-50%)`;
  } else {
    const scale =
      clientWidth / clientHeight < w / h ? clientWidth / w : clientHeight / h;
    transformScale = `scale(${scale}) translate(-50%)`;
  }
  document.getElementById("screen").style.transform = transformScale;
};

// 防抖 避免调整窗口大小时多次执行
const debounce = (cb, delay = 100) => {
  let timer;
  return () => {
    console.log(1);
    clearTimeout(timer);
    timer = setTimeout(() => {
      cb && cb();
    }, delay);
  };
};
const dbScreenAuto = debounce(handleScreenAuto);
</script>

<style lang="scss" scoped>
.screen-wrapper {
  height: 100%;
  width: 100%;

  .screen {
    display: inline-block;
    width: 1920px;
    height: 960px;
    transform-origin: 0 0;
    position: absolute;
    left: 50%;
    transition: 0.28s;
  }
}
</style>
