<template>
  <div class="tree-panel">
    <el-tree
      ref="cusTreeRef"
      :data="deplist"
      node-key="departmentid"
      default-expand-all
      highlight-current
      :check-strictly="true"
      :check-on-click-node="true"
      :expand-on-click-node="false"
      :show-checkbox="checked"
      @node-click="checkChange"
      :default-checked-keys="dep_default">
      <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>

import {mapGetters} from 'vuex'

export default {
  props:['checked',"dep_default"],
  components:{
  },
  computed:{
    ...mapGetters({
      pageOnlyRead:"pageOnlyRead"
    })
  },
  data () {
    return {
      deplist:[],
      cusChecked: [],
      responseData:[],
      currentKey:0
    }
  },
  methods:{
    async department () {
      const res = await this.$api.requested({
        "classname": "webmanage.department.department",
        "method": "querydepartment",
        "content": {
        }
      })
      // 数据格式转换成elementui-tree所需的格式
      this.responseData = res.data
      this.deplist = this.createMenu(res.data)
      // this.$store.dispatch('setDeplistData',this.deplist)
      
      this.$emit('onClick',{data:this.deplist[0],parent:[]})

      // 如果存在默认组织数据就执行
    },
    createMenu (array) {
      var that = this
      let arr = []
      console.log(that.pageOnlyRead,'-----')
      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'],
          disabled:that.pageOnlyRead,
          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
    },

    handleCheck (currentNode, treeStatus) {
      /**
       * @des 根据父元素的勾选或取消勾选，将所有子级处理为选择或非选中状态
       * @param { node: Object }  当前节点
       * @param { status: Boolean } （true ： 处理为勾选状态 ； false： 处理非选中）
       */
      const setChildStatus = (node, status) => {
          /* 这里的 id children 也可以是其它字段，根据实际的业务更改 */
          this.$refs.cusTreeRef.setChecked(node.departmentid, status)
          if (node.children) {
              /* 循环递归处理子节点 */
              for (let i = 0; i < node.children.length; i++) {
                  setChildStatus(node.children[i], status)
              }
          }
      }
      /* 设置父节点为选中状态 */
      const setParentStatus = (nodeObj) => {
          /* 拿到tree组件中的node,使用该方法的原因是第一次传入的 node 没有 parent */
          const node = this.$refs.cusTreeRef.getNode(nodeObj)
          if (node.parent.key) {
              this.$refs.cusTreeRef.setChecked(node.parent, true)
              setParentStatus(node.parent)
          }
      }

      /* 判断当前点击是选中还是取消选中操作 */
      if (treeStatus.checkedKeys.includes(currentNode.departmentid)) {
          setParentStatus(currentNode)
          setChildStatus(currentNode, true)
      } else {
          /* 取消选中 */
          if (currentNode.children) {
              setChildStatus(currentNode, false)
          }
      }

      this.cusChecked = [...this.$refs.cusTreeRef.getCheckedKeys()]
      this.$emit('onChecked',this.cusChecked)
      this.cusChecked = this.cusChecked
    },
    checkChange (a,b,c) {
      this.$emit('onClick',{data:a})
    }
  },
  mounted () {
    this.department()
  },
  watch:{
    pageOnlyRead () {
      this.department()
    },
    dep_default (val) {
      this.$emit('onChecked',this.dep_default)
    }
  }
}

</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>