<template>
	<view class="bg-image">
		<bindSelectMat type="dialog" ref="proup" @close="handlePopupClose" @selected="bindSelectedMat" />

		<view class="diy-flex-row">
			<view style="flex: 3">
				<!-- 占位 -->
			</view>
			<view style="flex: 80;margin: 5rpx;">
				<view class="diy-flex-row">
					<view class="rightImageContainer" @click="cameraScanCode" style="flex: 12;padding-top: 20rpx;">
						<image style="width: 60rpx;height: 60rpx" src="/static/scan.png" />
					</view>

					<view class="uni-input-wrapper" style="flex: 60;">
						<input id="inputMatCode" class="uni-input" style="font-size: 50rpx; padding: 10rpx;"
							:placeholder="placeholderText" v-model="matCodeCondition" ></input>
					</view>

					<view style="flex: 3;">
					</view>

					<view style="flex: 30;">
						<button @click="queryMatList">查询</button>
					</view>
				</view>
			</view>
			<view style="flex: 3">
				<!-- 占位 -->
			</view>
		</view>

		<view class="diy-flex-column" style="margin-top: 20rpx;">
			<view class="diy-flex-inforow" style="flex: 1;">
				<view style="flex: 5;"></view>

				<view style="flex: 35;font-weight: 700;">货架类型：</view>
				<view class="shelf-type-picker-container" style="flex: 55;font-size: 30rpx;font-weight: 700;">
					<picker :range="shelfTypeOptions" @change="shelfTypeOptionChange" range-key="shelfTypeName"
						:value="selectedShelfTypeIndex" style="font-size: 35rpx;">
						<view class="uni-input" style="padding-left: 5rpx;">
							{{shelfTypeOptions[selectedShelfTypeIndex].shelfTypeName}}
						</view>
					</picker>
				</view>

				<view style="flex: 3;"></view>

				<view style="flex: 32;">
					<button class="mini-btn" type="warn" size="mini" @click="callEmptyShelf">呼叫货架</button>
				</view>
			</view>

			<view class="diy-flex-inforow" style="flex: 1;">
				<view style="flex: 5;"></view>

				<view style="flex: 35;">工位编码：</view>

				<view style="flex: 90;overflow:hidden;">{{locationCode}}</view>
				<!-- 
				<view style="flex: 30;">
					<button class="mini-btn" type="warn" size="mini" @click="callEmptyShelf">呼叫货架</button>
				</view> -->
			</view>

			<view class="diy-flex-inforow" style="flex: 1;">

				<view style="flex: 5;"></view>

				<view style="flex: 35;">货架编码：</view>

				<view style="flex: 90;overflow:hidden;">{{shelfCode}}</view>

			</view>

			<view class="diy-flex-inforow" style="flex: 1;">

				<view style="flex: 5;"></view>

				<view style="flex: 35;">物料编码：</view>

				<view style="flex: 90;overflow:hidden;">{{matCode}}</view>

			</view>

			<view class="diy-flex-inforow" style="flex: 1;">

				<view style="flex: 5;"></view>

				<view style="flex: 35;">物料名称：</view>

				<view style="flex: 90;overflow:hidden;">{{matName}}</view>

			</view>
			


			<view class="diy-flex-inforow" style="flex: 1;">

				<view style="flex: 5;"></view>

				<view style="flex: 35;">物料规格：</view>

				<view style="flex: 90;overflow:hidden;">{{matSpec}}</view>

			</view>
			
			<view class="diy-flex-inforow" style="flex: 1;">
			
				<view style="flex: 5;"></view>
			
				<view style="flex: 35;">物料批次：</view>
			
				<view class="uni-input-wrapper" style="flex: 80;">
					<input class="uni-input" style="font-size: 40rpx; " placeholder="请输入批次" v-model="matBatch"></input>
				</view>
				
				<view style="flex: 10;"></view>
			
			</view>

			<view class="diy-flex-inforow" style="flex: 1;">

				<view style="flex: 5;"></view>

				<view style="flex: 35;">物料数量：</view>

				<view class="uni-input-wrapper" style="flex: 50;">
					<input class="uni-input" type="number" style="font-size: 40rpx; " placeholder="请输入物料数量" v-model="matQty"></input>
				</view>

				<view style="flex: 40;">
					<button @click="bind" class="mini-btn" style="margin-left: 10rpx;" type="warn"
						size="mini">绑定</button>
				</view>

			</view>

			<view style="flex: 1;">
				<view style="flex: 40;text-align: center;">

					<view class="picker-container">
						<view> 点击选择送回区域：</view>
						<picker ref="shelfAreaPicker" :range="shelfAreaOptions" range-key="locationAreaName"
							:value="selectedShelfAreaIndex" @change="onShelfAreaChange" style="font-size: 35rpx;">
							<view class="uni-input">{{shelfAreaOptions[selectedShelfAreaIndex].locationAreaName}}</view>
						</picker>
					</view>

					<button style="font-size: 40rpx;margin: 15rpx;background-color: green;" size="mini"
						@click="sendShelfBack">送货架</button>
				</view>
			</view>
		</view>
	
	</view>
