<template>
  <el-tree
    ref="tree"
    :props="props"
    :filter-node-method="filterNodeMethod"
    :load="loadNode"
    class="warehouse-tree"
    node-key="value"
    lazy
  >
    <template slot-scope="{ node, data }">
      <div
        :class="{ isDisabled: data.disabled }"
        class="node-wrapper"
        @click="handleNodeClick(data, node)"
      >
        <span>{{ node.label }}</span>
      </div>
    </template>
  </el-tree>
</template>

<script>
  // import {
  //   getWarehouse,
  //   getReservoir,
  //   getShelves,
  //   getLocation
  // } from '@/api/stockManagement'
  export default {
    props: {
      disabledList: {
        type: Array,
        default: () => []
      },
      filterNodeMethod: Function
    },
    data() {
      return {
        props: {
          label: 'label',
          children: 'children',
          isLeaf: 'leaf'
        }
      };
    },
    methods: {
      getInstance() {
        return this.$refs.tree;
      },
      handleNodeClick(data, node) {
        // if (data.disabled) return
        this.$emit('handleNodeClick', data, node);
      },
      loadNode(node, resolve) {
        const { level, data } = node;
        const api = {
          0: getWarehouse, //仓库
          1: getReservoir, //库区
          2: getShelves, // 货架
          3: getLocation //货位
        };
        if (api[level]) {
          const params = {};
          if (level > 0) {
            params.id = data.value.split('-')[0];
          }
          api[level](params)
            .then((res) => {
              if (res.success) {
                const arr = [];
                for (const key in res.data) {
                  const value = `${key}-${res.data[key]}-${level}`;
                  arr.push({
                    value,
                    label: res.data[key] || key,
                    leaf: level >= 3,
                    disabled: this.disabledList.includes(value)
                  });
                }
                resolve(arr);
              }
            })
            .catch(() => {
              resolve([]);
            });
        } else {
          resolve([]);
        }
      }
    }
  };
</script>

<style lang="scss" scoped>
  .isDisabled {
    background-color: #ccc;
    cursor: not-allowed;
  }
  .node-wrapper {
    flex: 1;
  }
</style>

<style lang="scss">
  .warehouse-tree {
    .el-tree-node__content:has(.isDisabled) {
      background-color: #ccc;
      cursor: not-allowed;
    }
  }
</style>
