<template>
  <template v-for="config in configList">
    <template v-if="config.type === 'separator'">
      <el-divider v-bind="config.bind">{{ config.title }}</el-divider>
    </template>
    <template v-else-if="config.type === 'alert'">
      <el-alert :title="config.title" v-bind="config.bind" />
    </template>
    <template v-else-if="config.type === 'card'">
      <ele-card shadow="always" :header="config.title" v-bind="config.bind">
        <config-form-list
          :config-list="config.children"
          v-if="config.children && config.children.length > 0"
        />
      </ele-card>
    </template>
    <template v-else-if="config.type === 'collapse'">
      <el-collapse v-bind="config.bind">
        <el-collapse-item :title="config.title">
          <config-form-list
            :config-list="config.children"
            v-if="config.children && config.children.length > 0"
          />
        </el-collapse-item>
      </el-collapse>
    </template>
    <template v-else-if="config.type === 'tabs'">
      <el-tabs type="card" v-model="config.value">
        <el-tab-pane
          v-for="tabPane in config.children"
          :label="tabPane.title"
          :name="tabPane.id"
          :key="tabPane.id"
        >
          <config-form-list
            :config-list="tabPane.children"
            v-if="tabPane.children && tabPane.children.length > 0"
          />
        </el-tab-pane>
      </el-tabs>
    </template>
    <template v-else>
      <config-form-item
        :name="config.name"
        :title="config.title"
        :type="config.type"
        :value="config.value"
        :option="config.option"
        :item-bind="config.bind"
        :key="config.id"
        :ref="setItemRef"
      />
      <el-form-item v-if="config.tips">
        <ele-text type="placeholder" style="line-height: 1.6">
          {{ config.tips }}
        </ele-text>
      </el-form-item>
    </template>
  </template>
</template>

<script setup lang="ts">
  import ConfigFormItem from '../components/config-form-item.vue';
  import {onBeforeUpdate, ref} from "vue";
  import type { ComponentPublicInstance } from "vue";


  // 定义组件引用类型
  interface ConfigFormItemInstance {
    getDataValue: () => any; // 根据实际返回类型调整
  }

  // 存储所有组件引用的数组
  const itemRefs = ref<ConfigFormItemInstance[]>([]);

  // 收集组件引用的函数
  const setItemRef = (el: unknown) => {
    const component = el as ComponentPublicInstance & ConfigFormItemInstance;
    if (component && component.getDataValue) {
      itemRefs.value.push(component);
    }
  };
  // 获取所有组件数据的函数
  const getAllDataValues = () => {
    let data = {}
    itemRefs.value.map((item)=>{
      const [name, value] = item.getDataValue();
      data[name] = value;
    });
    return data;
  };
  // 每次更新前清空引用数组
  onBeforeUpdate(() => {
    itemRefs.value = [];
  });

  const props = defineProps<{
    configList: any;
  }>();

  defineExpose({
    getFormData(){
      return getAllDataValues();
    }
  })
</script>
