<template>
  <div>
    <van-radio-group direction="vertical">
      <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>
        <van-radio checked-color="#f63634" :name="v.attr.name">{{
          v.attr.label
        }}</van-radio>
      </div>
    </van-radio-group>
    <div style="padding-top: 1em">
      <el-button v-if="!showEle" type="primary" @click="() => editEle()">
        <el-icon color="#fff" :size="15"><Plus /></el-icon>
        新增选项
      </el-button>
      <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';
const props = defineProps({
  item: Object,
  index: String,
});

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

const showEle = ref(false);
console.log(localItem);

const emit = defineEmits(['change']);
const form = ref({
  name: '',
});

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

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;
    localItem.value.child_list[form.value.index].attr.label = 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: 0;
  right: 3px;
}
</style>
