<template>
	<view class="container" style="width: 100%;">

		<view class="top-section">
			<u-toast ref="uToast"></u-toast>
			<uni-easyinput v-model="clothValue" placeholder="扫描成衣条码" @confirm="scanCloth" :focus="isFocus"
				@blur="isFocus = false"></uni-easyinput>
		</view>
		<scroll-view class="scroll-view" scroll-y="true" show-scrollbar="true" @scroll="scroll"
			:scroll-into-view="scrollIndex">
			<!-- <view class="m-content"> -->
			<uni-swipe-action ref="swipeAction">
				<uni-swipe-action-item :ref="'swipeItem'+index" :id="'scroll'+index" v-for="(item, index) in clist"
					:key="item.FUniqueCode" :right-options="options" @click="click($event,index)">
					<view class="swipe-action u-border-top u-border-bottom">
						<view class="swipe-action__content">
							<text class="item-text"
								:style="boxData.BillType === 'AJHZX' && item.scan > item.FQty || item.isNew ||item.isErr?'color:red' : ''">
								计划跟踪号：{{item.FMoto}}
								尺码:{{item.FSize}},
								<span v-if="(boxData.BillType === 'AJHZX')">
								        数量:{{item.FQty}},
								    </span>已扫描{{item.scan}}</text>
						</view>
					</view>
				</uni-swipe-action-item>
			</uni-swipe-action>
			<u-divider textColor="#2979ff" lineColor="#61a0ff" text="没有更多了"></u-divider>
			<!-- </view> -->

		</scroll-view>


		<view class="bottom-section">
			<uni-popup ref="inputDialog" type="dialog">
				<uni-popup-dialog ref="inputClose" mode="input" title="输入修改数量" v-model="updateVal"
					@confirm="dialogInputConfirm"></uni-popup-dialog>
			</uni-popup>
			<button @click="back" class="cu-btn bg-blue lg shadow" style="font-size: 60rpx;">上一步</button>
			<button @click="toCreat" :disabled="isClicked" ref="cButton" class="cu-btn bg-blue lg shadow"
				style="font-size: 60rpx;">生成</button>
		</view>



	</view>
</template>

