<template>
  <form-create
    v-model="formData"
    v-model:api="fapi"
    :rule="rule"
    :option="option"
    @submit="onSubmit"
  ></form-create>
</template>

<script setup>
import {ref, watch} from "vue";
// import formCreate from "@form-create/ant-design-vue";
// import { default as formCreate } from '@form-create/ant-design-vue'
//import * as formCreate from '@form-create/ant-design-vue'
import formCreate from '@form-create/ant-design-vue';

const option = ref([]);
const rule = ref([]);
const fapi = ref(null);
const formData = ref({});

// 监听表单数据变化
watch(formData, (newVal) => {
  updateDisabledFields(newVal);
}, { deep: true });

// 更新禁用状态的字段
function updateDisabledFields(formValues) {
  if (!rule.value || !fapi.value) return;
  
  rule.value.forEach((field, index) => {
    if (field.field && formValues[field.field] !== undefined && formValues[field.field] !== null && formValues[field.field] !== '') {
      // 如果字段有值，设置为禁用
      fapi.value.updateRule({
        field: field.field,
        props: {
          disabled: true
        }
      });
    } else {
      fapi.value.updateRule({
        field: field.field,
        props: {
          disabled: false
        }
      });
    }
  });
}

async function iniData(data) {
  try {
    if (!data) {
      rule.value = []
      option.value = []
      return;
    }
    
    const { formRules, formOptions } = data;
    if (!formRules || !formOptions) {
      console.error('表单数据格式不正确:', data);
      rule.value = []
      option.value = []
      return;
    }

    if(formRules) {
      rule.value = formCreate.parseJson(formRules);
    }
    if(formOptions) {
      option.value = formCreate.parseJson(formOptions);
    }

    console.log('表单初始化成功:', { rule: rule.value, option: option.value });
  } catch (error) {
    console.error('表单初始化失败:', error);
    console.error('原始数据:', data);
  }
}

const getFormData =() => {
  return formData.value
}

const setFormData =(data) => {
  Object.assign(formData.value, data)
  //updateDisabledFields(formData.value);
}

const resetForm =() => {
  Object.keys(formData.value).forEach(key => {
    formData.value[key] = '';
  });
}

defineExpose({
  iniData,
  getFormData,
  setFormData,
  resetForm
});
</script>