<template>
  <left-skeleton @save="save" @deleteFunc="deleteFunc">
    <el-form :model="form" label-width="55px">
      <el-form-item label="名称">
        <el-input v-model="form.label" />
      </el-form-item>
      <el-form-item v-if="defaultForm" label="提示">
        <el-input v-model="form.placeholder" />
      </el-form-item>
      <el-form-item label="必填">
        <el-switch v-model="form.isRequired" />
      </el-form-item>
      <el-form-item label="key">
        <el-input v-model="form.key" />
      </el-form-item>
      <el-form-item v-if="!defaultForm" label="子属性">
        <component
          v-for="(item, index) in form.child_list"
          :key="index"
          :is="H5EditorObj[item.type]"
          :item="item"
          :index="index + ''"
          @change="seacechange"
        ></component>
      </el-form-item>
    </el-form>
  </left-skeleton>
</template>

<script setup>
import { defineProps, inject, ref } from 'vue';
import leftSkeleton from '../H5Editor/leftSkeleton.vue';

import vanRadioGroup from './van_radio_group';
import vanUploader from './van_uploader';

const H5EditorObj = {
  'van-radio-group': vanRadioGroup,
  'van-uploader': vanUploader,
};

const saveComponents = inject('saveComponents');
const deleteItemComponents = inject('deleteItemComponents');

const props = defineProps({
  item: Object,
  index: String,
});
const item = JSON.parse(JSON.stringify(props.item.item));
const defaultForm = ref(false);

const formSele = {};
if (!item.child_list || !item.child_list.length) {
  defaultForm.value = true;
  formSele.label = item.attr.label;
  formSele.placeholder = item.attr.placeholder;
  formSele.isRequired = item.attr.isRequired;
  formSele.key = item.attr.key;
} else {
  defaultForm.value = false;
  formSele.child_list = item.child_list;
  formSele.label = item.attr.label;
  formSele.isRequired = item.attr.isRequired;
  formSele.key = item.attr.key;
}

const form = ref(formSele);

// 获取子组件内更新的数据
const seacechange = (item, index) => {
  form.value.child_list[index] = item;
};

const save = () => {
  if (defaultForm.value) {
    item.attr.label = form.value.label;
    item.attr.placeholder = form.value.placeholder;
    item.attr.isRequired = form.value.isRequired;
    item.attr.key = form.value.key;
  } else {
    item.child_list = form.value.child_list;
    item.attr.label = form.value.label;
    item.attr.isRequired = form.value.isRequired;
    item.attr.key = form.value.key;
  }
  saveComponents({ item, index: props.index });
};

const deleteFunc = () => {
  /**
   * 1.删除本地
   * 2.删除远程
   */
  deleteItemComponents(props.index);
};
</script>

<style scoped></style>
