
<template>
  <div>
    <h3 class="attr-title">
      标签属性
    </h3>
    <template v-for="(tag, index) in tags">
      <a-tooltip v-if="tag.length > 20" :key="tag" :title="tag">
        <a-tag
          :key="tag"
          :closable="true"
          :afterClose="() => handleClose(tag)"
        >{{`${tag.slice(0, 20)}...`}}</a-tag>
      </a-tooltip>
      <a-tag v-else :key="tag" :closable="true" :afterClose="() => handleClose(tag)">{{tag}}</a-tag>
    </template>
    <a-input
      v-if="inputVisible"
      ref="input"
      type="text"
      size="small"
      :style="{width: '78px'}"
      style="margin-top: 10px;"
      :value="inputValue"
      @change="handleInputChange"
      @blur="handleInputConfirm"
      @keyup.enter="handleInputConfirm"
    />
    <a-tag v-else @click="showInput" style="background: #fff; borderStyle: dashed;">
      <a-icon type="plus" />新建标签
    </a-tag>
  </div>
</template>

<script>
import { getTagList, deleteTag, addTag } from '@/api/graph/tag'
export default {
  name: "tagEditor",
  data() {
    return {
      vertexId: null,
      tags: [],
      inputVisible: false,
      inputValue: ""
    };
  },
  props: [
    "entid", 
    "classid"
  ],
  created() {
    this.vertexId = this.entid;
    // this.vertexId = this.classid
    if (this.vertexId) {
      this.refreshTagList();
    }
  },
  methods: {
    /**
     * 刷新tag列表
     */
    refreshTagList() {
      getTagList(this.vertexId).then(data => {
        const tags = [];
        for (var i = 0; i < data.length; i++) {
          tags.push(data[i].tagName);
        }
        this.tags = tags;
      });
    },
    /**
     * 删除标签
     **/
    handleClose(removedTag) {
      deleteTag(this.vertexId, removedTag).then(data => {
        if (data) {
          const tags = this.tags.filter(tag => tag !== removedTag);
          this.tags = tags;
        }
      });
    },
    /**
     * 点击新建标签按钮
     * */
    showInput() {
      this.inputVisible = true;
      this.$nextTick(function() {
        this.$refs.input.focus();
      });
    },
    /**
     * 输入框变化触发
     * */
    handleInputChange(e) {
      this.inputValue = e.target.value;
    },
    /**
     * 新建提交
     */
    handleInputConfirm() {
      const inputValue = this.inputValue;
      let tags = this.tags;
      if (inputValue && tags.indexOf(inputValue) === -1) {
        addTag(this.vertexId, inputValue).then(data => {
          if (data) {
            tags = [...tags, inputValue];
            Object.assign(this, {
              tags,
              inputVisible: false,
              inputValue: ""
            });
          }
        });
      } else if (inputValue && tags.indexOf(inputValue) > -1) {
        this.$message.error("不可以有重名标签");
      }
    }
  }
};
</script>

<style scoped>
.attr-title{ padding-bottom: 10px; font-weight: bold; border-bottom: 1px solid #ddd; }
.ant-tag{ margin-top: 10px; }
</style>
