<template>
  <div class="tree-panel">
    <el-tree
      ref="treeRef"
      :data="deplist"
      node-key="departmentid"
      :current-node-key="currentKey"
      default-expand-all
      highlight-current
      :expand-on-click-node="false"
      @node-click="handleClick">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <slot name="operation" :data="data"></slot>
        </span>
      </span>
    </el-tree>
  </div>
</template>

<script>


export default {
  components:{
  },
  data () {
    return {
      deplist:[],
      departmentid:0,
      currentKey:null
    }
  },
  methods:{
    async department (callback) {
      const res = await this.$api.requested({
        "classname": "webmanage.department.department",
        "method": "querydepartment",
        "content": {
        }
      })
      // 数据格式转换成elementui-tree所需的格式
      this.deplist = this.createMenu(res.data)
      this.$store.dispatch('setDeplistData',this.deplist)
      callback()
    },
    createMenu (array) {
      var that = this
      let arr = []
      function convertToElementTree(node) {
        // 新节点
        var elNode = {
          label: node["depname"],
          parentid:node['parentid'],
          departmentid:node["departmentid"],
          value:node["departmentid"],
          remarks:node["remarks"],
          isused:node["isused"],
          changedate:node['changedate'],
          changeby:node['changeby'],
          createdate:node['createdate'],
          createby:node['createby'],
          depno:node['depno'],
          sequence:node['sequence'],
          children: []
        }
          
        if (node.subdep && node.subdep.length > 0) {
          // 如果存在子节点
          for (var index = 0; index < node.subdep.length; index++) {
          // 遍历子节点, 把每个子节点看做一颗独立的树, 传入递归构造子树, 并把结果放回到新node的children中
          elNode.children.push(convertToElementTree(node.subdep[index]));
          }
        }
        return elNode;
      }
      array.forEach((element) => {
        arr.push(convertToElementTree(element))
      });
      return arr
    },
    handleClick (row,node,VueComponent) {
      this.$emit('onClick',node)
    },
    setCurrentKey (id) {
      this.currentKey = id
      this.$nextTick(() => {
        this.$refs['treeRef'].setCurrentKey(this.currentKey)
      })
    },
  },
  watch: {
  },
  mounted () {
    this.department(()=>{
      this.$emit('onClick',{data:this.deplist[0],parent:[]})
      this.setCurrentKey(this.deplist[0].departmentid)
    })
  }
}

</script>
<style>
.tree-panel .el-tree {
  background: none;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  background: none;
}
</style>
<style scoped>
.tree-panel{
  padding: 16px;
  font-size: 14px;
  /* width:300px; */
  background: #FAFAFA;
}

</style>