<!-- 非采购上架入库 -->
<template>
	<view class="shpage">
		<!-- 标题栏 -->
		<view class="mianheade mianheade2" @click="goback()">
			<image src="../../static/img/n_baiback.png" class="blacBackico"></image>
			<text class="pagetitle">非采购上架入库</text>
		</view>
		<!-- 固定内容-->
		<view class="sh_gdInfo">
			<view class="item" :class="{ itembg2: fid }" :style="{ 'pointer-events': fid ? 'none' : '' }">
				<view class="it">
					<text class="t1">
						<text class="redtag">*</text>
						仓库:
					</text>
					<w-select
						class="wwselectit"
						v-model.trim="warehouseName"
						defaultValue="请选择"
						:list="warehouseList"
						valueName="name"
						keyName="name"
						@change="ckchange"
						@focus="inputfocus($event, 'ck')"
						ref="wselectck"
					></w-select>
				</view>
			</view>
			<view class="item" :class="{ itembg2: !warehouseCode || boxstrList.length > 0 }" :style="{ 'pointer-events': !warehouseCode || boxstrList.length > 0 ? 'none' : '' }">
				<view class="it itsp">
					<text class="t1">
						<text class="redtag">*</text>
						来源单号:
					</text>
					<w-select
						class="wwselectit"
						v-model.trim="lyOrderVal"
						defaultValue="请输入订单号搜索"
						:list="lyOrderSelectList"
						valueName="sourceBillNo"
						keyName="sourceBillNo"
						@change="lyorderChange"
						:filterable="filterable"
						optionType="order-fcg"
						@onBottomPage="onBottomPage"
						@focus="inputfocus($event, 'lyorder')"
						:pagingSet="false"
						:showClose="true"
						ref="wselectlyorder"
					></w-select>
					<image src="../../static/img/smico.png" class="searchico" @click="scanImg('lyorder')"></image>
				</view>
			</view>
			<view
				class="item"
				:class="{ itembg2: !fid || !warehouseCode || boxstrList.length > 0 }"
				:style="{ 'pointer-events': !fid || !warehouseCode || boxstrList.length > 0 ? 'none' : '' }"
			>
				<view class="it itsp">
					<text class="t1">
						<text class="redtag">*</text>
						仓位号:
					</text>
					<w-select
						class="wwselectit"
						v-model.trim="cwNum"
						defaultValue="模糊搜索"
						:list="cwselectList"
						:focus="focusInput == 'cw'"
						@focus="inputfocus($event, 'cw')"
						valueName="name"
						keyName="name"
						@change="cwchange"
						:filterable="filterable"
						:showClose="true"
						ref="wselect1"
						@clearnFn="clearnFn"
					></w-select>
					<image src="../../static/img/smico.png" class="searchico" @click="scanImg('cw')"></image>
				</view>
			</view>
			<view
				class="item"
				:class="{ itembg2: !fid || !warehouseCode || boxstrList.length > 0 }"
				:style="{ 'pointer-events': !fid || !warehouseCode || boxstrList.length > 0 ? 'none' : '' }"
			>
				<view class="it itsp">
					<text class="t1">
						<text class="redtag">*</text>
						上架方式:
					</text>
					<w-select
						class="wwselectit"
						v-model.trim="sjfsType"
						defaultValue="请选择"
						:list="sjfslist"
						valueName="name"
						keyName="name"
						@change="sjfsChange"
						ref="wselectsjfs"
					></w-select>
				</view>
			</view>
			<view
				class="item"
				:class="{ itembg2: !subStockCode || !warehouseCode || !fid || xlhstrList.length > 0 || !sjfsType }"
				:style="{ 'pointer-events': !subStockCode || !warehouseCode || !fid || xlhstrList.length > 0 || !sjfsType ? 'none' : '' }"
			>
				<view class="it itsp">
					<text class="t1">
						<text class="redtag">*</text>
						箱号:
					</text>
					<input
						v-model.trim="xhNo"
						class="inpt1"
						type="text"
						@focus="inputfocus($event, 'box')"
						@blur="inputblur($event, '')"
						@confirm="inputConfirm($event, 'box')"
						:focus="focusInput == 'box'"
					/>
					<image src="../../static/img/smico.png" class="searchico" @click="scanImg('box')"></image>
				</view>
			</view>
			<view class="item" v-if="sjfsType == '按箱上架' && subStockCode">
				<view class="it">
					<text class="t1">
						<text class="redtag">*</text>
						上架数量:
					</text>
					<text class="t1 tpleft">{{ sjNum }}</text>
				</view>
			</view>
			<view class="item" v-if="sjfsType == '按产品上架'" :class="{ itembg2: !xhNo }" :style="{ 'pointer-events': !xhNo ? 'none' : '' }">
				<view class="it itsp">
					<text class="t1">序列号:</text>
					<input
						v-model.trim="xlhVal"
						class="inpt1"
						type="text"
						@focus="inputfocus($event, 'xlh')"
						@blur="inputblur($event, '')"
						@confirm="inputConfirm($event, 'xlh')"
						:focus="focusInput == 'xlh'"
					/>
					<image src="../../static/img/smico.png" class="searchico" @click="scanImg('xlh')"></image>
				</view>
			</view>
		</view>
		<!-- 列表内容-->
		<view class="shlb cgsjrklb f_cgsjrklb" :style="{ 'margin-top': heights.top + 'px', height: heights.body + 'px' }">
			<view class="item" v-for="(item, index) in dataList" :key="index">
				<view class="it" style="border: none">
					<text class="txt titstr" style="padding-bottom: 4px; border-bottom: 1px dashed #d2d2d2">{{ item.specifications }}</text>
					<view class="cssj_it" style="background: #fff">
						<view class="tlinb">
							<view class="txt txtflexnum">
								<view class="pl">
									<text style="max-width: 50%">{{ item.materialNumber }}</text>
									<view style="background: #eef1f5;display:flex;flex-deraction:row">
										{{ item.materialSubStocks && item.materialSubStocks.length > 0 ? '(' : '' }}
										<view @click="cwtkfn(item.materialSubStocks)" class="cwhitzs" >
										{{ item.materialSubStocks && item.materialSubStocks.length > 0 ? item.materialSubStocks.join(',') : '' }}
										</view>
										{{ item.materialSubStocks && item.materialSubStocks.length > 0 ? ')' : '' }}
									</view>
								</view>
							</view>
							<view class="txt txtflexnum" v-if="sjfsType == '按箱上架' || sjfsType == ''">
								<text class="txtNum">{{ item.availableQty }}</text>
								<text class="txtNum" v-if="sjfsType == '按箱上架'">{{ item.qty }}</text>
							</view>
						</view>
						<view class="txtNum" v-if="sjfsType == '按产品上架'">
							<view>
								<text>{{ item.availableQty }}</text>
							</view>
							<view class="tinput">
								<text>上架数量</text>
								<u-input
									v-model="item.qty"
									border="surround"
									clearable
									class="inpt"
									:class="{ inptbordred: item.qty > item.availableQty }"
									type="number"
									:disabled="boxstrList.length == 0 || (item.xlhList && item.xlhList.length > 0)"
									@input="itSJnumConfirm($event, index)"
								></u-input>
							</view>
						</view>
					</view>
				</view>
			</view>
			<zero-loading v-if="listloading" type="circle" style="top: 60%"></zero-loading>
		</view>
		<!-- 底部按钮固定-->
		<view class="footbts">
			<view class="bt bt1" @click="qktkshow = true">清空上架数量</view>
			<view class="bt bt2" @click="wcNxetFn">完成/下一单</view>
		</view>
		<!--清空二次确认弹框-->
		<u-modal :show="qktkshow" :title="qktkTitle" :content="qktkContent" @confirm="qktkconfirm" :showCancelButton="true" @cancel="qktkshow = false"></u-modal>
		<!-- 仓位弹框-->
		<u-modal :show="cwtkshow" title="可入仓位" @confirm="cwtkshow = false">
			<view class="boxtkct">
				<view v-for="(item, index) in materialSubStocks" class="c_item">{{ item }}</view>
			</view>
		</u-modal>
	</view>
