<script lang="ts" setup>
import { DESIGN_HEIGHT, DESIGN_WIDTH } from '@/utils/kb'
import hsummary from './kb/hsummary.vue'
import hmttr from './kb/hmttr.vue'
import hdeviceType from './kb/hdeviceType.vue'
import dayfinish from './kb/dayfinish.vue'
import hsafe from './kb/hsafe.vue'
import hdeviceStatus from './kb/hdeviceStatus.vue'
import horderTrend from './kb/horderTrend.vue'

const company = ref('首页')

const wrapperRef = ref<HTMLDivElement>()
const scale = ref(1)

let resizeObserver: ResizeObserver | null = null
let resizeRaf = 0

const targetWrapperStyle = computed(() => ({
  width: `${DESIGN_WIDTH * scale.value}px`,
  height: `${DESIGN_HEIGHT * scale.value}px`
}))

const targetAreaStyle = computed(() => ({
  width: `${DESIGN_WIDTH}px`,
  height: `${DESIGN_HEIGHT}px`,
  transform: `scale(${scale.value})`,
  transformOrigin: '0 0'
}))

function updateScale() {
  cancelAnimationFrame(resizeRaf)

  resizeRaf = requestAnimationFrame(() => {
    const wrapper = wrapperRef.value
    if (!wrapper) return

    const { clientWidth, clientHeight } = wrapper
    if (!clientWidth || !clientHeight) return

    scale.value = Math.min(clientWidth / DESIGN_WIDTH, clientHeight / DESIGN_HEIGHT)
  })
}

onMounted(() => {
  nextTick(updateScale)
  resizeObserver = new ResizeObserver(updateScale)
  if (wrapperRef.value) {
    resizeObserver.observe(wrapperRef.value)
  }

  window.addEventListener('resize', updateScale)
})

onUnmounted(() => {
  resizeObserver?.disconnect()
  window.removeEventListener('resize', updateScale)
  cancelAnimationFrame(resizeRaf)
})
</script>
<template>
  <div ref="wrapperRef" class="bg absolute top-0 left-0 size-full z-10">
    <div class="mx-a overflow-hidden" :style="targetWrapperStyle">
      <div class="bg" :style="targetAreaStyle">
        <header class="header">{{ company }}</header>
        <div class="mt-3 px-5">
          <hsummary class="kb-stage-card kb-stage-card--1" />
          <div class="w-full h-96 grid grid-rows-2 grid-cols-3 gap-3 mt-3">
            <hmttr class="kb-stage-card kb-stage-card--2" />

            <hdeviceType class="row-span-2 kb-stage-card kb-stage-card--4" />
            <dayfinish class="row-span-2 kb-stage-card kb-stage-card--5" />
            <hsafe class="kb-stage-card kb-stage-card--3" />
          </div>
          <div class="w-full h-107 grid grid-cols-2 gap-3 mt-3">
            <hdeviceStatus class="kb-stage-card kb-stage-card--6" />
            <horderTrend class="kb-stage-card kb-stage-card--7" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
@import url('@/styles/kb.scss');
</style>
