<script setup lang="ts" name="SelTable">

const emit = defineEmits(['check', 'input'])

const props = defineProps({
  value: {
    type: Array,
    default: () => []
  },
  addTagOnKeys: {
    type: Array,
    default: () => []
  },
  readOnly: {
    type: Boolean,
    default: false
  },
})

const tagInputRef: any = ref(null)
const newTag = ref('')
const innerTags = ref([...props.value])

watch(
  () => props.value,
  () => {
    innerTags.value = [...props.value]
  }
)

function focusTagInput() {
  if (props.readOnly || !tagInputRef.value) {
    return
  } else {
    tagInputRef.value.focus()
  }
}

function inputTag(ev: any) {
  newTag.value = ev.target.value
}
function remove(index: number) {
  innerTags.value.splice(index, 1)
  tagChange()
}
function addNew(e: any) {
  if (e && (!props.addTagOnKeys.includes(e.keyCode)) && (e.type !== 'blur')) {
    return
  }
  if (e) {
    e.stopPropagation()
    e.preventDefault()
  }
  let addSuccess = false
  if (newTag.value.includes(',')) {
    newTag.value.split(',').forEach(item => {
      if (addTag(item.trim())) {
        addSuccess = true
      }
    })
  } else {
    if (addTag(newTag.value.trim())) {
      addSuccess = true
    }
  }
  if (addSuccess) {
    tagChange()
    newTag.value = ''
  }
}
function addTag(tag: any) {
  tag = tag.trim()
  if (tag && !innerTags.value.includes(tag)) {
    innerTags.value.push(tag)
    return true
  }
  return false
}

function removeLastTag() {
  if (newTag.value) {
    return
  }
  innerTags.value.pop()
  tagChange()
}
function tagChange() {
  emit('input', innerTags.value)
}


</script>
<template>
  <div class="el-input el-input--suffix el-tooltip__trigger" @click="focusTagInput">
    <div class="el-input__wrapper">
      <el-space>
        <template v-for="(tag, idx) in innerTags" :key="tag">
          <el-tag v-bind="$attrs" type="info" size="small" round :closable="!readOnly" :disable-transitions="false"
            @close="remove(idx)">
            {{ tag }}
          </el-tag>
        </template>
        <input v-if="!readOnly" ref="tagInputRef" class="el-input__inner" @input="inputTag" :value="newTag"
          @keydown.delete.stop="removeLastTag" @keydown="addNew" @blur="addNew" />
      </el-space>
    </div>
  </div>
</template>

<style scoped lang="scss">
.el-input__wrapper {
  justify-content: flex-start;
}
</style>