</template>

<script>
export default {
	data() {
		return {
			cwtkshow: false, // 仓位弹框
			materialSubStocks: [], //仓位弹框显示内容
			heights: {
				top: 0,
				body: 0
			},
			krkStrVal: '', //物料可入库仓位号文本显示
			listloading: false,
			focusInput: 'ck', //自动聚焦
			warehouseName: '', //仓库名称
			warehouseCode: '', //仓库编码
			warehouseList: [], // 仓库下拉数据
			cwNum: '', // 仓位号
			cwselectList: [], // 仓位下拉数据
			subStockCode: '', // 仓位code
			sjNum: '', // 上架数量
			sjfsType: '', // 上架方式
			lyOrderVal: '', // 来源单号
			lyOrderSelectList: [], //来源单号下拉选择单据
			xhNo: '', //箱号
			boxId: '', // 箱号id
			boxstrList: [], // 缓存的箱号信息（多个）
			dataList: [], // 页面列表明细数据
			qktkshow: false, //清空二次确认弹框
			qktkTitle: '确定清空已收货数量?',
			qktkContent: '清空后页面数据将不保存',
			focusTag: '', //  判斷聚焦
			xlhVal: '', // 序列号的输入值
			xlhstrList: [], // 序列号的箱号信息（多个）
			filterable: true,
			sjfslist: [],
			sjfskey: '', // 上架方式key值
			boxs: [],
			fid: null, // 来源订单号id
			orgCode: '', // 组织cdoe
			timer: null,
			dqboxNO: '', //用来是否保存当前输入箱号的值
			dqboxXlh: '', //用来是否保存当前输入xlh的值
			APPdevice: uni.getStorageSync('devicePixelRatio'), // 缓存设备的像素比用来区分普通安卓normalAnroid还是pda
			requestStatus: false, // 请求状态识别变量
			lymaterialNumber:'',// 选中来源单的编码
			twoData:[],//用于判断是否已扫码
			scanTracker: {
				lastScanTime: 0,
				lastScanCode: null
			} // 源头处理扫码段时间内重复扫
		};
	},
	watch: {
		boxNo(n) {
			if (!n) {
				this.dqboxNO = '';
			}
		},
		xlhVal(n) {
			if (!n) {
				this.dqboxXlh = '';
			}
		},
		// 仓位下拉数据
		cwNum(n, o) {
			if (!n) {
				this.cwselectList = [];
				this.subStockCode = null;
				this.$refs.wselect1.inputData = '';
			} 
			if(n) {
				this.subStockCode = null
				this.getcwList(n);
			}

		},
		cwselectList(n,o) {
			console.log(n,'监听到了吗')
			if(n.length && this.cwNum) {
				this.cwselectList.forEach((item)=>{
					if(item.name === this.cwNum) {
						// this.$refs.wselect1.optionsShow = false;
						// this.$refs.wselect1.isShow = false;
						this.subStockCode = item.code
						if(this.subStockCode) {
								this.$refs.wselect1.optionsShow = false;
								this.$refs.wselect1.isShow = false;
						}
						// setTimeout(()=>{
						// 	this.$refs.wselect1.optionsShow = false;
						// 	this.$refs.wselect1.isShow = false;
						// },500)
						
					}
				})
			}
		},
		// 来源订单号实时输入监听
		lyOrderVal(n, o) {
			if (!n) {
				this.qktkconfirm();
				this.dataList = [];
				this.lyOrderSelectList = [];
				this.fid = '';
				this.cwNum = '';
				this.subStockCode = '';
				this.sjfsType = '';
				this.$refs.wselectsjfs.inputData = '';
				this.$refs.wselect1.inputData = '';
			} else {
				this.getlyOrderInfolist(n);
			}
		}
	},
	mounted() {
		this.heights = this.$util.setlistHeight('.sh_gdInfo', '.footbts');
		console.log('最终列表高度非采购', this.heights);
	},
	onLoad() {
		this.sjfslist = this.$util.setObjectArry(uni.getStorageSync('allTypelist').shelfMethod);
		this.sjfskey = this.sjfslist[0].id;
		// 按箱子上架   箱号对应来源单号的箱号，且可以扫描多个  箱号存在值之后,仓位就不能修改
		// 按产品上架   箱号只取最后的箱，仓位可以一直修改
		///获取广播扫码监听
		this.$broadcastScan.init(this.getScancode);
		this.$broadcastScan.start();
		this.stopScanCode();
		this.startScanCode();
		this.getcklist();
	},
	onHide() {
		this.$broadcastScan.stop();
		this.stopScanCode();
	},
	onShow() {
		this.$broadcastScan.start();
		this.startScanCode();
	},
	onBackPress(e) {
		this.$util.appgoBack(e, 'warehousIndex');
		return true;
	},
	methods: {
		// 开启广播
		startScanCode() {
			uni.$on('xwscan', (res) => {
				const now = Date.now();
				const timeSinceLastScan = now - this.scanTracker.lastScanTime;
				// 如果扫描的箱码和上次相同，并且时间间隔小于500ms，则不作处理
				if (res.code === this.scanTracker.lastScanCode && timeSinceLastScan < 4000) {
					return;
				} else {
					// 更新扫描跟踪信息
					this.scanTracker.lastScanTime = now;
					this.scanTracker.lastScanCode = res.code;
					this.getScancode(res.code);
				}
			});
		},
		// 关闭广播
		stopScanCode() {
			uni.$off('xwscan');
		},
		// 明细上架框显示上架数量不能大于当前物料数量，如果大于就默认为最大数量
		itSJnumConfirm(val, index) {
			if (parseInt(val) > parseInt(this.dataList[index].availableQty)) {
				setTimeout(() => {
					this.dataList[index].qty = this.dataList[index].availableQty;
				}, 200);
			}
		},
		// 打开仓位弹框
		cwtkfn(list) {
			if (!list || (list && list.length < 2)) return;
			this.cwtkshow = true;
			this.materialSubStocks = list;
		},
		//仓库选择下拉监听
		ckchange(e) {
			this.warehouseName = e.name;
			this.warehouseCode = e.code;
			this.orgCode = e.erpOrgCode;
			this.lyOrderVal = '';
			this.$refs.wselectlyorder.inputData = '';
		},
		// 获取仓库下拉数据
		getcklist() {
			this.warehouseList = [];
			this.$api.get('/SysConfig/GetUcStock').then((res) => {
				if (res.status == 200) {
					this.warehouseList = res.data;
				}
			});
		},
		// 完成下一单
		wcNxetFn() {
			console.log('完成下一单', this.subStockCode, this.lyOrderVal, this.boxstrList);
			if (!this.subStockCode || !this.lyOrderVal || this.boxstrList.length == 0) {
				uni.showToast({
					title: '请先输入必填值',
					icon: 'none',
					duration: 1000
				});
				return;
			}
			let dataForm = {};
			let details = [];
			console.log(this.dataList);
			details = this.dataList.map((it) => {
				return {
					qty: it.qty,
					supplierId: it.supplierId,
					materialNumber: it.materialNumber,
					serialNumbers: it.xlhList, //序列号集
					erpDetailId: it.erpDetailId
				};
			});
			console.log('提交数据1', this.dataList, dataForm);
			if (this.sjfsType == '按产品上架') {
				this.boxs[0].details = details;
			}
			dataForm = {
				taskId: this.fid,
				shelfMethod: this.sjfskey,
				orgCode: this.orgCode,
				stockCode: this.warehouseCode,
				subStockCode: this.subStockCode,
				boxs: this.boxs
			};
			console.log('dataForm', dataForm);
			// 节流
			if (this.requestStatus) {
				return false;
			}
			this.requestStatus = true;
			this.$api.post('/InStock/ShelfOther', dataForm).then((res) => {
				if (res.status == 200) {
					uni.showToast({
						title: '成功',
						icon: 'none',
						duration: 1000
					});
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/warehous/noCgPutOnsale'
						});
					}, 200);
					// this.$router.go(0)
				}
			});
			setTimeout(() => {
				this.requestStatus = false;
			}, 1500);
		},
		// 清空二次确认
		qktkconfirm() {
			this.boxstrList = [];
			this.xlhstrList = [];
			this.twoData=[];
			this.boxs = [];
			this.xlhVal = '';
			this.xhNo = '';
			this.dqboxNO = '';
			this.dqboxXlh = '';
			this.sjNum = null;
			this.dataList.forEach((it) => {
				it.qty = 0;
				it.xlhList = [];
			});
			this.qktkshow = false;
			this.focusInput = '';
		},
		// 根据来源单号获取下拉数据
		getlyOrderInfolist(val) {
			if (!val) return;
			clearTimeout(this.timer);
			this.timer = setTimeout(() => {
				this.$api
					.post('/InStockTask/GetSourceOrderNoPurchase', {
						sourceBillNo: val,
						stockCode: this.warehouseCode
					})
					.then((res) => {
						if (res.status == 200) {
							this.lyOrderSelectList = res.data;
						}
					});
			}, 1000);
		},
		// 扫描框数据重置，光标聚焦
		setSMinputbox() {
			this.focusInput = '';
			setTimeout(() => {
				this.dqboxNO = '';
				this.xhNo = '';
				this.sjNum = null;
				this.focusInput = 'box';
			}, 200);
		},
		clearnFn(){
			// console.log('123232323')
			this.cwNum=''
			this.subStockCode =''
			this.cwselectList=[]
			this.focusInput = ''
			setTimeout(()=>{
				this.focusInput ='cw'
			},300)	
		},
		// 根据箱号查相关信息
		getboxinfo() {
			clearTimeout(this.timer);
			this.timer = setTimeout(() => {
				if (!this.xhNo) {
					this.setSMinputbox();
					uni.showToast({
						title: '请扫描需要上架的箱号',
						icon: 'none',
						duration: 1000
					});
					return;
				}
				if (this.boxstrList.includes(this.xhNo) && this.sjfsType == '按箱上架') {
					this.setSMinputbox();
					uni.showToast({
						title: '该箱号已扫描',
						icon: 'none',
						duration: 1000
					});
					return;
				}
				this.focusInput = '';
				//采购订单物料明细和箱物料明细-对比接口，
				if (this.sjfsType == '按箱上架') {
					this.$api
						.post('/InStockTask/Contrast', {
							boxBillNos: [this.xhNo],
							stockCode: this.warehouseCode,
							taskId: this.fid,
							isPurchase:false,
						})
						.then((res) => {
							if (res.status == 200) {
								/*
								 数据分配 如果相同物料相同单号，相同规格，相同组织
								1.先判断箱子里面的物料数量是否大于订单里面物料数量的总和大于直接提示不能上架
								2.先判断a物料总数，对应明细相同物料去分配总数
								3.// 如果是扫描的第一箱子，就一一判断明细物料数量去判断，一旦某条物料总数超过就提示不能上架 
								*/
								// 明细相同物料，数量总和
								let mxwldb = this.$util.subtractQty(this.$util.sumByField(this.dataList, 'availableQty'), this.$util.sumByField(this.dataList, 'qty'));
								// 如果是第一次扫箱，就拿物料的availableQty做统计，如果不是就那qty做统计
								let mxggWLnumTotal = this.boxstrList.length > 0 ? mxwldb : this.$util.sumByField(this.dataList, 'availableQty');
								// 箱子相同物料，数量总和
								let xwlnumTotal = this.$util.sumByField(res.data.boxs[0].details, 'qty');
								// 如果存在箱物料数量大于订单物料数量就不能上架
								let pdcg = !this.$util.checkQtyExceedsLimit(mxggWLnumTotal, xwlnumTotal, 'materialNumber', 'qty');
								// console.log('判断数量超过', mxwldb,mxggWLnumTotal, xwlnumTotal,pdcg)
								if (pdcg) {
									// 进行分配
									const result = this.$util.allocateQty(xwlnumTotal, this.dataList);
									this.dataList = result.updatedDetails;
									// 每个箱子分配要知道给那条物料分别分配了多少数量
									this.boxs.push({
										id: 0,
										boxId: res.data.boxs[0].boxId,
										boxBillNo: res.data.boxs[0].boxBillNo,
										details: result.allocationLog
									});
									this.sjNum = res.data.boxs[0].totalCount;
									//保留当前输入的数据
									this.dqboxNO = res.data.boxs[0].boxBillNo;
									this.xhNo = res.data.boxs[0].boxBillNo;
									// 缓存箱号
									this.boxstrList.push(res.data.boxs[0].boxBillNo);
									this.focusInput = 'box';
									uni.showToast({
										title: '获取成功',
										icon: 'none',
										duration: 1000
									});
								} else {
									this.setSMinputbox();
									uni.showToast({
										title: '箱内产品数量超过可上架数量',
										icon: 'none',
										duration: 1000
									});
									return;
								}
							} else {
								this.setSMinputbox();
							}
						});
				}
				if (this.sjfsType == '按产品上架') {
					this.$api
						.get('/SysConfig/GetBoxSynthesis', {
							boxBillNo: this.xhNo
						})
						.then((res) => {
							if (res.status == 200) {
								// 如果当前箱子的仓库和来源单的仓库不一致就不能用这个箱子
								if (res.data.stockCode && res.data.stockCode !== this.warehouseCode) {
									this.setSMinputbox();
									uni.showToast({
										title: '该箱号仓库与来源单仓库不一致，请重新操作',
										icon: 'none',
										duration: 1400
									});
									return;
								}
								// 如果查询的箱号正常返回数据，就缓存改箱号信息
								this.boxstrList = [];
								this.boxstrList.push(this.xhNo);
								var theid = 0;
								// 如果是按产品上架，要判断是否存在过的部分扫过的箱信息，如果存在id不能为0 。按照箱就不存这这个情况为0
								if (this.lyOrderSelectList && this.lyOrderSelectList.length > 0 && this.lyOrderSelectList.boxs) {
									this.lyOrderSelectList.boxs.forEach((it) => {
										if (res.data.id == it.boxId) {
											theid = it.id;
										}
									});
								}
								this.boxs = [];
								this.boxs.push({
									id: theid,
									boxId: res.data.id,
									boxBillNo: res.data.boxBillNo
								});
								this.sjNum = res.data.totalQty ? res.data.totalQty : 0;
								//保留当前输入的数据
								this.dqboxNO = '';
								this.dqboxNO = res.data.boxBillNo;
								this.xhNo = res.data.boxBillNo;
								this.xlhVal = '';
								// 如果这个箱子仓库有值和单的仓库一致但是仓位不一致以箱子的仓位为准
								if (res.data.stockCode == this.warehouseCode && res.data.subStockCode) {
									this.$refs.wselect1.inputData = res.data.subStock;
									this.cwNum = res.data.subStock;
									this.subStockCode = res.data.subStockCode;
									console.log('仓位为准', res.data);
								}
								uni.showToast({
									title: '获取成功',
									icon: 'none',
									duration: 1000
								});
								this.focusInput = 'xlh';
							} else {
								this.setSMinputbox();
							}
						});
				}
			}, 1000);
		},
		// 普通安卓设备碘酒扫描图标扫描
		scanImg(type) {
			if (this.APPdevice == 'normalAnroid') {
				this.$util.doScanQrCode().then((res) => {
					this.focusInput = type;
					this.focusTag = type;
					this.getScancode(res.result);
				});
			}
		},
		// 获取扫描的值
		getScancode(code) {
			console.log('获取扫描的值', this.focusTag, code);
			if (this.focusTag == 'box') {
				this.xhNo = '';
				this.xhNo = code.trim();
				this.getboxinfo();
				console.log('获取扫描的值', code);
			}
			// 序列号
			if (this.focusTag == 'xlh') {
				this.xlhVal = '';
				this.xlhVal = code.trim();
				this.getXlhInfo();
				//根据序列号去更新对应的明细规格型号的上架数量的值 扫描一个数量加一，重复扫描要提示
			}
			// 仓位
			if (this.focusTag == 'cw') {
				this.cwNum = '';
				this.cwNum = code.trim();
				this.$refs.wselect1.inputData = code.trim();
				this.getcwList();
			}
			// 来源单
			if (this.focusTag == 'lyorder') {
				this.lyOrderVal = '';
				this.lyOrderVal = code.trim();
				this.$refs.wselect1.wselectlyorder = code.trim();
				this.getlyOrderInfolist(this.lyOrderVal);
			}
		},
		// 輸入失去焦點
		inputblur(val, type) {},
		// 输入聚焦
		inputfocus(val, type) {
			this.focusTag = type;
			if (type == 'cw') {
				this.focusInput = 'cw';
			}
		},
		// 区分不同的扫描数据、输入数据做处理显示 box
		setSMstr(str) {
			let lth = str.length - this.dqboxNO.length;
			if (lth > 1) {
				// 扫描的值
				this.xhNo = str.substring(this.dqboxNO.length);
			} else {
				this.dqboxNO = str;
				this.xhNo = str;
			}
		},
		// 区分不同的扫描数据、输入数据做处理显示 xlh
		setSMxlhstr(str) {
			let lth = str.length - this.dqboxXlh.length;
			if (lth > 1) {
				// 扫描的值
				this.xlhVal = str.substring(this.dqboxXlh.length);
			} else {
				this.dqboxXlh = str;
				this.xlhVal = str;
			}
		},
		// 输入确认
		inputConfirm(val, type) {
			if (val) {
				if (this.focusTag == 'box') {
					this.setSMstr(val.target.value);
					this.getboxinfo();
				}
				if (this.focusTag == 'xlh') {
					this.setSMxlhstr(val.target.value);
					this.getXlhInfo();
				}
			}
		},
		// 扫描框数据重置，光标聚焦
		setSMinputxlh() {
			this.focusInput = '';
			setTimeout(() => {
				this.xlhVal = '';
				this.focusInput = 'xlh';
			}, 200);
		},
		// 根据序列号获取对应的规格型号
		getXlhInfo() {
			if (!this.xlhVal) {
				this.setSMinputxlh();
				uni.showToast({
					title: '请扫描来源单内的序列号',
					icon: 'none',
					duration: 1000
				});
				return;
			}
			if (this.xlhstrList.includes(this.xlhVal) || this.twoData.includes(this.xlhVal) && this.sjfsType == '按产品上架') {
				this.setSMinputxlh();
				uni.showToast({
					title: '该序列号已扫描过',
					icon: 'none',
					duration: 1000
				});
				return;
			}

			this.focusInput = '';
			
			
			
			console.log('序列號', this.xlhVal);
			this.$api
				.get('/SysConfig/GetMaterial', {
					serialNumber: this.xlhVal,
					IsOps: true,
					serialStatus: 1
				})
				.then((res) => {
					if (res.status == 200) {
						let thindx = this.dataList.findIndex((it) => it.materialNumber == res.data.materialNumber);
						if (thindx == -1) {
							this.setSMinputxlh();
							uni.showToast({
								title: '请扫描来源单内的序列号',
								icon: 'none',
								duration: 1000
							});
						} else if (res.data.isBoxInventory && !res.data.isOldOps) {
							this.setSMinputxlh();
							uni.showToast({
								title: '序列号已上架入库',
								icon: 'none',
								duration: 1000
							});
						} else if (!res.data.serialNumber) {
							this.setSMinputxlh();
							uni.showToast({
								title: '请扫描序列号',
								icon: 'none',
								duration: 1000
							});
						} else {
							/*
							 *1.判断该序列号对应的物料是否有存在过扫描的物料，
							 *	如果存在都已经是扫描的状态，就判断该物料所有的上架数量是否有大于该物料数量的总和，大于就提示不能在扫描了
							 * 	如果存在部分扫描就拿扫描的的数量总和去判断是否大于物料明细的总和，大于也不能在扫描了
							 *2.分配序列号重上到下，如果第一条没有扫描过就重置上架输入框为空然后置灰累计加一，
							 * 	如果累计的数量大于了物料数量就继续往下分配，下一条物料也是如此
							 *3.一直扫描序列号 就扫描到所有物料都分配完为止（）
							 * */
							let totalAvailableQty = 0;
							let totalXlhListLength = 0;
							// 遍历数组，计算总可用数量和xlhList总长度
							for (const item of this.dataList) {
								if (item.materialNumber === res.data.materialNumber) {
									totalAvailableQty += item.availableQty;
									totalXlhListLength += item.xlhList.length;
								}
							}
							if (totalXlhListLength + 1 > totalAvailableQty) {
								this.setSMinputxlh();
								uni.showToast({
									title: '上架数量超过来源单可上架数量',
									icon: 'none',
									duration: 1000
								});
								return;
							}
							this.dataList = this.$util.scanAndAllocate(this.dataList, res.data.materialNumber, res.data.serialNumber);
							// 缓存序列号
							this.xlhstrList.push(res.data.serialNumber);
							//缓存2件装序列号
							if(res.data.isTwo==2) {
								this.twoData.push(res.data.twoSerialNumber)
							}
							//保留当前输入的数据
							this.dqboxXlh = res.data.serialNumber;
							this.xlhVal = res.data.serialNumber;
							//清空当前框数据 自动聚焦箱号
							uni.showToast({
								title: '获取成功',
								icon: 'none',
								duration: 1000
							});
						}
					} else {
						this.dqboxXlh = '';
						this.xlhVal = '';
					}
					this.focusInput = 'xlh';
				});
		},
		// 根据序列号的时候明细数据结构
		xlhsetDetaildata(list) {
			if (list && list.length > 0) {
				list.forEach((it) => {
					it.qty = 0;
					it.xlhList = [];
				});
			}
			console.log('根据序列号的时候明细数据结构', list);
			return list;
		},
		// 来源单号下拉选择监听
		lyorderChange(e) {
			this.fid = e.id;
			this.focusInput = '';
			this.fid = e.id;
			this.lymaterialNumber = e.materialNumber
			e.details = this.itemDateset(e.details);
			this.dataList = this.xlhsetDetaildata(e.details);
			console.log(1111, this.dataList);
			this.focusInput = 'cw';
		},
		// 明细数据初始化处理
		itemDateset(list) {
			let objArray = [];
			objArray = list;
			let newObjArray = objArray.map((obj) => {
				obj.zQty = JSON.parse(JSON.stringify(obj.qty)); // 修改 name 属性，这里是在姓名后加上 ' Smith'
				obj.qty = 0; // 添加 age 属性，这里设定年龄为 30
				return obj;
			});
			return objArray;
		},
		// 仓位下拉选择
		cwchange(e) {
			this.cwNum = e.name;
			this.subStockCode = e.code;
		},
		// 上架返回下拉选择监听
		sjfsChange(e) {
			// 清空箱号和缓存
			this.boxstrList = [];
			this.xhNo = '';
			this.sjfskey = e.id;
			this.sjfsType = e.name;
			this.boxs = [];
			setTimeout(() => {
				this.heights.top = this.heights.top + 36;
				this.heights.body = this.heights.body - 36;
				this.heights = this.$util.setlistHeight('.sh_gdInfo', '.footbts');
			}, 200);
			// if(this.cwNum && this.cwselectList.length  && !this.subStockCode){
			// 	this.cwselectList.forEach((item)=>{
			// 		if(item.name === this.cwNum) {
			// 			this.subStockCode = item.code
			// 			console.log(this.subStockCode,'=走到这里来了=')
			// 		}
			// 	})
			// }
			
			this.$forceUpdate();
		},
		// 获取仓位下拉数据
		getcwList(val) {
			if (!val && !this.warehouseCode) return;
			this.$api
				.post('/SysConfig/GetSubUcStockByName', {
					name: val,
					stockCode: this.warehouseCode,
					orgCode:this.orgCode
				})
				.then((res) => {
					if (res.status == 200) {
						this.cwselectList = res.data;
						//&& this.cwselectList.length == 1
						// if (this.cwselectList && this.cwselectList.length == 1) {
						// 	this.cwNum = this.cwselectList[0].name;
						// 	this.cwchange(this.cwselectList[0]);
						// 	this.$refs.wselect1.optionsShow = false;
						// 	this.$refs.wselect1.isShow = false;
						// }
						
					}
				});
		},
		onBottomPage() {},
		goback() {
			uni.navigateTo({
				url: '/pages/warehous/index'
			});
		}
	}
};
</script>

<style lang="scss">
@import '@/static/public.scss';

.mianheade2 {
	.pagetitle {
		margin-left: 26%;
	}
}
</style>
