// 用法：
// width: calc(950 / v-bind('windowSizeWhenDesignForRef') * v-bind('windowSizeInCssForRef'));

import { onBeforeUnmount, ref } from 'vue'

export default function useSizeAdapt(windowWidthWhenDesign = 1920, windowHeightWhenDesign = 1080, needReactivity = true) {
  const windowSizeInCssForRef = ref('')
  const windowSizeWhenDesignForRef = ref('')
  const scaleRate = ref(-1)

  function compute() {
    if (window.innerWidth / window.innerHeight > windowWidthWhenDesign / windowHeightWhenDesign) {
      windowSizeWhenDesignForRef.value = windowHeightWhenDesign
      windowSizeInCssForRef.value = window.innerHeight + 'px' // 用100vh的话在移动端会有兼容性问题。
      scaleRate.value = windowHeightWhenDesign / window.innerHeight
    } else {
      windowSizeWhenDesignForRef.value = windowWidthWhenDesign
      windowSizeInCssForRef.value = window.innerWidth + 'px'
      scaleRate.value = windowWidthWhenDesign / window.innerWidth
    }
  }

  compute()

  if (needReactivity) {
    window.addEventListener('resize', compute)
    onBeforeUnmount(() => {
      window.removeEventListener('resize', compute)
    })
  }

  return {
    windowSizeInCssForRef,
    windowSizeWhenDesignForRef,
    scaleRate,
  }
}