<template>
  <div>
    <van-radio-group v-model="select" :direction="localItem.attr.direction">
      <div
        v-for="(v, i) in localItem.child_list || []"
        @close="close"
        :key="i"
        class="leftTag"
      >
        <div class="closeCss">
          <el-icon @click="() => editEle(v, i)"><Edit /></el-icon>
          <el-icon @click="() => close(v, i)"><Close /></el-icon>
        </div>
        <h5-van-radio :item="v"></h5-van-radio>
      </div>
    </van-radio-group>
    <div style="padding-top: 1em">
      <el-icon
        v-if="!showEle"
        color="#409eff"
        :size="30"
        @click="() => editEle()"
        ><FolderAdd
      /></el-icon>

      <el-form class="formEle" :model="form" v-if="showEle">
        <el-form-item label="文案">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">保存</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script setup>
import { defineProps, ref, defineEmits } from 'vue';
import H5VanRadio from './van_radio.vue';
const props = defineProps({
  item: Object,
  index: String,
});

const localItem = ref(JSON.parse(JSON.stringify(props.item)));

const select = ref(
  localItem.value.child_list ? localItem.value.child_list[0].attr.name : ''
);

const showEle = ref(false);

const emit = defineEmits(['change']);
const form = ref({
  name: '',
});
console.log(localItem.value);

const editEle = (v, i) => {
  showEle.value = true;
  form.value.isEdit = !!v;
  if (v) {
    form.value.index = i;
    form.value.name = v.attr.label;
  }
};

const close = (v, i) => {
  const li = JSON.parse(JSON.stringify(localItem.value.child_list));
  li.splice(i, 1);
  localItem.value.child_list = li;
  emit('change', localItem.value, props.index);
};

const onSubmit = () => {
  if (!form.value.name) return;
  showEle.value = false;
  if (form.value.isEdit) {
    localItem.value.child_list[form.value.index].attr.name = form.value.name;
  } else {
    localItem.value.child_list.push({
      attr: {
        label: form.value.name,
        name: form.value.name,
      },
      type: 'van-radio',
    });
  }
  form.value.name = '';
  emit('change', localItem.value, props.index);
};

const cancel = () => {
  showEle.value = false;
};
</script>

<style scoped>
.leftTag {
  padding: 5px 35px 5px 5px;
  position: relative;
  margin-right: 4px;
  min-width: 4em;
}
.closeCss {
  position: absolute;
  top: 7px;
  right: 3px;
}
</style>
