<template>
  <div class="ya-box">
    <el-tag
      v-for="(tag, i) in tagArr"
      :key="tag"
      class="mx-1"
      :closable="canAdd"
      @close="handleClose(i)"
      size="small"
      :style="{cursor:canAdd?'pointer':'not-allowed'}"
    >
      <span
        :contenteditable="canAdd"
        @keydown="handleForbiteLine"
        ref="tags"
        >{{ tag }}</span
      >
    </el-tag>
    <el-input
      v-if="inputVisible"
      ref="InputRef"
      v-model.trim="inputValue"
      class="ml-1 w-20"
      size="small"
      @keyup.enter="handleInputConfirm"
      @blur="handleInputConfirm"
      maxlength="10"
    />
    <template v-else>
      <ya-button v-if="canAdd"  size="small" @click="showInput"> + </ya-button>
    </template>
  </div>
</template>

<script lang="ts" setup>
import {
  ref,
  defineProps,
  watch,
  defineEmits,
  onUnmounted,
  nextTick,
  onMounted,
  unref,
  watchEffect,
} from "vue";
import { ElTag, ElInput } from "element-plus";
interface PropType {
  tag: Array<string>;
    canAdd:Boolean
}
const emit = defineEmits(["tabChange"]);
const tags = ref();
const tagArr = ref([]); // 标签值
const { tag = [],canAdd=true } = defineProps<PropType>();
const inputValue = ref("");
const inputVisible = ref(false);
const InputRef = ref<InstanceType<typeof ElInput>>();
//删除按钮的事件
const handleClose = (index: number) => {
  tagArr.value.splice(index, 1);
  emit("tabChange", tagArr.value);
};
//添加按钮的点击事件
const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value!.input!.focus();
  });
};
//enter键禁止换行
const handleForbiteLine = (e) => {
  if (e.code === "Enter"||e.target.innerText.length>10) {
    e.preventDefault();
  }
};
//添加的input框失去焦点
const handleInputConfirm = () => {
  if (inputValue.value) {
    tagArr.value?.push(inputValue.value);
    emit("tabChange", tagArr.value);
   nextTick(()=>{
    addEventListener(tags.value[tags.value.length - 1], tags.value.length - 1);
   })
  }
  inputVisible.value = false;
  inputValue.value = "";
};
//增加事件监听
const addEventListener = (data, i) => {
  data.addEventListener("blur", function (event) {
    const content = event.target.textContent;
    tagArr.value[i] = content;
    if(!content){
      tagArr.value.splice(i,1)
    }
    emit("tabChange", tagArr.value);
  });
};
watch(
  () => tag,
  (val) => {
    if(unref(tag).length == 0) {
      tagArr.value = []
    }
    if (tagArr.value.length) return 
    tagArr.value = val;
    nextTick(() => {
      tags.value?.forEach((item, i) => {
        addEventListener(item, i);
      });
    });
  },
  {
    deep: true,
    immediate: true
  }
);

onUnmounted(() => {
  tags.value?.forEach((item) => {
    item.removeEventListener("blur", function () {});
  });
});

</script>
<style lang="scss" scoped>
.ya-box {
  .el-tag {
    margin-right: 12px;
    vertical-align: middle;
  }
  .el-tag__content {
    span {
      outline: none;
    }
  }
}
</style>
