<!--
 * @Author: your name
 * @Date: 2021-11-09 09:46:37
 * @LastEditTime: 2021-12-22 17:08:40
 * @LastEditors: Please set LastEditors
 * @Description: vue2-org-tree
 * @FilePath: \Foshan4A\src\layout\components\OrgTree\index.vue
-->
<template>
  <div class="orgTree">
    <div class="orgTreeContent">
      <vue2-org-tree :data="dataList" :horizontal="true" collapsable @on-expand="onExpand" :render-content="renderContent" />
    </div>
  </div>
</template>

<script>
export default {
  name: "OrgTree",
  props: {
    dataList: {
      type: Object,
      default: () => { },
    },
    renderContent: {
      type: Function,
    },
  },
  mounted () {
    this.toggleExpand(this.dataList, true);
  },
  watch: {
    dataList: {
      handler (val, old) {
        if (val != old) {
          this.toggleExpand(val, true);
        }
      },
      deep: true,
    },
  },
  methods: {
    collapse (list) {
      const _this = this;
      list.forEach(function (child) {
        if (child.expand) {
          child.expand = false;
        }
        child.children && _this.collapse(child.children);
      });
    },
    //展开
    onExpand (e, data) {
      const _this = this;
      if ("expand" in data) {
        data.expand = !data.expand;
        if (!data.expand && data.children) {
          _this.collapse(data.children);
        }
      } else {
        _this.$set(data, "expand", true);
      }
      if (data.expand) {
        this.$emit("expandData", data);
      }
    },
    //节点关闭按钮点击
    onNodeClick (e, data) {
      const _this = this;
      if (e.target.className === "icon el-icon-close") {
        this.decompose(_this.dataList.children, data.id);
      }
    },
    //删除指定数据
    decompose (data, id) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].id === id) {
          data.splice(i, 1);
        } else if (data[i].children && data[i].children.length > 0) {
          this.decompose(data[i].children, id);
        }
      }
    },
    //是否完全展开
    toggleExpand (data, val) {
      const _this = this;
      if (Array.isArray(data)) {
        data.forEach(function (item) {
          _this.$set(item, "expand", val);
          if (item.children) {
            _this.toggleExpand(item.children, val);
          }
        });
      } else {
        _this.$set(data, "expand", val);
        if (data.children) {
          _this.toggleExpand(data.children, val);
        }
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.orgTree {
  ::v-deep .orgTreeContent {
    .org-tree-node-btn {
      display: none;
    }
    .renderContent {
      .name {
        font-size: 14px;
        margin-top: 5px;
        max-width: 90px;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
      }
    }
  }
}
</style>