</template>

<script>
	import bindSelectMat from '@/pages/bindSelectMat/bindSelectMat.vue';

	import {
		recive
	} from '../../src/libs/Broadcast.js';

	import {
		unregisterReceiver
	} from '../../src/libs/Broadcast.js';

	import {
		getConfig
	} from '@/config.js';

	import {
		saveConfig
	} from '@/config.js';

	import {
		getServerIPAndPort
	} from '@/config.js';

	export default {
		components: {
			bindSelectMat
		},
		data() {
			return {

				isNeedScanLocationCode: true,
				isNeedCallShelfCode: true,

				placeholderText: '请先扫描工位码',
				matCodeCondition: '', //物料编码搜索条件
				matBaseInfoId: null,
				matCode: '',
				locationId: null,
				locationCode: '',
				shelfId: null,
				shelfCode: '',
				matCode: '',
				matName: '',
				matBatch:'',
				matSpec: '',
				matQty: 0, //默认数量值

				// 货架区域选项
				shelfAreaOptions: [{
					id: 1,
					locationAreaName: '请先获取工位码'
				}],
				selectedShelfAreaIndex: 0, // 选择的货架区域索引

				// 需要的空货架类型选项
				shelfTypeOptions: [{
					id: 1,
					shelfTypeName: '请先获取工位码'
				}],
				selectedShelfTypeIndex: 0, // 选择的货架类型索引

				userName: '', //当前登录的用户名
			}
		},
		onShow: function() {
			this.userName = getConfig('userName', 'admin');

			const self = this; // 保存this的引用
			recive(function(res) {
				console.log("Success:" + res.data);
				self.analysisScanCode(res.data);
			}, function(err) {
				console.log("Error:", JSON.stringify(err)); // 正确打印错误信息
			});
		},
		methods: {
			//摄像头扫码
			cameraScanCode() {
				uni.scanCode({
					success: (res) => {
						console.log('扫码结果:', res.result);
						this.analysisScanCode(res.result);
					},
					fail: (err) => {
						console.error('扫码失败:', err);
						// 处理扫码失败的情况
					}
				});
			},
			//扫码枪扫码
			analysisScanCode: function(encodedString) {
				// 去除末尾的逗号和"..."（如果有的话）
				encodedString = encodedString.replace(/,\s*\.\.\.$/, '');
				this.locationCode = encodedString;
				this.getShelfInfoByLocationCode(true);
			},
			getShelfInfoByLocationCode: function(isTip) {
				//调用接口获取当前工位信息 当前工位是否有货架
				var serverIPAndPort = getServerIPAndPort();
				uni.request({
					url: 'http://' + serverIPAndPort + '/pdaMatBind/getShelfInfoByLocationCode', // 请求的接口地址
					method: 'POST', // 设置请求方式为 POST
					data: {
						"locationCode": this.locationCode,
						"shelfCode": this.locationCode,
						"userName": this.userName,
						"deviceType": "PDA"
					},
					header: {
						'Content-Type': 'application/json', // 如果需要以JSON格式发送数据
					},
					success: (res) => {
						// 请求成功的回调函数
						if (res.statusCode === 200) {
							//接口返回数据为200 表示获取成功！
							if (res.data.code == 200) {
								this.matCodeCondition = '';
								
								this.locationId = res.data.data.locationId;
								this.locationCode = res.data.data.locationCode;
								this.shelfId = res.data.data.shelfId;
								this.shelfCode = res.data.data.shelfCode;
								this.shelfTypeOptions = res.data.data.shelfTypes;
								this.selectedShelfTypeIndex = getConfig("bindSelectedShelfTypeIndex", 0);

								this.shelfAreaOptions = res.data.data.locationArea;
							
								var index = getConfig("bindSelectedShelfAreaIndex", 0);
								if (index + 1 < this.shelfAreaOptions.length) {
									this.selectedShelfAreaIndex = index;
								}

								if (this.shelfId == null) {
									this.shelfCode = '(工位无货架，请呼叫！)';
									this.isNeedScanLocationCode = false;
									this.isNeedCallShelfCode = true;
									this.placeholderText = '请呼叫货架';
								} else if (this.shelfId != null && this.shelfCode != null && this
									.shelfCode.includes('运输中')) {
									this.placeholderText = '请等待货架运输';

								} else {
									this.isNeedScanLocationCode = false;
									this.isNeedCallShelfCode = false;
									this.placeholderText = '输入编码或名称';
								}
								if (isTip) {
									uni.showToast({
										title: '获取成功!',
										icon: 'none',
										duration: 1500
									});
								}

							} else {
								if (isTip) {
									uni.showToast({
										title: '获取失败:' + res.data.message,
										icon: 'none',
										duration: 3600
									});
									this.clear();
								}
							}

						} else {
							if (isTip) {
								uni.showToast({
									title: '服务器返回错误状态码' + res.statusCode,
									icon: 'none',
									duration: 3000
								});
								this.clear();
							}
						}
					},
					fail: (err) => {
						// 请求失败的回调函数
						if (isTip) {
							uni.showToast({
								title: '请求失败' + err.errMsg,
								icon: 'none',
								duration: 3000
							});

							this.clear();
						}
					},
					complete: (event) => {
						// 请求完成的回调函数（无论成功或失败都会调用）
						console.log('请求完成', event);
					}
				});
			},

			bindSelectedMat: function(item) {
				console.log('用户选择了项目:', item);
				this.matCode = item.matCode;
				this.matName = item.matName;
				this.matSpec = item.matSpec;
				this.matQty = item.matDefaultQty;
				this.matBaseInfoId = item.id;
			},

			//物料绑定
			bind: function() {
				this.userName = getConfig('userName', '');
				var serverIPAndPort = getServerIPAndPort();
				uni.request({
					url: 'http://' + serverIPAndPort + '/pdaMatBind/bindMatDetail', // 请求的接口地址
					method: 'POST', // 设置请求方式为 POST
					data: {
						"locationId": this.locationId,
						"locationCode": this.locationCode,
						"shelfId": this.shelfId,
						"shelfCode": this.shelfCode,
						"matBaseInfoId": this.matBaseInfoId,
						"matCode": this.matCode,
						"matBatch": this.matBatch,
						"qty": this.matQty,
						"userName": this.userName,
						"deviceType": "PDA"
					},
					header: {
						'Content-Type': 'application/json', // 如果需要以JSON格式发送数据
					},
					success: (res) => {
						// 请求成功的回调函数
						if (res.statusCode === 200) {
							//接口返回数据为200 表示获取成功！
							if (res.data.code == 200) {
								this.clearMatInfo();
								uni.showToast({
									title: '绑定成功!',
									icon: 'none',
									duration: 1500
								});

							} else {
								this.visible = false;
								uni.showToast({
									title: '绑定失败:' + res.data.message,
									icon: 'none',
									duration: 1500
								});
							}

						} else {
							uni.showToast({
								title: '绑定失败:服务器返回错误状态码' + res.statusCode,
								icon: 'none',
								duration: 1500
							});
						}
					},
					fail: (err) => {
						// 请求失败的回调函数
						uni.showToast({
							title: '请求失败' + err.errMsg,
							icon: 'none',
							duration: 3000
						});
					},
					complete: (event) => {
						// 请求完成的回调函数（无论成功或失败都会调用）
						console.log('请求完成', event);
					}
				});

			},

			queryMatList: function() {
				if (this.isNeedScanLocationCode) {
					uni.showToast({
						title: '请先扫描工位码！',
						icon: 'none',
						duration: 1000
					});
					return;
				}
				if (this.isNeedCallShelfCode) {
					uni.showToast({
						title: '请先呼叫货架！',
						icon: 'none',
						duration: 1000
					});

					this.getShelfInfoByLocationCode(false);
					return;
				}
				if (this.matCodeCondition == null || this.matCodeCondition == '') {
					uni.showToast({
						title: '输入物料编码或物料名称后进行查询！',
						icon: 'none',
						duration: 1000
					});
					return;
				} else {
					this.clearMatInfo();
					saveConfig('matCodeCondition', this.matCodeCondition);
					
					this.$refs.proup.show();
				}
			},

			//呼叫空货架
			callEmptyShelf: function() {
				if (this.isNeedScanLocationCode) {
					uni.showToast({
						title: '请先扫描工位码!',
						icon: 'none',
						duration: 3000
					});
					return;
				}

				if (this.selectedShelfTypeIndex == 0) {
					uni.showToast({
						title: '请选择需要呼叫的货架类型!',
						icon: 'none',
						duration: 3000
					});
					return;
				}

				saveConfig("bindSelectedShelfTypeIndex", this.selectedShelfTypeIndex);
				this.userName = getConfig('userName', '');
				var serverIPAndPort = getServerIPAndPort();
				uni.request({
					url: 'http://' + serverIPAndPort + '/pdaMatBind/callEmptyShelf', // 请求的接口地址
					method: 'POST', // 设置请求方式为 POST
					data: {
						"locationId": this.locationId,
						"locationCode": this.locationCode,
						'needShelfTypeId': this.shelfTypeOptions[this.selectedShelfTypeIndex].id,
						'needShelfTypeName': this.shelfTypeOptions[this.selectedShelfTypeIndex].shelfTypeName,
						"userName": this.userName,
						"deviceType": "PDA"
					},
					header: {
						'Content-Type': 'application/json', // 如果需要以JSON格式发送数据
					},
					success: (res) => {
						// 请求成功的回调函数
						if (res.statusCode === 200) {
							//接口返回数据为200 表示获取成功！
							if (res.data.code == 200) {
								uni.showToast({
									title: '呼叫成功，请等待!',
									icon: 'none',
									duration: 2500
								});
								this.getShelfInfoByLocationCode(false);
							} else {
								uni.showToast({
									title: '呼叫失败:' + res.data.message,
									icon: 'none',
									duration: 2500
								});
							}

						} else {
							uni.showToast({
								title: '呼叫失败:服务器返回错误状态码' + res.statusCode,
								icon: 'none',
								duration: 2500
							});
						}
					},
					fail: (err) => {
						// 请求失败的回调函数
						uni.showToast({
							title: 'http请求失败' + err.errMsg,
							icon: 'none',
							duration: 2500
						});
					},
					complete: (event) => {
						// 请求完成的回调函数（无论成功或失败都会调用）
						console.log('请求完成', event);
					}
				});

			},

			//送回货架
			sendShelfBack: function() {
				if (this.isNeedScanLocationCode) {
					uni.showToast({
						title: '请先扫描工位码!',
						icon: 'none',
						duration: 3000
					});
					return;
				}

				if (this.shelfId == null) {
					uni.showToast({
						title: '当前工位无货架！无法送货架!',
						icon: 'none',
						duration: 3000
					});
					return;
				} else if (this.shelfId != null && this.shelfCode != null && this
					.shelfCode.includes('运输中')) {
					uni.showToast({
						title: '当前工位无货架！无法送货架!',
						icon: 'none',
						duration: 3000
					});
					return;
				}


				if (this.selectedShelfAreaIndex == 0) {
					uni.showToast({
						title: '请选择需要送回的位置区域',
						icon: 'none',
						duration: 3000
					});
					return;
				}

				saveConfig("bindSelectedShelfAreaIndex", this.selectedShelfAreaIndex);
				this.userName = getConfig('userName', '');
				var serverIPAndPort = getServerIPAndPort();
				uni.request({
					url: 'http://' + serverIPAndPort + '/pdaMatBind/bindSendBackShelf', // 请求的接口地址
					method: 'POST', // 设置请求方式为 POST
					data: {
						"locationId": this.locationId,
						"locationCode": this.locationCode,
						"shelfId": this.shelfId,
						"shelfCode": this.shelfCode,
						'sendBackLocationAreaId': this.shelfAreaOptions[this.selectedShelfAreaIndex].id,
						'sendBackLocationAreaName': this.shelfAreaOptions[this.selectedShelfAreaIndex]
							.locationAreaName,
						"userName": this.userName,
						"deviceType": "PDA"
					},
					header: {
						'Content-Type': 'application/json', // 如果需要以JSON格式发送数据
					},
					success: (res) => {
						// 请求成功的回调函数
						if (res.statusCode === 200) {
							//接口返回数据为200 表示获取成功！
							if (res.data.code == 200) {
								uni.showToast({
									title: '送货架呼叫成功，请等待!',
									icon: 'none',
									duration: 2500
								});
								this.getShelfInfoByLocationCode(false);

							} else {
								uni.showToast({
									title: '送货架呼叫失败:' + res.data.message,
									icon: 'none',
									duration: 2500
								});
							}

						} else {
							uni.showToast({
								title: '送货架呼叫失败:服务器返回错误状态码' + res.statusCode,
								icon: 'none',
								duration: 2500
							});
						}
					},
					fail: (err) => {
						// 请求失败的回调函数
						uni.showToast({
							title: 'http请求失败' + err.errMsg,
							icon: 'none',
							duration: 2500
						});
					},
					complete: (event) => {
						// 请求完成的回调函数（无论成功或失败都会调用）
						console.log('请求完成', event);
					}
				});

			},

			//清空当前界面所有内容
			clear: function() {
				this.locationId = null;
				this.locationCode = '';
				this.shelfId = null;
				this.shelfCode = '';
				this.isNeedCallShelfCode = true;
				this.isNeedScanLocationCode = true;
				this.placeholderText = '请先扫描工位码';
			},
			shelfTypeOptionChange(e) {
				this.selectedShelfTypeIndex = e.detail.value;
			},
			onShelfAreaChange(e) {
				this.selectedShelfAreaIndex = e.detail.value;
			},

			clearMatInfo: function() {
				this.matCode = '';
				this.matName = '';
				this.matSpec = '';
				this.matBatch = '';
				this.matQty = 0;
			},
			handlePopupClose() {
				// 弹出层关闭后的处理逻辑
				console.log('弹出层已关闭');
			},
		}
	}
