<template>
  <a-row
    type="flex"
    :gutter="row.gutter || 0"
    :align="row.align || 'top'"
    :justify="row.justify || 'start'"
  >
    <a-col
      v-for="col in getColumns"
      :key="`page-col-${col.id}`"
      :span="col.span || 24"
      :xs="col.xs"
      :sm="col.sm"
      :md="col.md"
      :lg="col.lg"
      :xl="col.xl"
      :xxl="col.xxl"
    >
      <!-- 行类型，递归渲染子行 -->
      <template v-if="col.type === 'row'">
        <x-page-row-template :template="col.template">
          <render-row
            v-for="(nestedRow, index) in col.children"
            :row="nestedRow"
            :key="`nested-row-${col.id}-${index}`"
          />
        </x-page-row-template>
      </template>

      <!-- 组件类型，渲染动态组件 -->
      <template v-else>
        <x-page-row-template :template="col.template">
          <component
            :ref="(el) => registerComponentRef(col.id, el)"
            :is="resolveComponentType(col.type)"
            v-bind="col.props"
          >
            <!-- 如果组件有子组件，递归渲染子行 -->
            <template v-if="col.children && col.children.length">
              <!-- 处理纯文本节点 -->
              <template v-for="(nestedItem, index) in col.children">
                <template v-if="nestedItem.text">{{ nestedItem.text }}</template>
                <render-row
                  v-else
                  :row="nestedItem"
                  :key="`comp-child-${col.id}-${index}`"
                />
              </template>
            </template>
          </component>
        </x-page-row-template>
      </template>
    </a-col>
  </a-row>
</template>

<script setup>
import { defineProps, inject, computed } from 'vue'
import XPageRowTemplate from './XPageRowTemplate.vue'

import { resolveComponentType } from './componentTypes'

// 注入注册组件方法
const registerComponent = inject('registerComponent')

// 定义属性
const props = defineProps({
  row: {
    type: Object,
    required: true
  }
})

// 获取列数组
const getColumns = computed(() => {
  return props.row.type === 'row' ? props.row.children : [props.row]
})

// 注册组件引用
const registerComponentRef = (id, el) => {
  if (el) {
    registerComponent(id, el)
  }
}
</script>

<style scoped lang="less">
</style>
