<template>
	<view class="bg-image">
		<bindSelectMat 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" 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" @blur="queryMatList"></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;">工位编码：</view>

				<view style="flex: 50;overflow:hidden;">{{locationCode}}</view>

				<view style="flex: 40;">
					<button class="mini-btn" type="warn" size="mini">呼叫货架</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: 50;">
					<input class="uni-input" 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;">
					<button style="margin: 50rpx;font-size: 40rpx;" size="mini">送货架</button>
					<button style="margin: 50rpx;font-size: 40rpx;" size="mini">送货架</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: '',
				matSpec: '',
				matQty: 100, //默认数量值

				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: {
			analysisScanCode: function(encodedString) {
				// 去除末尾的逗号和"..."（如果有的话）
				encodedString = encodedString.replace(/,\s*\.\.\.$/, '');
				// // 分割字符串并转换为字节数组
				// let byteStrings = encodedString.split(',');
				// let byteArray = [];
				// for (let byteString of byteStrings) {
				// 	byteArray.push(parseInt(byteString, 10)); // 将字符串转换为十进制整数
				// }
				// // 将字节数组转换为UTF-8字符串
				// // 注意：这里使用了一个简单的循环来构建字符串，因为String.fromCharCode.apply可能在大数据上性能不佳
				// let originalString = '';
				// for (let i = 0; i < byteArray.length; i++) {
				// 	// 对于每个字节，使用fromCharCode转换为对应的字符
				// 	// 注意：这里假设你的字节数组已经是正确的UTF-8编码，并且不需要额外的处理来组合多字节字符
				// 	originalString += String.fromCharCode(byteArray[i]);
				// }
				this.locationCode = encodedString;
				//调用接口获取当前工位信息 当前工位是否有货架
				var serverIPAndPort = getServerIPAndPort();
				uni.request({
					url: 'http://' + serverIPAndPort + '/pdaMatBind/getShelfInfoByLocationCode', // 请求的接口地址
					method: 'POST', // 设置请求方式为 POST
					data: {
						"locationCode": 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.locationId = res.data.data.locationId;
								this.shelfId = res.data.data.shelfId;
								this.shelfCode = res.data.data.shelfCode;

								if (this.shelfId == null) {
									this.shelfCode = '(工位无货架，请呼叫！)';
									this.isNeedScanLocationCode = false;
									this.isNeedCallShelfCode = true;
									this.placeholderText = '请呼叫货架';
								} 
								else 
								{
									this.isNeedScanLocationCode = false;
									this.isNeedCallShelfCode = false;
									this.placeholderText = '输入编码或名称';
								}

								uni.showToast({
									title: '获取成功!',
									icon: 'none',
									duration: 1500
								});

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

						} else {
							uni.showToast({
								title: '服务器返回错误状态码' + res.statusCode,
								icon: 'none',
								duration: 3000
							});
							this.clear();
						}
					},
					fail: (err) => {
						// 请求失败的回调函数
						uni.showToast({
							title: '请求失败' + err,
							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.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,
						"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,
							icon: 'none',
							duration: 1500
						});
					},
					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
					});
					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();
				}
			},

			//清空当前界面所有内容
			clear: function() {
				this.locationId = null;
				this.locationCode = '';
				this.shelfId = null;
				this.shelfCode = '';
				this.isNeedCallShelfCode = true;
				this.isNeedScanLocationCode = true;
				this.placeholderText = '请先扫描工位码';
			},
			clearMatInfo: function() {
				this.matCode = '';
				this.matName = '';
				this.matSpec = '';
			},
			handlePopupClose() {
				// 弹出层关闭后的处理逻辑
				console.log('弹出层已关闭');
			},
		}
	}
</script>

<style>
	.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>