<template>
  <Form
    :model="formModel"
    :colon="false"
    :label-col="{ span: 8 }"
    ref="formRef"
    layout="horizontal"
    size="small"
  >
    <template v-for="item in formItems" :key="item.prop">
      <!-- 联动 -->
      <template v-if="item.type === 'dependency'">
        
      </template>
      <!-- 分组 -->
      <Collapse v-if="item.type === 'group'">
        <CollapsePanel :key="item.prop" :header="item.label">
          <CusFormItem v-for="child in item.children" :key="child.prop" :item="child" v-model="formModel[child.prop]" />
        </CollapsePanel>
      </Collapse>
      <!-- 单个表单项 -->
      <CusFormItem v-else :item="item" v-model="formModel[item.prop]" />
    </template>
  </Form>
</template>

<script setup lang="tsx">
import type { IFormItem } from "./type";
import type { FormInstance } from "ant-design-vue";
import {
  ref,
  defineProps,
  defineExpose,
  computed,
  watch,
  defineEmits,
} from "vue";
import {
  Form,
  Collapse,
  CollapsePanel
} from "ant-design-vue";
import CusFormItem from "./CusFormItem.vue";

const props = defineProps<{
  columns: IFormItem[];
  formModel?: Record<string, any>;
}>();

const emit = defineEmits(["change"]);

const formModel = ref<Record<string, any>>({});
const formRef = ref<FormInstance>();

const formItems = computed(() => {
  return props.columns.map((item) => {
    return {
      ...item,
      rules: item.rules || [],
    };
  });
});

watch(
  () => formItems.value,
  (val) => {
    val &&
      props.columns?.forEach((item) => {
        // 设置表单初始值
        if (item.type === "group") {
          const children = item.children || [];
          (children as IFormItem[]).forEach((child) => {
            if(item.type === 'divider') return;
            formModel.value[child.prop] = child?.defaultValue;
          });
        } else {
          if(item.type === 'divider') return;
          formModel.value[item.prop] = item?.defaultValue;
        }
      });
  },
  { immediate: true }
);

watch(
  () => formModel.value,
  (val) => {
    emit("change", val);
  },
  { deep: true }
);

defineExpose(formRef.value);
</script>

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