<template>
  <div class="tags-input-wrapper">
    <div class="tags-box">
      <el-tag v-for="tag in tags" :key="tag" color="#F5F5F5" :closable="!disabled" @close="handleClose(tag)">
        <span style="color: blue">{{ tag }}</span>
      </el-tag>
      <el-popconfirm title="确定清空吗？" @confirm="handleClear" :hide-after="10" placement="top">
        <template #reference>
          <el-button size="small" :disabled="tags.length === 0">{{ tags.length }}/{{ maxLength }}</el-button>
        </template>
      </el-popconfirm>
    </div>
    <el-input
      type="textarea"
      v-model="text"
      @blur="onBlur"
      :disabled="tags.length >= maxLength"
      :placeholder="placeholder"
      :autosize="{ minRows: 3, maxRows: 10 }"></el-input>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'
import XEUtils from 'xe-utils'

interface Props {
  data: string[]
  placeholder: string
  maxLength: number,
  disabled?: boolean
}
const props = withDefaults(defineProps<Props>(), {
  placeholder: '请输入',
  maxLength: 100,
})
const tags = ref(props.data)
const emits = defineEmits(['update:modelValue'])
const text = ref('')
const tagsMap = computed(() => {
  const map = {}
  for (const tag of tags.value) {
    map[tag] = true
  }
  return map
})

const onBlur = () => {
  const newTags = XEUtils.uniq(text.value.split(/[\r\n]/))
  for (const tag of newTags) {
    if (tag !== '' && !tagsMap.value[tag] && tags.value.length < props.maxLength) {
      tags.value.push(tag)
    }
  }
  text.value = ''
}
const handleClose = (tag: string) => {
  tags.value.splice(tags.value.indexOf(tag), 1)
}
const handleClear = () => {
  tags.value.splice(0, tags.value.length)
}
</script>

<style lang="scss" scoped>
.tags-box {
  width: 100%;
  display: flex;
  overflow: auto;
  flex-wrap: wrap;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  gap: 5px;
  background: #fff;
  padding: 3px;
  margin-bottom: 1px;
}
</style>
