<template>
  <div id="ztreePanel" class="flex-col">
    <a-button
      type="primary"
      block
      @click="addRootEntityClassModal"
      v-if="editable"
      class="entity-class-z"
    >
      <a-icon type="plus" />
      新增根实体类
    </a-button>
    <!--<a-input-search placeholder="搜索实体类" @change="search"/>-->
    <a-spin
      tip="Loading..."
      class="entity-class-tree auto-overflow flex1"
      :spinning="spinning"
      :style="{ 'max-height': maxHeight + 'px' }"
    >
      <GiantTree
        :setting="setting"
        :nodes="nodes"
        @onAsyncSuccess="onAsyncSuccess"
        @onRightClick="onRightClick"
        @onClick="onClick"
        @onCreated="handleCreated"
      ></GiantTree>
    </a-spin>
    <v-contextmenu ref="contextmenu" @hide="clearRightSelect">
      <v-contextmenu-item @click="addChildEntityClass"
        >添加子节点</v-contextmenu-item
      >
      <!--<v-contextmenu-item @click="handleEditEntityClassName">修改</v-contextmenu-item>-->
      <v-contextmenu-item @click="deleteEntityClass">删除</v-contextmenu-item>
    </v-contextmenu>
  </div>
</template>

<script>
import GiantTree from "@/views/knowledge/common/ztree";
import { treeCommon } from "@/plugins/knowledge/treeCommon";

import { entClsTreeLazy, delEntityClass } from "@/api/graph/entityClass"

// 点击树节点的懒加载回调
function ajaxDataFilter(treeId, parentNode, responseData) {
  if (responseData) {
    for (var i = 0; i < responseData.data.length; i++) {
      responseData.data[i].name = responseData.data[i].entClsName;
      responseData.data[i].id = responseData.data[i].entClsID;
      if (responseData.data[i].childCount > 0) {
        responseData.data[i].isParent = true;
      }
      if (responseData.data[i].noneCount > 0) {
        responseData.data[i].iconSkin = "diy03";
      }
    }
  }
  return responseData.data;
}

