<template>
  <div class="tree-panel">
    <el-tree
      ref="treeRef"
      :data="arealist"
      node-key="sa_saleareaid"
      :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 {
  props:['noDefaultData'],
  components:{
  },
  data () {
    return {
      arealist:[],
      currentKey:null
    }
  },
  methods:{
    async query_arealist (callback) {
      const res = await this.$api.requested({
        "classname": "webmanage.sale.salearea.salearea",
        "method": "query_area",
        "content": {
        }
      })
      // 数据格式转换成elementui-tree所需的格式
      this.arealist = this.createMenu(res.data)
      callback()
    },
    createMenu (array) {
      var that = this
      let arr = []
      function convertToElementTree(node) {
        // 新节点
        var elNode = {
          label: node["areaname"],
          remarks:node["remarks"],
          isused:node["isused"],
          sa_saleareaid:node['sa_saleareaid'],
          parentid:node['parentid'],
          children: []
        }
          
        if (node.subarea && node.subarea.length > 0) {
          // 如果存在子节点
          for (var index = 0; index < node.subarea.length; index++) {
          // 遍历子节点, 把每个子节点看做一颗独立的树, 传入递归构造子树, 并把结果放回到新node的children中
          elNode.children.push(convertToElementTree(node.subarea[index]));
          }
        }
        return elNode;
      }
      array.forEach((element) => {
        arr.push(convertToElementTree(element))
      });
      return arr
    },
    handleClick (row,node,VueComponent) {
      this.$emit('onClick',node.data)
    },
    setCurrentKey (id) {
      this.currentKey = id
      this.$nextTick(() => {
        this.$refs['treeRef'].setCurrentKey(this.currentKey)
      })
    },
  },
  mounted () {
    this.query_arealist(()=>{
      this.$emit('onClick',this.arealist[0])
      this.setCurrentKey(this.arealist[0].sa_saleareaid)
    })
  }
}

</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;
  height: calc(100vh - 130px);
  overflow-y: scroll;
}
</style>