<template>
  <el-form ref="form" size="small" :model="formModel">
    {{ formModel }}
    <form-render :list="formList" :model="model" @item-change="onItemChange" @form-item-change="onFormItemChange"></form-render>
  </el-form>
</template>

<script>
import FormRender from './form-render';

export default {
  components: { FormRender },
  props: {
    value: Object,
    list: Array,
  },
  data() {
    return {
      model: {},
      formModel: {}
    }
  },
  watch: {
    value(val) {
      const data = val || {};
      this.model = data;
      let formModel = {};
      const setFormModelValue = (list, parentKey) => {
        list.forEach(item => {
          item.fullKey = `${parentKey ? `${parentKey}-${item.key}` : item.key}`;
          if (item.value instanceof Object) {
            setFormModelValue(Object.keys(item.value).map(key => ({ key, value: item.value[key] })), item.fullKey);
          } else {
            if (item.fullKey) {
              formModel[item.fullKey] = item.value;
            }
          }
        });
      };
      setFormModelValue(Object.keys(data).map(key => ({ key, value: data[key] })));
      this.formModel = formModel;
    },
  },
  computed: {
    formList() {
      const newList = [...new Set(this.list)]
      const generateFullKey = (list, parentKey) => {
        list.forEach(item => {
          if (item.group && item.list) {
            if (item.group.key) {
              item.fullKey = `${parentKey ? `${parentKey}-${item.group.key}` : item.group.key}`;
            } else {
              item.fullKey = item.key;
            }
            generateFullKey(item.list, item.fullKey);
          } else {
            item.fullKey = `${parentKey ? `${parentKey}-${item.key}` : item.key}`;
          }
        });
      };
      generateFullKey(newList);
      return newList;
    }
  },
  methods: {
    // 表单项值变化
    onItemChange(item) {
      this.$emit('input', { ...this.model, ...item });
    },
    // 表单相校验值变化
    onFormItemChange(item) {
      this.formModel = { ...this.formModel, ...item };
    },
    // 校验表单
    validate() {
      this.$refs.form.validate(valid => {
        this.$emit("validate", valid);
      });
    },
  }
}
</script>

<style>

</style>