<template>
  <view class="input-group">
    <view class="general-label">{{ label }}</view>
    <view class="select-label" @click="showPicker = true">
      {{ selectedText || placeholder }}
    </view>
    <u-picker 
      :show="showPicker" 
      ref="uPicker" 
      :columns="columns" 
      @confirm="handleConfirm"
      @change="handleChange"
    ></u-picker>
  </view>
</template>

<script>
export default {
  props: {
    label: {
      type: String,
      default: '仓库'
    },
    placeholder: {
      type: String,
      default: '请选择仓库/货架/货位'
    },
    warehouses: {
      type: Array,
      default: () => []
    },
    warehouseShelvesData: {
      type: Object,
      default: () => ({})
    },
    shelfLocationsData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      showPicker: false,
      columns: [[], [], []],
      selectedText: '',
      selectedWarehouse: null,
      selectedShelf: null,
      selectedLocation: null
    };
  },
  watch: {
    warehouses: {
      immediate: true,
      handler(newVal) {
        if (newVal.length > 0) {
          this.columns[0] = newVal.map(item => item.name);
        }
      }
    }
  },
  methods: {
    handleConfirm(e) {
      this.showPicker = false;
      const [warehouse, shelf, location] = e.value;
      this.selectedText = `${warehouse}/${shelf}/${location}`;
      this.$emit('confirm', {
        warehouse,
        shelf,
        location
      });
    },
    handleChange(e) {
      const { columnIndex, value } = e;
      if (columnIndex === 0) {
        const selectedWarehouse = this.warehouses.find(item => item.name === value);
        if (selectedWarehouse && this.warehouseShelvesData[selectedWarehouse.id]) {
          this.columns[1] = this.warehouseShelvesData[selectedWarehouse.id].map(item => item.code);
          this.columns[2] = [];
        }
      } else if (columnIndex === 1) {
        const selectedShelf = this.warehouseShelvesData[this.selectedWarehouse.id].find(item => item.code === value);
        if (selectedShelf && this.shelfLocationsData[selectedShelf.id]) {
          this.columns[2] = this.shelfLocationsData[selectedShelf.id].map(item => item.code);
        }
      }
    }
  }
};
</script>

<style scoped>
.input-group {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}
.general-label {
  width: 150rpx;
  font-size: 28rpx;
  color: #333;
}
.select-label {
  flex: 1;
  height: 80rpx;
  line-height: 80rpx;
  padding: 0 20rpx;
  border: 1px solid #eee;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #999;
}
</style>