<template>
  <div class="dashboard">
    <!-- 按行渲染 -->
    <div
      v-for="(rowItems, rowIndex) in groupedComponents"
      :key="rowIndex"
      class="dashboard-row"
    >
      <el-card
        v-for="item in rowItems"
        :key="item.id"
        class="dashboard-item"
        shadow="hover"
        :class="{ 'full-width': rowItems.length == 1 }"
      >
        <component :is="loadComponent(item.componentFilePath)" />
      </el-card>
    </div>

  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, defineAsyncComponent, computed } from "vue"
import { getInfo } from "@/api/login"

interface ComponentItem {
  id: number
  componentId: number
  componentName: string
  componentRow: string
  componentColumn: string
  componentFilePath: string
  componentThumbnail: string
}

defineOptions({ name: "Index" })

const componentDetail = ref<ComponentItem[]>([])

// 获取 views/Home 下的所有 vue 文件
const modules = import.meta.glob("/src/views/UiCom/**/*.vue")

// 动态加载组件
const loadComponent = (path: string) => {
  const filePath = `/src/views/UiCom${path}.vue`
  if (modules[filePath]) {
    return defineAsyncComponent(modules[filePath] as any)
  }

}

// 去重 + 分组 + 排序
const groupedComponents = computed(() => {
  // 去重：根据 componentId 或 componentFilePath
  const uniqueMap = new Map<string | number, ComponentItem>()
  componentDetail.value.forEach((item) => {
    if (!uniqueMap.has(item.componentId)) {
      uniqueMap.set(item.componentId, item)
    }
  })
  const uniqueList = Array.from(uniqueMap.values())

  // 按 row 分组
  const groups: Record<string, ComponentItem[]> = {}
  uniqueList.forEach((item) => {
    if (!groups[item.componentRow]) {
      groups[item.componentRow] = []
    }
    groups[item.componentRow].push(item)
  })

  // 每行内部按 column 排序
  Object.keys(groups).forEach((row) => {
    groups[row].sort((a, b) => Number(a.componentColumn) - Number(b.componentColumn))
  })

  // 最终按 row 排序
  return Object.keys(groups)
    .sort((a, b) => Number(a) - Number(b))
    .map((key) => groups[key])
})

// 获取数据
const getPageContent = async () => {
  try {
    const pageData = await getInfo()
    componentDetail.value = pageData.uiComponentList
    // console.log("驾驶舱数据:", componentDetail.value)
  } catch (error) {
    console.log(error)
  }
}

onMounted(() => {
  getPageContent()
})
</script>


<style lang="scss" scoped>
.dashboard {
  display: flex;
  flex-direction: column;
  gap: 15px;
  padding: 15px;
}

.dashboard-row {
  display: flex;
  gap: 15px;
}

.dashboard-item {
  flex: 1; /* 多个组件时自动平分 */
  border-radius: 12px;
  overflow: hidden;
}

.dashboard-item.full-width {
  flex: none;
  width: 100%; /* 单个组件时占满整行 */
}
</style>
