<template>
  <div>
    <el-tag
      :key="tag"
      v-for="tag in dynamicTags"
      size="medium"
      closable
      :disable-transitions="false"
      @close="handleClose(tag)"
    >
      {{ tag }}
    </el-tag>
    <el-input
      class="input-new-tag"
      v-if="inputVisible"
      v-model="inputValue"
      ref="saveTagInput"
      size="small"
      @keyup.enter.native="handleInputConfirm"
      @blur="handleInputConfirm"
    >
    </el-input>
    <el-button
      v-else
      class="button-new-tag"
      size="mini"
      @click="showInput"
      icon="i-x-ktbj-tianjia"
    >
      增加关键词</el-button
    >
  </div>
</template>

<script>
export default {
  data () {
    return {
      dynamicTags: [],
      inputVisible: false,
      inputValue: ''
    }
  },
  props: {
    value: {
      require: false,
      default: []
    }
  },
  watch: {
    value: {
      immediate: true,
      deep: true,
      handler (nv) {
        this.dynamicTags = nv
      }
    },
    dynamicTags: {
      immediate: false,
      deep: true,
      handler (nv) {
        this.$emit('input', nv)
      }
    }
  },
  methods: {
    /*
    标签关闭按钮被点击
     */
    handleClose (tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
    },
    /*
      显示输入框新增标签
    */
    showInput () {
      this.inputVisible = true
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    /*
      输入框失去焦点或者回车键被按下后,调用
    */
    handleInputConfirm () {
      const inputValue = this.inputValue
      if (inputValue) {
        this.dynamicTags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    }
  }
}
</script>

<style lang="scss" scoped>
.el-tag {
  margin-right: 10px;
}
.input-new-tag {
  width: 100px;
  height: 28px;
  line-height: 28px;
  margin-left: 10px;
  vertical-align: bottom;
  ::v-deep .el-input__inner {
    height: 28px;
    line-height: 28px;
  }
}
</style>
