<template>
  <div class="fast-addition" :class="[disabled?'el-fast-addition--disabled':'']">
    <div class="fast-addition-content">
      <el-tag
        v-for="(tag, index) in data"
        :key="index"
        :closable="!disabled"
        :class="[disabled?'el-tag--disabled':'']"
        @close="onClose(index)">
        <span class="fast-addition-label">{{tag[prop]}}</span>
      </el-tag>
      <el-input
        v-if="!hidden"
        v-model.trim="inputValue"
        placeholder="输入后按回车确认"
        :maxlength="maxLength"
        @keyup.enter.native="onAdd">
      </el-input>
    </div>
    <span class="fast-addition-limit">{{data.length}}/{{limit}}</span>
  </div>
</template>

<script>

export default {
  name: 'ElFastAddition',
  props: {
    value: { // 传入的绑定数组
      type: Array,
      default: () => []
    },
    disabled: { // 是否禁止添加
      type: Boolean,
      default: false
    },
    repeatable: { // 是否可重复
      type: Boolean,
      default: false
    },
    maxLength: { // 输入的文本最大长度
      type: Number,
      default: 255
    },
    prop: { // 展示的对象属性值
      type: String,
      default: 'name'
    },
    limit: { // 可输入个数
      type: Number,
      default: 5
    }
  },
  data() {
    return {
      inputValue: '',
      data: this.value,
      hidden: this.disabled // 控制input的显示与隐藏
    }
  },
  mounted() {
    // 传入的数据个数大于等于限制数时，隐藏input
    if (this.data.length >= this.limit) {
      this.hidden = true
    }
  },
  methods: {
    onClose(index) {
      this.data.splice(index, 1)
      this.$emit('delete', this.data)
      // 删除标签并且标签数小于限制数时（可兼容老数据长度大于限制数），input显示
      if (this.hidden && this.data.length < this.limit) {
        this.hidden = false
      }
    },
    onAdd() {
      if (this.data.length > 0) {
        if (this.inputValue) {
          let repeats = this.data.filter((item) => {
            return this.inputValue === item[this.prop]
          })
          if (repeats.length > 0 && this.repeatable === false) {
            this.$message.warning('不允许添加重复内容')
          } else {
            let newData = JSON.parse(JSON.stringify(this.data[0]))
            for (let item in newData) {
              newData[item] = ''
            }
            newData[this.prop] = this.inputValue
            this.data.push(newData) && (this.inputValue = '')
            this.data.length < this.limit ? this.hidden = false : this.hidden = true
          }
        } else {
          return
        }
      } else { // 当数组中的数据全被清除时，定义一个Ucn对象
        if (this.inputValue) {
          let newData = { id: '', code: '', name: '' }
          newData[this.prop] = this.inputValue
          this.data.push(newData) && (this.inputValue = '')
          console.log(this.data)
        }
      }
      this.$emit('add', this.data)
    }
  }
}
</script>