export default {
  components: { GiantTree },
  mixins: [treeCommon],
  name: "ent-cls-ztree",
  //  editable 是否显示操作按钮  isLink: 是否能进行路由跳转
  props: {
    editable: {
      type: Boolean,
      default: true,
    },
    isLink: {
      type: Boolean,
      default: true,
    },
    id: {
      type: String,
    },
    activeId: {
      type: String,
    },
    rootId: {
      type: String,
    },
  },
  data() {
    return {
      searchValue: "", // 搜索的实体类名字
      treeList: [],
      spinning: false,
      maxHeight: 500,
      setting: {
        async: {
          enable: true,
          url: window.global.baseUrl() + "/knowledge/class/entcls/tree",
          dataFilter: ajaxDataFilter,
        },
      },
    };
  },
  events: {
    /**
     *更新后刷新左侧树
     * @param msg
     */
    ["entityClassZtree:entityClassUpdated"](msg) {
      let updateNode = this.ztreeObj.getNodeByParam("id", msg.entClsID, null);
      let newNode = Object.assign(updateNode, msg);
      this.ztreeObj.updateNode(newNode);
    },
    /**
     *刷新子节点
     * @param msg
     */
    ["entityClassZtree:refreshTreeNode"](msg) {
      let updateNode = this.ztreeObj
        .getNodeByParam("id", msg.entClsID, null)
        .getParentNode();
      this.ztreeObj.reAsyncChildNodes(updateNode, "refresh");
    },
    ["entityClassZtree:refreshTree"]() {
      this.ztreeObj.reAsyncChildNodes(null, "refresh");
    },
  },
  computed: {
    nodes() {
      return this.treeList;
    },
  },
  mounted() {
    this.$nextTick(function() {
      this.maxHeight = document.getElementById("ztreePanel").offsetHeight - 50;
    });
  },
  watch: {},
  methods: {
    refreshEntityClassList(id) {
      return entClsTreeLazy(id).then((res) => {
        res.forEach((v) => {
          v.id = v.entClsID;
        });
      });
    },
    search(e) {
      var str = e.data;
      if (this.searchTimeoutHandler) {
        clearTimeout(this.searchTimeoutHandler);
      }
      this.searchTimeoutHandler = setTimeout(() => {
        this.searchValue = str;
        this.searchTimeoutHandler = false;
      }, 800);
    },
    onClick(evt, treeId, treeNode) {
      // 点击事件
      this.$emit("nodeSelected", treeNode);
    },
    /**
     * 注入:添加根节点实体类模态窗
     * @param null
     * @returns {*}
     */
    addRootEntityClassModal() {
      const vm = this;
      this.$open("addRootEntityClassModal", {}, function(data) {
        // 刷新整个树
        if (data) {
          vm.ztreeObj.reAsyncChildNodes(null, "refresh");
        }
      });
    },
    /**
     * 注入：删除实体类
     */
    deleteEntityClass() {
      // 第二个参数为true会触发onRemove/beforeRemove 事件
      const id = this.onRightSelectNode.entClsID;
      const vm = this;
      this.$confirm({
        title: "你确定要删除吗?",
        content:
          "删除此实体类会删除下面所有的关系，请慎重！",
        okText: "确认",
        cancelText: "取消",
        onOk() {
         delEntityClass(id).then((res) => {
            if (res == null) {
              vm.ztreeObj.removeNode(vm.onRightSelectNode, true);
              vm.$message.success("删除成功");
            }
            if (res) {
              vm.ztreeObj.removeNode(vm.onRightSelectNode, true);
              vm.$message.success("删除成功");
              if (id === vm.$route.params.classId) {
                // 删除的是路由中的id，跳转实体类初始页面
                vm.$router.push("/mng/class");
              }
            }
          });
        },
        onCancel() {
          console.log("取消删除");
        },
      });
    },
    /**
     * 添加子实体类
     * @param null
     */
    addChildEntityClass() {
      const id = this.onRightSelectNode.id;
      const vm = this;
      this.$open(
        "addChildEntityClassModal",
        {
          pid: id,
        },
        function(boolean) {
          vm.refreshEntityClassList(id).then(() => {
            if (boolean) {
              vm.onRightSelectNode.isParent = true;
              vm.ztreeObj.reAsyncChildNodes(vm.onRightSelectNode, "refresh");
            }
          });
        }
      );
    },
    onAsyncSuccess(event, treeId, msg) {
      this.spinning = false;
      let node = this.ztreeObj.getNodes();
      let getAllRootList = [];
      node.forEach((v) => {
        var item = {};
        item["entClsID"] = v["entClsID"];
        item["entClsName"] = v["entClsName"];
        getAllRootList.push(item);
      });
      this.$emit("getAllRootList", getAllRootList);
      // 路由中有实体类id
      // if(this.$route.params){
      //   // this.ztreeObj.getNodeByParam("id", this.$route.params.classId, null);
      //     getEntClsParents(this.$route.params.classId).then(res => {
      //       let parentsList  = res
      //       let lastItem = res[res.length - 1]
      //       let node = this.ztreeObj.getNodeByParam("id", lastItem.entClsID, null);
      //       this.ztreeObj.expandNode(node, true)
      //     })
      // }
    },
    /**
     * 隐藏右键菜单
     */
    clearRightSelect() {
      this.$refs.contextmenu.hide();
    },
    // 右键菜单
    onRightClick(event, treeId, treeNodes) {
      const postition = {
        top: event.clientY,
        left: event.clientX,
      };
      // 可编辑
      if (this.editable) {
        this.$refs.contextmenu.show(postition);
      }
      // 右键选中的节点
      this.onRightSelectNode = treeNodes;
    },
    handleCreated(ztreeObj) {
      const vm = this;
      // 显示loading
      this.spinning = true;
      // 把ztree对象挂载到此vue实例中
      this.ztreeObj = ztreeObj;
      // onCreated 中操作ztreeObj对象展开第一个节点
      // 默认加载树的第一个节点展开
      ztreeObj.expandNode(ztreeObj.getNodes()[0], true);
      window.ztreeObj = ztreeObj;
      // setTimeout(function () {
      //   console.log(ztreeObj.getNodeByParam('entClsID', vm.$route.params))
      // }, 500)
    },
  },
};
</script>

<style>
.ant-tree.entity-class-tree {
  margin: 5px -10px;
  padding: 0 10px;
}

.entity-class-tree .ant-tree-title:hover .handleButton {
  visibility: visible;
}

.entity-class-tree .handleButton {
  visibility: hidden;
  line-height: 25px;
  position: relative;
  left: 5px;
}

.entity-class-z {
  margin-bottom: 10px;
}
</style>
