<script lang="ts" setup>
import { isDark } from '@/utils/is'
import { useAppStore } from '@/store/modules/app'
import { useDesign } from '@/hooks/web/useDesign'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import routerSearch from '@/components/RouterSearch/index.vue'

defineOptions({ name: 'APP' })

const { getPrefixCls } = useDesign()
const prefixCls = getPrefixCls('app')
const appStore = useAppStore()
const currentSize = computed(() => appStore.getCurrentSize)
const greyMode = computed(() => appStore.getGreyMode)
const { wsCache } = useCache()

// 根据浏览器当前主题设置系统主题色
const setDefaultTheme = () => {
  let isDarkTheme = wsCache.get(CACHE_KEY.IS_DARK)
  if (isDarkTheme === null) {
    isDarkTheme = isDark()
  }
  appStore.setIsDark(isDarkTheme)
}
setDefaultTheme()

const popperContainer = ref<Element | null>()

// 使用 ResizeObserver 监测尺寸变化
const resizeObserver = new ResizeObserver((entries) => {
  entries.forEach((entry) => {
    const popper = entry.target as HTMLElement

    if (popper.offsetWidth > 0 && popper.offsetHeight > 0) {
      const originalWidth = popper.offsetWidth
      // 把节点的高度改为节点的宽度
      popper.style.setProperty('height', `${originalWidth}px`, 'important')

      // 停止观察（如果需要持续监测可保留）
      resizeObserver.unobserve(popper)
    }
  })
})

onMounted(() => {
  // body下el-popper-container里面的样式修改。这里功能不完善
  if (appStore.getMobile) {
    popperContainer.value = document.querySelector('[id^="el-popper-container"]')
  } 
})

watch(
  () => popperContainer.value,
  (value) => {
    if (value) {
      const poppers = value.querySelectorAll('.el-popper')
      poppers.forEach((popper: HTMLElement) => {
        resizeObserver.observe(popper)
      })
    }
  }
)
</script>
<template>
  <ConfigGlobal :size="currentSize">
    <div class="h-100% w-100%" :class="greyMode ? `${prefixCls}-grey-mode` : ''">
      <RouterView />
    </div>
    <routerSearch />
  </ConfigGlobal>
</template>
<style lang="scss">
$prefix-cls: #{$namespace}-app;

.size {
  width: 100%;
  height: 100%;
}

html,
body {
  @extend .size;

  padding: 0 !important;
  margin: 0;
  overflow: hidden;

  #app {
    @extend .size;
  }
}

.#{$prefix-cls}-grey-mode {
  filter: grayscale(100%);
}
</style>
