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

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

export default {
  name: "WarehouseTree",
  props: {
    warehouseType: {
      type: String,
      default: 'real'
    },
  },
  data() {
    return {
      treeData: [],
      loading: true,
      treeProps: {
        children: 'children',
        label: 'warehouseLabel',
        isLeaf: () => false
      }
    };
  },
  watch: {
    warehouseType: {
      handler(newVal, oldVal) {
        this.getWarehouseTree()
      },
      immediate: true
    }
  },
  methods: {
    getWarehouseTree() {
      this.loading = true;
      if (this.warehouseType === 'real') {
        listActualWarehouse({ pageSize: 1000 }).then(response => {
          this.treeData = response.rows.map(item => ({
            ...item,
            warehouseLabel: item.actualWarehouseName
          }))
          this.loading = false;
          // this.treeData = [{ warehouseName: '全部', value: undefined },  ...this.handleTree(response.rows, 'warehouseId', 'parentId')];
        });
      } else {
        listWarehouse().then(response => {
          this.treeData = response.data.map(item => ({
            ...item,
            warehouseLabel: item.warehouseName
          }))
          this.loading = false;
          // this.treeData = [{ warehouseName: '全部', value: undefined },  ...this.handleTree(response.data, 'warehouseId', 'parentId')];
        });
      }
    },
    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>

<!-- <style scoped>
.stock-tree-card {
  height: 100%;
  border: none;
  box-shadow: none;
}
.stock-tree-title {
  font-weight: bold;
  font-size: 16px;
  padding: 8px 0;
}
.stock-tree {
  min-height: 500px;
  max-height: 80vh;
  overflow-y: auto;
}
</style> -->
