<script setup lang="ts">
import { DESIGN_HEIGHT, DESIGN_WIDTH } from '@/utils/kb'
import rysummary from './rykb/rysummary.vue'
import safeday from './rykb/safeday.vue'
import rydeviceStatus from './rykb/rydeviceStatus.vue'
import ryorderTrend from './rykb/ryorderTrend.vue'
import zjfinish from './rykb/zjfinish.vue'
import zjwork from './rykb/zjwork.vue'
import xjwork from './rykb/xjwork.vue'
import rydeviceList from './rykb/rydeviceList.vue'

defineOptions({
  name: 'IotRyStatt'
})

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">
          <rysummary class="kb-stage-card kb-stage-card--1" />
          <div class="w-full h-148 grid grid-rows-2 grid-cols-3 gap-3 mt-3">
            <rydeviceStatus class="kb-stage-card kb-stage-card--2" />
            <safeday class="kb-stage-card kb-stage-card--3" />
            <ryorderTrend class="kb-stage-card kb-stage-card--4" />
            <zjfinish class="kb-stage-card kb-stage-card--5" />
            <zjwork class="kb-stage-card kb-stage-card--6" />
            <xjwork class="kb-stage-card kb-stage-card--7" />
          </div>
          <rydeviceList class="kb-stage-card kb-stage-card--8 kb-stage-card--list" />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
@import url('@/styles/kb.scss');
</style>
