<!--
 * @Description: 删除标签的确认弹出框组件
 * @Author: liusheng
 * @Date: 2024-07-03 16:30:56
-->
<template>
  <el-popover :visible.sync="visible" v-model="popupVisible" placement="bottom-start" 
    width="200" trigger="click" @show="handleShow" @hide="handleHide">
    <el-tree class="tree-block" :data="gatherTagTree" :props="treeProps" show-checkbox default-expand-all
      node-key="id" :default-checked-keys="treeCheckedKeys" @check="handleTreeNodeCheck" />
    <div style="text-align:right; margin-top:15px">
      <el-button type="text" size="mini" @click="handleCancel">取消</el-button>
      <el-button type="primary" size="mini" @click="handleConfirm">确定</el-button>
    </div>
    <i class="el-icon-document-copy mouse-pointer" slot="reference"></i>
  </el-popover>
</template>

<script>
export default {
  name: 'GatherTagSetPopup',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    tagList: {
      type: Array,
      default: []
    },
  },
  data() {
    return {
      popupVisible: false,

      gatherTagTree: [],
      treeProps: { children: 'tagList', label: 'name' },
      treeCheckedKeys: [0],   // 定义一个元素，以避免显示表单验证错误信息

      tagDifference: []       // 标签差集 = [传入的标签列表]-[标签树中的标签列表]
    }
  },

  methods: {
    handleShow() {
      this.appAxios("GET", this.commonUrl.URL_TREE_ALL_GATHER_TAGS).then(result => {
        if (result == null) return;
        this.gatherTagTree = result.data;
        this.calcTagDifference();
      })
      this.treeCheckedKeys = this.tagList;
      this.$emit("update:visible", true);
    },

    //计算传入的标签列表和标签树中的标签列表的差集
    calcTagDifference() {
      let tagsInTree = [];
      this.gatherTagTree.forEach(tagSet => {
        let tags = tagSet.tagList.map(tag => tag.id);
        tagsInTree.push(...tags)
      });
      this.tagDifference = this.tagList.filter(item => !tagsInTree.includes(item));
    },

    handleHide() {
      this.$emit("update:visible", false);
    },
    
    handleTreeNodeCheck(_data, state) {
      this.treeCheckedKeys = state.checkedKeys.filter(Boolean);
    },
    
    handleConfirm() {
      this.popupVisible = false;
      let newTagList = [...this.tagDifference]
      this.$emit("confirm", newTagList.concat(this.treeCheckedKeys));
      this.handleHide();
    },
    
    handleCancel() {
      this.popupVisible = false;
    },
  }
}
</script>

<style scoped>
.tree-block {
  height: 220px;
  overflow-y: auto;
  margin-bottom: 20px;
}
</style>
