<template>
  <a-form-model
    ref="formRef"
    class="process-form"
    :label-col="{ span: 24 }"
    :wrapper-col="{ span: 24 }"
    :model="innerDataValue"
    :rules="rules"
    layout="vertical"
  >
    <template v-for="(item, index) in forms">
      <!-- 普通表单项 -->
      <a-form-model-item
        v-if="item.name !== 'SpanLayout' && item.name !== 'Description'"
        :key="item.id"
        :label="item.title"
        :prop="item.id"
      >
        <!-- 显式绑定 value + input，避免 v-model 对象属性响应式失效 -->
        <FormDesignRender
          :value="innerDataValue[item.id]"
          :mode="'PC'"
          :config="item"
          @input="val => updateValue(item.id, val)"
        />
      </a-form-model-item>

      <!-- 特殊表单项（布局/描述类） -->
      <template v-else>
        <FormDesignRender
          :value="innerDataValue"
          :mode="'PC'"
          :config="item"
          @input="val => updateValue(null, val)"
        />
      </template>
    </template>
  </a-form-model>
</template>

<script>
import FormDesignRender from './FormDesignRender.vue';

export default {
  name: 'FormRender',
  components: {
    FormDesignRender
  },
  props: {
    forms: {
      type: Array,
      required: true
    },
    value: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      rules: {},
      fieldErrors: {}, // 用于存储每个字段的错误信息
      innerDataValue: { ...this.value }
    };
  },
  watch: {
    // 父组件传值时更新内部数据
    value: {
      handler(val) {
        this.innerDataValue = { ...val };
      },
      deep: true
    },
    // 表单配置变化时生成校验规则
    forms: {
      handler(val) {
        this.rules = {};
        this.generateRules(val);
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    // 确保响应式更新 innerDataValue
    updateValue(id, val) {
      if (id) {
        this.$set(this.innerDataValue, id, val);
      } else {
        // SpanLayout / Description 类情况
        this.innerDataValue = { ...this.innerDataValue, ...val };
      }
      // 往父组件冒泡，保持 v-model 同步
      this.$emit('input', this.innerDataValue);
    },
    generateRules(items) {
      items.forEach(item => {
        if (
          item.name !== 'SpanLayout' &&
          item.name !== 'Description' &&
          item.props &&
          item.props.required
        ) {
          let rule = { required: true, message: `请输入${item.title}`, transform: value => (value === '' || value === null ? undefined : value) }

          // NumberInput/数字类：同时保证是 number
          if (item.name === 'NumberInput' || item.props.type === 'number' || item.type === 'Number') {
            rule = {
              required: true,
              type: 'number',
              message: `请输入${item.title}`,
              // 强制转 number；''/null 视为未填
              transform: v => (v === '' || v === null ? undefined : Number(v))
            };
          }

          this.$set(this.rules, item.id, [rule])
        }
        if (item.name === 'SpanLayout' && item.props && item.props.items) {
          this.generateRules(item.props.items);
        }
      });
    },
    async validate(callback) {
      // 清理该表单涉及到的字段的旧错误
      const props = Object.keys(this.rules || {});
      if (props.length) {
        this.$refs.formRef.clearValidate(props);
      }

      // 等待视图与 FormItem 同步
      await this.$nextTick();

      this.$refs.formRef.validate((valid, errors) => {
        callback && callback(valid, errors)
      })
    },
    reset() {
      this.$refs.formRef.resetFields();
    }
  }
};
</script>

<style scoped lang="less">
/* 可按需自定义样式 */
</style>
