<template>
	<view class="bg-image">
		<uni-popup ref="popup" type="dialog">
			<view class="popup-content">
				<view class="info-item">
					<label>单号：</label>
					<text>{{fixedInfo.taskCode}}</text>
				</view>
				<view class="info-item">
					<label>货架：</label>
					<text>{{fixedInfo.shelfCode}}</text>
				</view>
				<view class="info-item">
					<label>起点：</label>
					<text>{{fixedInfo.startLocationCode}}</text>
				</view>
				<view class="info-item">
					<label>终点：</label>
					<text>{{fixedInfo.endLocationCode}}</text>
				</view>
				<view class="info-item">
					<label>任务状态：</label>
					<text>{{fixedInfo.taskStatusStr}}</text>
				</view>

				<view>
					<button style="background-color: bisque;margin-top: 10rpx;"
						@click="saveData">{{fixedInfo.buttonMode}}</button>
				</view>

				<view class="button-group">
					<button @click="hidePopup">关&nbsp;闭</button>
				</view>
			</view>
		</uni-popup>

		<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" @blur="analysisScanCode"></input>
					</view>

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

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

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

				<view style="width: 10rpx;"></view>

				<view style="width: 275rpx;">记录数:[{{recordCount}}]</view>

				<view style="width: 10rpx;"></view>

				<view style="display: flex;flex-direction: row;width: 455rpx;">
					<view>任务状态：</view>
					<view class="picker-container" style="font-size: 30rpx;">
						<picker :range="taskStatusOptions" @change="onTaskStatusChange" range-key="taskStatusName"
							:value="selectedtaskStatusIndex">
							<view class="uni-input" style="padding-left: 5rpx;">
								{{taskStatusOptions[selectedtaskStatusIndex].taskStatusName}}
							</view>
						</picker>
					</view>
				</view>

			</view>
		</view>

		<view class="diy-flex-column" style="margin-top: 5rpx;">
			<scroll-view class="scroll-view" scroll-y="true">
				<view v-for="(item, index) in cardData" :key="index" @touchstart="cardTouchStart"
					@touchmove="cardTouchMove" @longpress="longpress(item)">
					<TaskCard :item="item" :currentIndex="index" :cardData="cardData" />
				</view>
			</scroll-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';

	import TaskCard from '@/components/TaskCard.vue';
	import {
		ref,
		nextTick
	} from 'vue';
	import uniPopup from '@/node_modules/@dcloudio/uni-ui/lib/uni-popup/uni-popup';
	import {
		getCurrentInstance
	} from 'vue';

	export default {
		components: {
			uniPopup,
			TaskCard
		},
		setup() {
			const {
				proxy
			} = getCurrentInstance();
			// 不能修改的信息
			const fixedInfo = {
				taskId: 0,
				taskCode: '',
				shelfCode: '',
				startLocationCode: '',
				endLocationCode: '',
				taskStatusStr: '',
				buttonMode: '无法操作'
			};
			const popup = ref(null);
			const inputValue = ref('');

			const showPopup = (info) => {
				fixedInfo.taskId = info.id;
				fixedInfo.taskCode = info.taskCode;
				fixedInfo.shelfCode = info.shelfCode;
				fixedInfo.startLocationCode = info.startLocationCode;
				fixedInfo.endLocationCode = info.endLocationCode;
				fixedInfo.taskStatusStr = info.taskStatusStr;

				if (info.taskStatusStr == '已创建' || info.taskStatusStr == '正在执行') {
					fixedInfo.buttonMode = '取消任务';
				} else if (info.taskStatusStr == '取消完成') {
					fixedInfo.buttonMode = '重新发送';
				} else {
					fixedInfo.buttonMode = '无法操作';
				}

				popup.value.open();
			};

			const hidePopup = () => {
				popup.value.close();
			};

			const saveData = () => {
				var url = '';
				var serverIPAndPort = getServerIPAndPort();
				if (fixedInfo.taskStatusStr == '已创建' || fixedInfo.taskStatusStr == '正在执行') {
					//取消任务
					url = 'http://' + serverIPAndPort + '/agvTask/cancelAGVTask';
				} else if (fixedInfo.taskStatusStr == '取消完成') {
					//重新发送任务
					url = 'http://' + serverIPAndPort + '/agvTask/resendAGVTask';
				} else {
					return;
				}
				//调用接口进行数量的修改
				uni.request({
					url: url, // 请求的接口地址
					method: 'POST', // 设置请求方式为 POST
					data: {
						"taskId": fixedInfo.taskId,
						"taskCode": fixedInfo.taskCode,
						"userName": getConfig('userName', 'admin'),
						"deviceType": "PDA"
					},
					header: {
						'Content-Type': 'application/json', // 如果需要以JSON格式发送数据
					},
					success: (res) => {
						// 请求成功的回调函数
						if (res.statusCode === 200) {
							//接口返回数据为200 表示获取成功！
							if (res.data.code == 200) {
								hidePopup();
								uni.showToast({
									title: '操作成功!',
									icon: 'none',
									duration: 2000
								});
								proxy.analysisScanCode();

							} 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: '请求失败' + err,
							icon: 'none',
							duration: 2500
						});

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

					}
				});
			};

			return {
				fixedInfo,
				popup,
				inputValue,
				showPopup,
				hidePopup,
				saveData
			};
		},
		data() {
			return {
				locationId: null,
				locationCode: '',

				userName: '', //当前登录的用户名

				recordCount: 0,
				shelfId: null,
				shelfCode: '',
				placeholderText: '',
				matCodeCondition: '', //物料编码搜索条件
				cardData: null,

				//监控滑动的位置
				touchStartX: 0,
				touchStartY: 0,
				isMove: false, //滑动标识 是否滑动

				// 货架区域选项
				taskStatusOptions: [{
					id: null,
					taskStatusName: '全部'
				}],
				selectedtaskStatusIndex: 0, // 
			}
		},
		onShow: function() {
			this.userName = getConfig('userName', 'admin');

			const self = this; // 保存this的引用
			recive(function(res) {
				console.log("Success:" + res.data);
				self.analysisScanCode();
			}, function(err) {
				console.log("Error:", JSON.stringify(err)); // 正确打印错误信息
			});
			self.getTaskStatus();
			
		},
		methods: {
			onTaskStatusChange(e) {
				this.selectedtaskStatusIndex = e.detail.value;
				this.analysisScanCode();
			},
			//摄像头扫码
			cameraScanCode() {
			      uni.scanCode({
			        success: (res) => {
			          console.log('扫码结果:', res.result);
			          this.analysisScanCode(res.result);
			        },
			        fail: (err) => {
			          console.error('扫码失败:', err);
			          // 处理扫码失败的情况
			        }
			      });
			    },
			//扫码枪扫码
			analysisScanCode: function() {
				//获取任务
				var serverIPAndPort = getServerIPAndPort();
				uni.request({
					url: 'http://' + serverIPAndPort +
						'/agvTask/getAGVTasks', // 请求的接口地址
					method: 'POST', // 设置请求方式为 POST
					data: {
						"taskStatus": this.taskStatusOptions[this.selectedtaskStatusIndex].id,
						"userName": this.userName,
						"deviceType": "PDA",
						"pageNumber": 1,
						"pageSize": 100,
					},
					header: {
						'Content-Type': 'application/json', // 如果需要以JSON格式发送数据
					},
					success: (res) => {
						// 请求成功的回调函数
						if (res.statusCode === 200) {
							//接口返回数据为200 表示获取成功！
							if (res.data.code == 200) {
								//未查询到信息
								if (res.data.data == null || res.data.data.count == 0) {
									uni.showToast({
										title: '未查询到状态为['+this.taskStatusOptions[this.selectedtaskStatusIndex].taskStatusName+']的任务信息!',
										icon: 'none',
										duration: 2500
									});
									this.clear();
									return;
								}
								//有物料信息
								this.cardData = res.data.data.lists;
								this.recordCount = res.data.data.count;
				

							} 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);
					}
				});


			},
			
			getTaskStatus: function() {
				//获取任务
				var serverIPAndPort = getServerIPAndPort();
				uni.request({
					url: 'http://' + serverIPAndPort +
						'/agvTask/getAGVTaskStatus', // 请求的接口地址
					method: 'POST', // 设置请求方式为 POST
					data: {
						"userName": this.userName,
						"deviceType": "PDA",
					},
					header: {
						'Content-Type': 'application/json', // 如果需要以JSON格式发送数据
					},
					success: (res) => {
						// 请求成功的回调函数
						if (res.statusCode === 200) {
							//接口返回数据为200 表示获取成功！
							if (res.data.code == 200) {
								//未查询到信息
								if (res.data.data == null || res.data.data.count == 0) {
									return;
								}
								this.taskStatusOptions = res.data.data;
								this.selectedtaskStatusIndex = 2;//默认查询正在执行的任务
								
								this.analysisScanCode();
							} else {
								return;
							}
			
						} else {
							return;
						}
					},
					fail: (err) => {
						// 请求失败的回调函数
						return;
					},
					complete: (event) => {
						// 请求完成的回调函数（无论成功或失败都会调用）
						console.log('请求完成', event);
					}
				});
			
			
			},
			
			
			//清空当前界面所有内容
			clear: function() {
				this.placeholderText = '';
				this.cardData = null;
				this.recordCount = 0;
			},
			//解决长按和滑动冲突的问题
			cardTouchStart(e) {
				this.isMove = false;
				this.touchStartX = e.touches[0].clientX;
				this.touchStartY = e.touches[0].clientY;
			},
			cardTouchMove(e) {
				var deltaX = e.changedTouches[0].clientX - this.touchStartX;
				var deltaY = e.changedTouches[0].clientY - this.touchStartY;
				if (Math.abs(deltaX) > 5 || Math.abs(deltaY) > 5) {
					this.isMove = true;
				}
			},
			//长按
			longpress(item) {
				if (this.isMove == false) {
					this.showPopup(item);
				}
			},
		}
	}
</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;
	}



	.scroll-view {
		height: 81vh;
	}

	.popup-content {
		min-width: 375rpx;
		padding: 20px;
		background-color: rgba(0, 0, 0, 1);
		background-color: white;
		z-index: 2;
		border-radius: 20rpx;
	}


	.input-item {
		margin-bottom: 5rpx;
		display: flex;
		align-items: center;
		/* 让内部元素垂直居中 */
	}

	.input-item label {
		display: inline-block;
	}

	.input-item input {
		display: inline-block;
		background: wheat;
		width: 280rpx;
	}

	.button-group {
		display: flex;
		justify-content: space-between;
		margin-top: 20rpx;
	}

	.button-group button {
		margin-top: 21rpx;
		padding: 10rpx 10rpx;
		border: none;
		border-radius: 5px;
		background-color: #007AFF;
		color: #fff;
		cursor: pointer;
	}

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