<template>
  <div class="bg-tags">
    <ul>
      <li v-for="(tag, index) in tags" :key="'tag_' + index" class="tag-item">
        <span>
          {{ tag }}
        </span>
        <a @click="deleteTag(index)" v-if="!disabled">
          <i class="el-icon-close"></i>
        </a>
      </li>
      <li v-if="!disabled">
        <el-button type="primary2" size="mini" @click="showInput = true" v-if="!showInput"> 新增 </el-button>
        <el-input v-model.trim="newTag" @blur="addTag" v-else />
      </li>
    </ul>
  </div>
</template>

<script setup>
import { reactive, ref, onBeforeMount, toRefs, computed, useSlots } from "vue";
const props = defineProps({
  modelValue: {
    type: String,
    default: "",
  },
  disabled: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["update:modelValue"]);

const newTag = ref("");
const showInput = ref(false);

const tags = computed(() => {
  return (props.modelValue && props.modelValue.split(",")) || [];
});

const deleteTag = (index) => {
  let tags = [...tags.value];

  tags.splice(index, 1);

  emit("update:modelValue", tags.join(","));
};
const addTag = () => {
  let tags = [...tags.value];

  if (newTag.value) {
    tags.push(newTag.value);
  }

  emit("update:modelValue", tags.join(","));
  newTag.value = "";
  showInput.value = false;
};
</script>
