<template>
	<!-- 三级联动选择器 -->
	<view class="view-item view-item-3">
		<view class="label" @click="navigateBack">货区</view>
		<view class="select" @click="show = true">{{ selectedStorage || '请选择货区' }}</view>
		<u-picker :show="show" ref="uPicker" :columns="columns" @cancel="cancel" @confirm="confirm"
			@change="changeHandler"></u-picker>
	</view>
</template>

<script>
	export default {
		props: {
			selectedStorage: {
				type: String,
				default: ''
			}
		},
		data() {
			return {
				showPicker: false,
				columns: [
					[],
					[],
					[]
				], // 仓库、货架、货位
				warehouseShelvesData: {},
				shelfLocationsData: {}
			};
		},
		methods: {
			confirm(e) {
				const [warehouse, shelf, location] = e.value;
				this.$emit('select', {
					warehouse,
					shelf,
					location
				});
				this.showPicker = false;
			},
			// 返回上一页并清除缓存
			navigateBack() {
				// 清除相关缓存数据
				uni.removeStorageSync('lastSelectedStorage');
				uni.removeStorageSync('selectedWarehouse');
				uni.removeStorageSync('lastSelectedShelf');
				uni.removeStorageSync('lastSelectedLocation');

				// 重置相关数据
				this.selectedStorage = '';
				this.warehouse = '';
				this.shelf = '';
				this.location = '';
				uni.navigateTo({
					url: '/pages/warehouse/warehouse-select'
				});
			},
			cancel() {
				this.show = false;
			},
			changeHandler(e) {
				// 防御性检查，确保e和必要的属性存在
				if (!e) {
					console.warn('changeHandler: 事件对象为空');
					return;
				}

				console.log('changeHandler 事件:', JSON.stringify(e));

				// 获取列索引和选中的索引数组
				const {
					columnIndex,
					index,
					indexes = []
				} = e;
				console.log('列索引:', columnIndex, '选中索引:', index, 'indexes数组:',
					indexes);

				// 如果是选择了仓库（第0列）
				if (columnIndex === 0) {
					// 获取选中的仓库
					const warehouseName = this.columns[0][index];
					const warehouse = this.selectedWarehouse || {
						id: null,
						name: warehouseName
					};
					console.log('选中的仓库:', warehouseName, '仓库对象:', warehouse);

					// 如果有仓库ID，获取对应的货架
					if (warehouse.id) {
						console.log('开始获取货架数据，仓库ID:', warehouse.id);
						this.fetchShelves(warehouse.id).then(shelves => {
							console.log('获取到货架数据:', shelves);
							// 清空货位列
							this.columns[2] = [];
							// 更新UI
							this.$nextTick(() => {
								if (this.$refs.uPicker) {
									this.$refs.uPicker
										.setColumnValues(2, []);
								}
							});
						});
					}
				}

				// 如果是选择了货架（第1列）
				if (columnIndex === 1) {
					// 获取选中的货架索引
					const shelfIndex = index;
					console.log('选中的货架索引:', shelfIndex);

					// 确保货架数据有效
					if (Array.isArray(this.shelves) && this.shelves.length > 0 &&
						shelfIndex >= 0 && shelfIndex < this
						.shelves.length) {
						const selectedShelf = this.shelves[shelfIndex];
						console.log("选中的货架对象:", selectedShelf);

						// 保存选中的货架ID
						this.selectedSheId = selectedShelf.id;

						// 如果货架有ID，获取对应的货位
						if (selectedShelf?.id) {
							console.log('开始获取货位数据，货架ID:', selectedShelf.id);
							this.fetchLocations(selectedShelf.id).then(
								locations => {
									console.log('获取到货位数据:', locations);

									// 确保locations是数组且有数据
									if (Array.isArray(locations) && locations
										.length > 0) {
										// 更新货位列
										this.columns[2] = locations.map(item =>
											item.code || '未知货位');
										console.log('更新后的货位列:', this.columns[
											2]);

										// 更新UI
										this.$nextTick(() => {
											if (this.$refs.uPicker) {
												console.log(
													'更新货位选择器UI');
												this.$refs.uPicker
													.setColumnValues(2,
														this.columns[2]
													);
											}
										});
									} else {
										console.warn('获取到的货位数据为空');
										// 清空货位列
										this.columns[2] = ['暂无货位'];
										this.$nextTick(() => {
											if (this.$refs.uPicker) {
												this.$refs.uPicker
													.setColumnValues(2,
														this.columns[2]
													);
											}
										});
									}
								}).catch(error => {
								console.error('获取货位数据失败:', error);
								// 显示错误提示
								this.columns[2] = ['获取失败'];
								this.$nextTick(() => {
									if (this.$refs.uPicker) {
										this.$refs.uPicker
											.setColumnValues(2,
												this.columns[2]);
									}
								});
							});
						} else {
							console.warn('货架ID无效');
						}
					} else {
						console.warn('无效的货架索引或数据未准备好', {
							shelfIndex,
							shelvesLength: this.shelves?.length
						});
						// 清空货位列
						this.columns[2] = ['请先选择有效货架'];
						this.$nextTick(() => {
							if (this.$refs.uPicker) {
								this.$refs.uPicker.setColumnValues(2, this.columns[2]);
							}
						});
					}
				}
			},
		}
	}
</script>

<style>
	.view-item-3 {
		flex: 3 !important;
	}

	.view-item-4 {
		flex: 4 !important;
	}

	.view-item-6 {
		flex: 6 !important;
	}

	.view-item-7 {
		flex: 7 !important;
	}

	.view-item>.label {
		display: inline;
		padding: 10rpx;
		text-align: center;
		height: 40rpx;
		line-height: 40rpx;
		color: #000;
		font-size: 29rpx;
		background-color: #ccc;
		border-top-left-radius: 10rpx;
		border-bottom-left-radius: 10rpx;
	}

	.view-item>.select {
		padding: 10rpx;
		text-align: center;
		width: 100%;
		height: 40rpx;
		font-size: 18rpx;
		line-height: 40rpx;
	}
</style>