<template>
  <div>
    <el-tree key="warehouseTree" v-loading="loading" :data="treeData" :props="treeProps" node-key="actualWarehouseId" highlight-current
      @node-click="handleNodeClick" :expand-on-click-node="false" class="stock-tree" />
  </div>
</template>

<script>
import { listWarehouse } from '@/api/wms/warehouse';
// import { listActualWarehouse } from '@/api/wms/actualWarehouse';
import { treeActualWarehouseTwoLevel } from '@/api/wms/actualWarehouse';

export default {
  name: "WarehouseTree",
  props: {
    warehouseType: {
      type: String,
      default: 'real'
    },
  },
  data() {
    return {
      treeData: [],
      loading: true,
      treeProps: {
        children: 'children',
        label: 'actualWarehouseName',
        isLeaf: 'isLeaf'
      }
    };
  },
  watch: {
    warehouseType: {
      handler(newVal, oldVal) {
        this.getWarehouseTree()
      },
      immediate: true
    }
  },
  methods: {
    loadChildren(node, resolve) {
      if (this.warehouseType !== 'real') {
        return;
      }
      if (node.level === 0) {
        // resolve(this.handleTree(this.treeData, 'warehouseId', 'parentId'));
      } else {
        listActualWarehouse({ parentId: node.data.actualWarehouseId }).then(response => {
          resolve(response.data);
        });
      }
    },
    getWarehouseTree() {
      this.loading = true;
      if (this.warehouseType === 'real') {
        treeActualWarehouseTwoLevel().then(response => {
          this.treeData = response.data
          this.loading = false;
        });
      } else {
        listWarehouse().then(response => {
          this.treeData = response.data.map(item => ({
            ...item,
            actualWarehouseId: item.warehouseId,
            actualWarehouseName: item.warehouseName
          }))
          this.loading = false;
        });
      }
    },
    handleTree(data, id, parentId) {
      const cloneData = JSON.parse(JSON.stringify(data));
      return cloneData.filter(father => {
        const branchArr = cloneData.filter(child => father[id] === child[parentId]);
        if (branchArr.length > 0) father.children = branchArr;
        return father[parentId] === 0 || father[parentId] === null;
      });
    },
    handleNodeClick(node) {
      this.$emit('node-click', node);
    }
  }
};
</script>