<template>
  <el-row :gutter="15" type="flex" style="flex-wrap: wrap;">
    <template v-for="(item, index) in list">
      <el-col v-if="item.group && item.list" :key="index" :span="item.group.span || 24">
        <el-row :gutter="15" type="flex" style="flex-wrap: wrap;">
          <el-col v-if="item.group.title" :span="24">{{ item.group.title || item.group }}</el-col>
          <form-render :list="item.list" :model="itemKey ? model[itemKey] || {} : model" @item-change="onItemChange" @form-item-change="onFormItemChange" :itemKey="item.group.key"></form-render>
        </el-row>
      </el-col>
      <el-col v-else :span="item.span || 12" :key="index">
        <el-form-item :label="item.label" :label-width="item.labelWidth || '120px'" :prop="item.fullKey" :rules="item.rules">
          <component :is="item.type" :value="itemValue({ item })" @input="v => handleInput({ value: v, item })"></component>
        </el-form-item>
      </el-col>
    </template>
  </el-row>
</template>

<script>
export default {
  name: 'form-render',
  props: {
    list: Array,
    model: Object,
    itemKey: String,
  },
  methods: {
    itemValue({ item }) {
      if (this.itemKey) {
        const groupItem = this.model[this.itemKey] || {};
        return groupItem[item.key];
      } else {
        return this.model[item.key];
      }
    },
    handleInput({ value, item }) {
      if (this.itemKey) {
        this.$emit('item-change', { [this.itemKey]: { ...this.model[this.itemKey], [item.key]: value } });
      } else {
        this.$emit('item-change', { [item.key]: value });
      }
      this.$emit('form-item-change', { [item.fullKey]: value });
    },
    onItemChange(value) {
      if (this.itemKey) {
        this.$emit('item-change', { [this.itemKey]: { ...this.model[this.itemKey], ...value } });
      } else {
        this.$emit('item-change', value);
      }
    },
    onFormItemChange(value) {
      this.$emit('form-item-change', value);
    }
  }
}
</script>