<script>
	import {
		GetClothesEnchaseByBarCode,
		GenerateClothesEnchase,
		GenerateClothesEnchaseCheck
	} from "../../api/enchase";

	export default {
		data() {
			return {
				isFocus: true,
				scrollTop: 0,
				old: {
					scrollTop: 0
				},
				scrollIndex: '',
				keyboardHideTimer: null,
				isScl: true,
				isPlan:true,
				isClicked: false,
				clist: [],
				clothValue: '',
				updateVal: '',
				currentIndex: '',
				bgColor: '',
				boxData: {
					IsExistCheck: true,
					PrdOrgId: '',
					BillType: '',
					EnchaseId: '',
					WorkShop: '',
					OrderNo: '',
					BoxNo: '',
					MatchNo: '',
					EnchaseTypeId: '',
					EnchaseType: '',
					Note: '',
					CustomId: '',
					CreatorNumber: '',
					FEntity: []
				},
				audioContext: null, // 存储音频上下文实例
				allSuccessUrl: "../../static/y1809.mp3",

				options: [{
						text: '编辑',
						style: {
							backgroundColor: '#007aff'
						}
					},
					{
						text: '删除',
						style: {
							backgroundColor: '#dd524d'
						}
					}
				]
			};
		},

		//获取上一页传过来的参数
		onLoad(option) {
			let box_invType = uni.getStorageSync('box_invType')
			const Info = JSON.parse(decodeURIComponent(option.Info))
			if ("ZXRGJC" == box_invType) {
				console.log("手工检查----")
				this.boxData.BillType = Info.BillType;
				this.boxData.CreatorNumber = uni.getStorageSync('username')
				this.boxData.PrdOrgId = uni.getStorageSync('box_org')
				this.boxData.BoxNo = Info.EnchaseId
				this.boxData.WorkShop = uni.getStorageSync('box_workshopCode');
				this.boxData.EnchaseType = uni.getStorageSync('box_packType');
				this.boxData.EnchaseTypeId = uni.getStorageSync('box_packTypeId');
				uni.setStorageSync("plist", [])
				// console.log(this.boxData)
			} else {
				console.log("按计划装箱校验----")
				this.boxData.CreatorNumber = uni.getStorageSync('username')
				this.boxData.PrdOrgId = Info.PrdOrgId
				this.boxData.EnchaseId = Info.EnchaseId
				this.boxData.WorkShop = Info.WorkShopId
				this.boxData.OrderNo = Info.OrderNo
				this.boxData.CustomId = Info.FCustId
				this.boxData.FPlanQty = Info.FPlanQty
				this.boxData.BoxNo = Info.BoxNo
				this.boxData.MatchNo = Info.MatchNo
				this.boxData.EnchaseTypeId = Info.EnchaseTypeId
				this.boxData.EnchaseType = Info.EnchaseType
				this.boxData.Note = Info.Note

				this.boxData.BillType = Info.BillType;
				let plist = Info.FEntity.map(item => {
					return {
						FMoto: item.FMoto,
						FSize: item.FSize,
						FQty: item.FQty,
						scan: 0,
						isNew: false,
						isErr: false,
						show: 'none',
						FUniqueCode: item.FUniqueStr || '',
						FMaterialNum: item.FMaterialNum || '',
						FFabricPatternNo: item.FColorNo || '',
					}
				})
				uni.setStorageSync("plist", plist)

				this.clist = plist
				this.boxData.FEntity = plist
				console.log(this.boxData.FEntity)
			}




			//定时器隐藏软键盘
			// this.startKeyboardHideTimer();
		},
		// onReady() {
		// 	let Info = uni.getStorageSync("Info")
		// 	console.log(Info)
		// 	//判断装箱方式
		// 	if ("ZXRGJC" == Info.BillType) {

		// 	} else {

		// 	}
		// },
		computed: {
			shouldWatchData() {
				// 计算属性，决定是否应该监听clist的变化
				return this.boxData.BillType === 'AJHZX';
			},
		},

		methods: {

			click(e, index) {
				console.log("eeeeeeee" + index)
				if ("编辑" == e.content.text) {
					this.update(index)

					return
				}
				if ("删除" == e.content.text) {
					this.del(index)
				}

			},
			open(index) {
				// 先将正在被操作的swipeAction标记为打开状态，否则由于props的特性限制，
				// 原本为'false'，再次设置为'false'会无效
				this.list[index].show = true;
				this.list.map((val, idx) => {
					if (index != idx) this.list[idx].show = false;
				})
			},
			focusPoint() {
				console.log("执行了")
				this.clothValue = ""
				this.isFocus = false;
				this.$nextTick(() => {
					this.clothValue = ""
					this.isFocus = true;
					// console.log("执行了2")
				});
			},
			//定位错误行
			findAndScrollToItem(index) {
				if (index > -1) {
					this.scrollIndex = ''
					setTimeout(() => {
						this.$nextTick(() => {
							this.scrollIndex = 'scroll' + index
						})
					}, 300);
				}
			},
			scroll: function(e) {
				console.log(e)
				this.old.scrollTop = e.detail.scrollTop
			},


			// onInputTap() {
			// 	// 清除定时器，允许键盘正常弹出
			// 	this.clearKeyboardInterval()
			// 	// 手动聚焦输入框
			// 	this.$refs.myInput.focus();

			// },
			// startKeyboardHideTimer() {
			// 	// 设置定时器尝试隐藏软键盘
			// 	this.keyboardHideTimer = setInterval(() => {
			// 		uni.hideKeyboard();
			// 	}, 50);
			// },
			// clearKeyboardInterval() {
			// 	// 页面销毁前清除定时器，防止内存泄漏
			// 	clearInterval(this.keyboardHideTimer);
			// 	this.keyboardHideTimer = null;
			// },
			//扫描成衣
			async scanCloth() {

				let that = this
				let data = '';


				console.log(this.clothValue);
				if (this.clothValue == "") {
					// this.playvoice()
					uni.showToast({
						title: '请扫描成衣条码',
						icon: 'none',
						duration: 3000
					})
					this.focusPoint()
					return
				}
				// if(!that.clothValue){
				// 	this.$modal.msgError("成衣扫描失败");
				// 	return
				// }
				
				this.checkCloth();
			
				try {
					let res = []
					if(this.isPlan){
						res = await GetClothesEnchaseByBarCode(this.clothValue,this.boxData.OrderNo)
					}else{
						res = await GetClothesEnchaseByBarCode(this.clothValue)
					}
					
					console.log(res);
					if (res && res[0]) {
						data = res[0]
					}
				} catch (e) {
					this.showToastError('请检查网络连接');
					console.error('GetClothesEnchaseByQRCode', e);
				}
				if (!data) {
					this.showToastError("成衣明细读取异常！");
					return
				}
				console.log(data);
				this.updateClist(data);




			},
			//手工单个检查
			checkOne(data) {
				if (this.clist.length < 1) {
					return true
				}
				let one = this.clist[0]
				if (this.boxData.EnchaseType.includes("独款")) {
					if (data.FMaterialNum != one.FMaterialNum) {
						console.log("检查装箱方式---one---》独款false")
						return false
					}
				}
				if (this.boxData.EnchaseType.includes("独色")) {
					if (data.FMoto != one.FMoto || data.FFabricPatternNo != one.FFabricPatternNo) {
						console.log("检查装箱方式---one---》独色false")
						return false
					}
				}
				if (this.boxData.EnchaseType.includes("独码")) {
					if (data.FSize != one.FSize) {
						console.log("检查装箱方式---one---》独码false")
						return false
					}
				}
				return true

			},
			//手工检查装箱方式
			checkAll() {
				if (this.clist.length < 2) {
					return true
				}
				let one = this.clist[0]
				console.log("检查装箱方式---one---》" + one.FUniqueCode)
				if (this.boxData.EnchaseType.includes("独款")) {
					if (!this.clist.every(item => item.FMaterialNum === one.FMaterialNum)) {
						// this.boxData.IsExistCheck = false;
						console.log("检查装箱方式---one---》独款false")
						return false
					}

				}
				if (this.boxData.EnchaseType.includes("独色")) {
					if (!this.clist.every(item => item.FMoto === one.FMoto) || !this.clist.every(item => item
							.FFabricPatternNo === one.FFabricPatternNo)) {
						// this.boxData.IsExistCheck = false;
						console.log("检查装箱方式---one---》独色false")
						return false
					}
				}
				if (this.boxData.EnchaseType.includes("独码")) {
					if (!this.clist.every(item => item.FSize === one.FSize)) {
						// this.boxData.IsExistCheck = false;
						console.log("检查装箱方式---one---》独码false")
						return false
					}
				}
				return true
			},
			//第一步检查
			checkCloth() {
				//判断是否是扫描列表中的成衣
				this.isScl = this.clist.find(item => item.FUniqueCode == this.clothValue)
				// //判断是否是计划中的成衣
				let plist = uni.getStorageSync("plist")				
				this.isPlan = plist.find(item => item.FUniqueCode == this.clothValue)
			},
			//第二步更新列表
			updateClist(data) {
				let vm = this
				if ("AJHZX" == this.boxData.BillType) {
					if (this.isScl) {
						for (let i = 0; i < this.clist.length; i++) {
							console.log(this.clist[i])
							let FUniqueCode = this.clist[i].FUniqueCode;
							let fqty = this.clist[i].FQty || 0;
							if (FUniqueCode == data.FUniqueCode) {
								if (!this.clist[i].scan) {
									this.clist[i].scan = 0
								}

								this.$set(this.clist[i], "scan", this.clist[i].scan + 1)
								this.$set(this.clist[i], "FUniqueCode", data.FUniqueCode)
								this.$set(this.clist[i], "FMaterialNum", data.FMaterialNum)
								this.$set(this.clist[i], "FFabricPatternNo", data.FFabricPatternNo)
								this.$set(this.clist[i], "FSize", data.FSize)

								if (this.clist[i].scan > fqty) {
									this.scanError(i, '请检查扫描数量！')
									//定位错误行

									break;
								} else {
									this.scanSuccess()
									break;
								}

							}
						}
					} else {
						//新增一行
						let size = this.clist.length;
						console.log(size + "新增一条")
						this.clist[size] = data
						this.clist[size].scan = 1
						this.clist[size].isNew = true;

						this.scanError(size, "不在计划中！")
					}

				} else {
					if (this.isScl) {
						for (let i in this.clist) {
							console.log(this.clist[i].FUniqueCode)
							let FUniqueCode = this.clist[i].FUniqueCode;
							let fqty = this.clist[i].FQty || 0;
							if (FUniqueCode == data.FUniqueCode) {
								this.clist[i].scan += 1;
								if (i === 0 && this.clist[i].scan === 1) {
									this.scanSuccess()
									break;
								} else {
									if (!this.checkAll()) {
										this.scanError(i, "请检查装箱方式！")
										break;
									}
									this.scanSuccess()
								}

							}

						}
					} else {
						let size = this.clist.length;
						console.log(size + "新增一条")
						this.clist[size] = data
						this.clist[size].scan = 1
						if (!this.checkOne(data)) {
							this.clist[size].isErr = true
							this.scanError(size, "请检查装箱方式！")
						} else {
							if (!this.checkAll()) {
								this.scanError(size, "请检查装箱方式！")

							} else {
								this.scanSuccess()
							}

						}
					}

				}


			},
			scanSuccess() {
				this.showToastSuccess('扫描成功！')
				this.playvoiceGood()
				this.$forceUpdate();
				this.focusPoint();
			},
			scanError(index, message) {
				this.showToastError(message)
				this.playvoiceError()
				this.$forceUpdate();
				//定位错误行
				console.log(index);
				this.findAndScrollToItem(index)

			},
			async toCreat() {
				if (this.isClicked) return;
				this.isClicked = true;
				uni.showLoading({
					title: '正在生成...',
				});

				try {
					if (!this.clist || this.clist.length == 0) {
						this.showToastError("扫描列表为空")
						return
					}

					if ("ZXRGJC" == this.boxData.BillType) {
						if (!this.checkAll()) {
							this.showToastError("装箱方式不合规")
							this.playvoiceError()
							return
						} else {

							//封装装箱数据
							let scanSum = 0
							for (let i = 0; i < this.clist.length; i++) {
								console.log(this.clist[i].FUniqueCode)
								scanSum = scanSum + this.clist[i].scan || 0;
							}
							this.boxData.ScanQty = scanSum
							this.boxData.FEntity = this.clist

							this.boxData.OrderNo = this.clist[0].FOrderNo
							this.boxData.CustomId = this.clist[0].FCustId
							//生成装箱
							let param = this.transParam(this.boxData);
							console.log(param)
							await this.generateClothesEnchase(param);
						}

					} else {
						//封装装箱数据
						let scanSum = 0
						for (let i = 0; i < this.clist.length; i++) {
							console.log(this.clist[i].FUniqueCode)
							scanSum = scanSum + this.clist[i].scan || 0;
						}
						this.boxData.ScanQty = scanSum
						this.boxData.FEntity = this.clist

						//计划装箱校验
						let param = this.transParam(this.boxData);
						console.log(param)
						let check = await this.generateClothesEnchaseCheck(param)

						if (check.Flag) {
							//生成装箱
							await this.generateClothesEnchase(param);
						} else {
							console.log(check.Flag)
							console.log(check.IsInteractive)
							console.log(check.Message)
							let vm = this
							//根据提示是否弹窗提醒
							if (check.IsInteractive) {
								await uni.showModal({
									title: '提示',
									content: check.Message,
									success: function(res) {
										if (res.confirm) {
											console.log('用户点击确定');
											vm.generateClothesEnchase(param);
										} else if (res.cancel) {
											console.log('用户点击取消');
											return
										}
									}
								});
							} else {
								this.showToastError(check.Message)
								this.playvoiceError()
								return
							}
						}

					}

				} catch (e) {
					console.log(e);
				} finally {
					this.isClicked = false;
					// this.$refs.cButton.disabled = false;
					uni.hideLoading()
					console.log('处理完成');
				}


			},
			transParam(data) {
				let Entity = data.FEntity.map(item => {
					return {
						UniqueNoId: item.FUniqueCode,
						ScanQty: item.scan
					}
				})
				let param = {
					"IsExistCheck": data.IsExistCheck,
					"PrdOrgId": data.PrdOrgId,
					"BillType": data.BillType,
					"EnchaseId": data.EnchaseId,
					"WorkShop": data.WorkShop,
					"OrderNo": data.OrderNo,
					"BoxNo": data.BoxNo,
					"MatchNo": data.MatchNo,
					"EnchaseTypeId": data.EnchaseTypeId,
					"EnchaseType": data.EnchaseType,
					"Note": data.Note,
					"CustomId": data.CustomId,
					"CreatorNumber": data.CreatorNumber,
					"FEntity": Entity
				}

				return param
			},
			back() {
				let vm = this
				//检查扫描数据
				if (this.clist.length != 0) {
					uni.showModal({
						title: '提示',
						content: '已经有扫描数据，是否放弃扫描结果？',
						cancelText: '否',
						confirmText: '是',
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击确定');
								// vm.clearKeyboardInterval()
								uni.reLaunch({
									url: "/pages/index/scan-box"
								})
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				} else {
					// vm.clearKeyboardInterval()
					uni.reLaunch({
						url: "/pages/index/scan-box"
					})
				}

			},
			update(index) {

				// this.clearKeyboardInterval()
				let val = this.clist[index].scan || 0
				this.updateVal = val;
				this.currentIndex = index;
				this.$refs.inputDialog.open()

			},
			dialogInputConfirm(val) {

				if (isNaN(val)) {
					this.showToastError('请输入正确的数量！');

				} else {
					this.clist[this.currentIndex].scan = parseInt(val);
				}

				if ("AJHZX" == this.boxData.BillType) {
					if (parseInt(val) > this.clist[this.currentIndex].FQty) {
						this.clist[this.currentIndex].setRed = true;
					} else {
						this.clist[this.currentIndex].setRed = false;
					}

				}
				// 关闭窗口
				this.$refs.inputDialog.close()
				this.$forceUpdate();
				this.$refs.swipeAction.closeAll()
			},
			del(index) {
				console.log(index)
				if (this.clist[index].FQty > 0) {
					this.$refs.uToast.show({
						message: '不可以删除计划内的成衣！',
						type: 'warning',
						icon: true
					})
					return
				}

				this.clist.splice(index, 1)
				let isPlay = false;
				if (index === 0 && "ZXRGJC" == this.boxData.BillType) {

					for (let i in this.clist) {
						let data = this.clist[i]
						if (!this.checkOne(data)) {
							this.clist[i].isErr = true
							isPlay = true;

						} else {
							this.clist[i].isErr = false
						}
					}
					if (isPlay) {
						this.showToastError("删除成功！请检查装箱方式！")
						this.playvoiceError()
						return
					}

				}
				this.$refs.uToast.show({
					message: '删除成功',
					type: 'success',
					icon: true,
					position: 'top'
				})
				this.playvoiceGood()
				this.$forceUpdate();
			},

			playvoiceGood() {
				console.log('good-----shengyin', this.audioContext)
				if (this.audioContext) {
					try {
						this.audioContext.pause();
						this.audioContext.destroy()
						this.audioContext = null
					} catch (e) {
						//TODO handle the exception
					}
					this.audioContext = uni.createInnerAudioContext();
					this.audioContext.autoplay = true;
					this.audioContext.src = '../../static/success.mp3';
					this.audioContext.onPlay(() => {
						console.log('开始播放');
					});
				} else {
					// 如果音频上下文实例不存在，则创建新的实例并播放
					this.audioContext = uni.createInnerAudioContext();
					this.audioContext.autoplay = true;
					this.audioContext.src = '../../static/success.mp3';
					this.audioContext.onPlay(() => {
						console.log('开始播放');
					});
				}

			},
			playvoiceError() {
				console.log('error-----shengyin', this.audioContext)
				if (this.audioContext) {
					try {
						this.audioContext.pause();
						this.audioContext.destroy()
						this.audioContext = null
					} catch (e) {
						//TODO handle the exception
					}
					this.audioContext = uni.createInnerAudioContext();
					this.audioContext.autoplay = true;
					this.audioContext.src = '../../static/error.mp3';
					this.audioContext.onPlay(() => {
						console.log('开始播放');
					});
				} else {
					// 如果音频上下文实例不存在，则创建新的实例并播放
					this.audioContext = uni.createInnerAudioContext();
					this.audioContext.autoplay = true;
					this.audioContext.src = '../../static/error.mp3';
					this.audioContext.onPlay(() => {
						console.log('开始播放');
					});
				}
			},
			showToastSuccess(message) {
				this.$refs.uToast.show({
					message: message,
					type: 'success',
					icon: true,
					position: 'top'
				});
			},
			showToastError(message) {
				this.$refs.uToast.show({
					message: message,
					type: 'error',
					icon: true,
					position: 'top'
				});
			},
			async generateClothesEnchaseCheck(param) {
				return await GenerateClothesEnchaseCheck(JSON.stringify(param))
			},
			async generateClothesEnchase(param) {
				try {
					const res = await GenerateClothesEnchase(JSON.stringify(param))
					if (res) {
						if (res.Flag) {
							uni.reLaunch({
								url: "/pages/index/scan-box"
							})
							this.showToastSuccess("生成装箱成功！")
							this.playvoiceGood()
						} else {

							uni.showModal({
								title: '提示',
								content: res.Message,
								showCancel: false,
								success: function(res) {
									if (res.confirm) {
										console.log('用户点击确定');
										return
									} else if (res.cancel) {
										console.log('用户点击取消');
										return
									}
								}
							})
							this.playvoiceError()
						}

					} else {
						console.error('装箱接口连接失败')
						uni.showModal({
							title: '提示',
							content: '接口连接失败',
							showCancel: false,
							success: function(res) {
								if (res.confirm) {
									console.log('用户点击确定');
									return
								} else if (res.cancel) {
									console.log('用户点击取消');
									return
								}
							}
						});
						this.playvoiceError()
					}

				} catch (error) {
					console.error('GenerateClothesEnchase', error);
					uni.showModal({
						title: '生成装箱错误',
						content: error.errMsg,
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击确定');
								return
							} else if (res.cancel) {
								console.log('用户点击取消');
								return
							}
						}
					});
					this.playvoiceError()



				}


			}
		},
	}
</script>

<style lang="scss" scoped>
	.container {
		display: flex;
		flex-direction: column;
		height: 100%; // 填满整个视口高度
		// overflow-y: hidden;

		.top-section {
			flex: 1;
			flex-shrink: 0; // 确保 input 总是在顶部
			padding: 20rpx 20rpx 1rpx; // 添加适当的内边距
		}


		.scroll-view {
			flex: 5;
			overflow-y: auto;
			height: 500rpx;
			padding: 1rpx 20rpx 10rpx;
			// .m-content {
			// 	/* 示例高度，可以根据实际内容调整 */


			.item-text {
				font-size: 15px;
			}

			// }

		}


		.bottom-section {
			flex: 1;
			flex-shrink: 0; // 确保按钮总是在底部
			display: flex;
			justify-content: space-evenly; // 按钮之间均匀分布
			padding: 20rpx; // 添加适当的内边距
		}
	}
</style>