<template>
  <el-select
    v-model="selected"
    :placeholder="placeholder"
    :clearable="clearable"
    :disabled="disabled"
    :size="size"
    filterable
    @change="onChange"
    style="width: 100%"
  >
    <el-option
      v-for="item in warehouseOptions"
      :key="item.actualWarehouseId"
      :label="item.actualWarehouseName"
      :value="item.actualWarehouseId"
    >
      <span :style="{ paddingLeft: item.level * 20 + 'px' }">
        {{ item.actualWarehouseName }}
      </span>
    </el-option>
  </el-select>
</template>

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

export default {
  name: 'ActualWarehouseSelect',
  props: {
    value: {
      type: [Number, String, null],
      default: null
    },
    placeholder: {
      type: String,
      default: '请选择实际库区/库位'
    },
    clearable: {
      type: Boolean,
      default: true
    },
    disabled: {
      type: Boolean,
      default: false
    },
    size: {
      type: String,
      default: 'mini'
    },
    showTop: {
      type: Boolean,
      default: false // 是否显示顶级节点
    }
  },
  data() {
    return {
      warehouseOptions: [],
      selected: this.value
    };
  },
  watch: {
    value(val) {
      this.selected = val;
    }
  },
  mounted() {
    this.loadOptions();
  },
  methods: {
    loadOptions() {
      listActualWarehouse({ pageSize: 1000 }).then(response => {
        console.log('实际库区/库位自关联API返回数据:', response);
        const data = response.rows || [];
        console.log('处理后的数据:', data);
        // this.warehouseOptions = this.buildTreeOptions(data);
        this.warehouseOptions = data;
        console.log('构建的树形选项:', this.warehouseOptions);
      }).catch(error => {
        console.error("加载仓库选项失败:", error);
        this.warehouseOptions = [];
      });
    },
    buildTreeOptions(data, parentId = null, level = 0) {
      const options = [];
      
      data.forEach(item => {
        if (item.parentId === parentId) {
          const option = {
            warehouseId: item.warehouseId,
            warehouseName: item.warehouseName,
            level: level
          };
          
          // 递归构建子节点
          const children = this.buildTreeOptions(data, item.warehouseId, level + 1);
          if (children.length > 0) {
            options.push(option);
            options.push(...children);
          } else {
            options.push(option);
          }
        }
      });
      
      return options;
    },
    onChange(val) {
      this.$emit('input', val);
      this.$emit('change', val);
    }
  }
};
</script>

<style scoped>
.el-select {
  width: 100%;
}
</style>