</script>

<style>
	.picker-container {
		border-radius: 5rpx;
		border: 2rpx solid #000;
		/* 设置边框宽度和颜色 */
		margin: 25rpx auto;
		/* 上下边距为5rpx，左右边距自动，以实现水平居中 */
		width: 400rpx;
		/* 设置宽度 */
		/* 其他样式保持不变 */
	}

	.shelf-type-picker-container {
		border-radius: 5rpx;
		border: 2rpx solid #000;
		/* 设置边框宽度和颜色 */
		margin-left: 25rpx auto;
		margin-right: 25rpx auto;
		/* 上下边距为5rpx，左右边距自动，以实现水平居中 */
		width: 400rpx;
		/* 设置宽度 */
		/* 其他样式保持不变 */
	}

	.uni-input-wrapper {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		flex-wrap: nowrap;
		background-color: #FFFFFF;
	}

	.mini-btn {
		margin-right: 10rpx;
	}

	.bg-image {
		background-image: url('/static/background.png');
		/* 背景图片路径 */
		background-size: cover;
		/* 背景图片覆盖整个元素 */
		background-position: center;
		/* 背景图片居中 */
		height: 100%;
		/* 视图高度设置为100% */
		width: 100%;
		/* 视图宽度设置为100% */
		position: fixed;
		/* 视图定位为固定 */
		top: 0;
		left: 0;
		/* z-index: -1; */
	}

	.diy-flex-row {
		display: flex;
		flex-direction: row;
		margin-top: 15rpx;
		margin-bottom: 15rpx;
		font-size: 50rpx;
	}

	.diy-flex-column {
		display: flex;
		flex-direction: column;
	}

	.diy-flex-inforow {
		display: flex;
		flex-direction: row;
		font-size: 40rpx;
		font-weight: 500;
		margin-top: 8rpx;
		margin-bottom: 8rpx;
	}
</style>