<script lang="ts" setup>
import { DESIGN_HEIGHT, DESIGN_WIDTH } from '@/utils/kb'

import rhsummary from './rhkb/rhsummary.vue'
import deviceType from './rhkb/deviceType.vue'
import deviceStatus from './rhkb/deviceStatus.vue'
import operation from './rhkb/operation.vue'
import orderTrend from './rhkb/orderTrend.vue'
import todayGas from './rhkb/todayGas.vue'
import historyGas from './rhkb/historyGas.vue'
import deviceList from './rhkb/deviceList.vue'

defineOptions({
  name: 'IotRhStatt'
})

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" id="rhkb" :style="targetAreaStyle">
        <header class="header">{{ company }}</header>
        <div class="mt-3 px-5">
          <rhsummary 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">
            <deviceStatus class="kb-stage-card kb-stage-card--2" />
            <deviceType class="kb-stage-card kb-stage-card--3" />
            <operation class="kb-stage-card kb-stage-card--4" />
            <orderTrend class="kb-stage-card kb-stage-card--5" />
            <todayGas class="kb-stage-card kb-stage-card--6" />
            <historyGas class="kb-stage-card kb-stage-card--7" />
          </div>
          <deviceList class="kb-stage-card kb-stage-card--8 kb-stage-card--list" />
        </div>
      </div>
    </div>
  </div>
</template>

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