<template>
  <div class="tree-scroll">
    <el-tree ref="deviceTree" :data="deviceTree" :props="defaultProps" node-key="id" :default-expanded-keys="defaultExpandedKeys" :default-checked-keys="defaultCheckedKeys" :expand-on-click-node="false" highlight-current @node-click="handleNodeClick" />
  </div>
</template>

<script>
import { menu } from '@/api/storeManage/levelManage/level'

export default {
  name: 'DeviceTree',
  data() {
    return {
      deviceTree: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      defaultExpandedKeys: [],
      defaultCheckedKeys: []
    }
  },
  created() {
    this.getDeviceTree()
  },
  methods: {
    getDeviceTree() {
      let defaultCheckedData = {}
      menu().then((data) => {
        let storeroom = {}
        let devices = []
        this.deviceTree.splice(0, this.deviceTree.length)
        for (let i = 0; i < data.length; i++) {
          if (!storeroom.id) {
            storeroom = data[i].storeroomId
            data[i].name = data[i].deviceName
            data[i].isCurrent = true
            devices.push(data[i])
            // 设置第一个区域第一个节点的默认选中
            defaultCheckedData = data[i]
            // 第一个区域默认展开
            this.defaultExpandedKeys.push(data[i].storeroomId.id)
          } else if (storeroom.id !== data[i].storeroomId.id) {
            storeroom.children = devices
            this.deviceTree.push(storeroom)
            devices = []
            data[i].name = data[i].deviceName
            devices.push(data[i])
            storeroom = data[i].storeroomId
          } else {
            data[i].name = data[i].deviceName
            devices.push(data[i])
          }
          if (i === data.length - 1) {
            storeroom.children = devices
            this.deviceTree.push(storeroom)
          }
        }
        this.$nextTick(() => {
          // 设置第一个区域第一个节点的默认选中
          this.handleNodeClick(defaultCheckedData)
          this.$refs.deviceTree.setCurrentKey(defaultCheckedData.id)
        })
      })
    },
    handleNodeClick(selectedData) {
      if (selectedData.deviceName) {
        this.$emit('nodeClick', selectedData)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
