<!-- 收货 -->
<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 itembg2">
				<view class="it">
					<text class="t1">仓库: </text>
					<text class="t2">{{warehouseName}}</text>
				</view>
			</view>
			<view class="item" :class="{'itembg2':xhNo || boxstrList.length>0 }"
				:style="{'pointer-events':xhNo ||boxstrList.length>0?'none':''}">
				<view class="it itsp" >
					<text class="t1"><text class="redtag">*</text>采购订单号: </text>
					<!-- <view class="t1" style="display: flex;">
						<text class="redtag">*</text>
						<uni-data-select
						style="font-size:12px"
						  v-model="selectValue"
						  :localdata="options"
						  @change="hanldeSelectChange"
						  :clear="false"
						></uni-data-select>
					</view> -->
					
						<w-select  class="wwselectit" v-model.trim='cgOrderVal' defaultValue="请输入订单号搜索" :list='cgselectList'
							valueName='sourceBillNo' keyName="sourceBillNo" @change='cgchange' :filterable='filterable'
							optionType="order" @onBottomPage="onBottomPage" :pagingSet='false' :focus="focusInput=='cgdd'"
							@focus="inputfocus($event,'cgdd')" :showClose='true' ref="wselectcgdd">
						</w-select>
						<image src="../../static/img/smico.png" class="searchico" @click="scanImg('cgdd')"></image>
				</view>
			</view>
			<view class="item" :class="{'itembg2':!cgOrderVal}" :style="{'pointer-events':!cgOrderVal?'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 itembg2">
				<view class="it">
					<text class="t1">数量: </text>
					<text class="t1 tpleft">{{boxNum}} </text>
				</view>
			</view>
			<view class="item item2">
				<view class="it2">
					<text class="t1">{{cgOrderWLnum}}</text>
					<text class="t2">订单数量</text>
				</view>
				<view class="it2">
					<text class="t1">{{krkNum}}</text>
					<text class="t2">可入库数</text>
				</view>
				<view class="it2">
					<text class="t1 rednum">{{yshNum}}</text>
					<text class="t2">已收货数</text>
				</view>
				<view class="it2" @click="xhmodelOpen">
					<text class="t1 rednum">{{boxstrList.length}}</text>
					<text class="t2">已收箱数</text>
				</view>
			</view>
		</view>
		<!-- 列表内容-->
		<view class="shlb" :style="{'margin-top':heights.top+'px','height':heights.body+'px'}">
			<z-paging ref="paging" v-model="dataList" @query="queryList" class="xlfeview"
				loading-more-default-text="上拉加载更多" :refresher-enabled="false">
				<view class="item" v-for="(i,index) in dataList" :key="index">
					<view class="it">
						<text class="txt">{{i.specifications}}</text>
						<text class="txt">{{i.materialNumber}}</text>
						<text class="txt">明细备注:{{i.remark}}</text>
					</view>
				</view>
				<zero-loading v-if="listloading" type="circle" style="top: 60%;"></zero-loading>
			</z-paging>
		</view>
		<!-- 已上架箱号-->
		<u-modal :show="xhlistshow" title="已收箱号" @confirm="xhlistshow =false">
			<view style="display: flex;flex-direction: column;overflow-y: auto;max-height: 60vh;overflow-y: auto;">
				<view v-for="(item,index) in boxstrList" style="margin-bottom: 5px;">{{item}}</view>
			</view>
		</u-modal>
		<!-- 底部按钮固定-->
		<view class="footbts">
			<view class="bt bt1" @click="qktkshow = true">清空收货数量</view>
			<view class="bt bt2" @click="completefn()">完成/下一单</view>
		</view>
		<!--清空二次确认弹框-->
		<u-modal :show="qktkshow" :title="qktkTitle" :content='qktkContent' @confirm="qktkconfirm"
			:showCancelButton='true' @cancel="qktkshow = false"></u-modal>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				heights: {
					top: 0,
					body: 0,
				},
				options:[
					{value:1,text:'采购订单号'},
					{value:2,text:'生产单号'},
				],
				selectValue:1,//单号选择
				listloading: false,
				xhlistshow: false, // 箱号查看弹框
				focusInput: 'cgdd', // 自动聚焦
				mxid: '', //采购订单下拉选中明细id
				focusTag: "", //  判斷聚焦
				warehouseName: '', //仓库名称
				warehouseCode: '', // 仓库编码
				xhNo: "", //箱号
				boxstrList: [], // 缓存的箱号信息（多个）
				filterable: true, // 采购订单是否开启模糊下拉搜索
				boxNum: 0, //数量（扫码箱子的数量）
				boxs: [], // 已经扫描的箱子和对应id集合
				cgOrderWLnum: 0, // 订单数量（采购订单物料数量）
				cgOrderVal: "", //输入的采购订单号
				cgselectList: [], //采购下拉数据
				krkNum: 0, //可入库数量
				yshNum: 0, // 已收货数量
				dataList: [], // 列表数据
				qktkshow: false, //清空二次确认弹框
				qktkTitle: '确定清空已收货数量?',
				qktkContent: "清空后页面数据将不保存",
				timer: null,
				availableQty: 0, // 第一次订单的可入库数量
				erpDetailId: null, // erp明细id
				dqboxNO: '', //用来是否保存当前输入箱号的值
				APPdevice: uni.getStorageSync('devicePixelRatio'), // 缓存设备的像素比用来区分普通安卓normalAnroid还是pda
				requestStatus: false, // 请求状态识别变量
				materialNumber: null, //选中采购单的时候物料编码
				scanTracker: {
					lastScanTime: 0,
					lastScanCode: null
				}, // 源头处理扫码段时间内重复扫
			}
		},
		watch: {
			boxNo(n) {
				if (!n) {
					this.dqboxNO = ''
				}
			},
			// 采购订单号实时输入监听
			cgOrderVal(n, o) {
				if (!n) {
					this.qktkconfirm()
					this.dataList = []
					this.cgOrderWLnum = 0
					this.krkNum = 0
					this.yshNum = 0
					this.yshNum = 0
					this.dqboxNO = ''
					this.cgselectList = []
					this.warehouseName = ''
					this.warehouseCode = ''
				} else {
					this.getcgOrderSelectData(n)
				}
			}
		},
		onReady() {
			setTimeout(() => {
				this.heights = this.$util.setlistHeight('.sh_gdInfo', '.footbts')
				console.log("设备信息", this.heights)
			}, 500)
		},
		mounted() {
			//获取广播扫码监听
			this.$broadcastScan.init(this.getScancode)
			this.$broadcastScan.start();
			this.stopScanCode()
			this.startScanCode()
		},
		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')
			},
			// 打开查看箱号
			xhmodelOpen() {
				if (this.boxstrList.length > 0) {
					this.xhlistshow = true
				}
			},
			// 清空二次确认
			qktkconfirm() {
				this.xhNo = ""
				this.boxNum = 0
				this.krkNum = this.$util.sumObjectArrayValues(this.dataList, 'availableQty')
				this.qktkshow = false
				this.yshNum = 0
				this.boxs = []
				this.boxstrList = []
			},
			// //select-change
			// hanldeSelectChange() {
			// 	this.cgOrderVal = ""
			// 	this.$refs.wselectcgdd.inputData=""
			// 	this.focusInput= ""
			// 	setTimeout(()=>{
			// 		this.focusInput='cgdd'
			// 	},200)
			// },
			// 获取采购订单下拉数据
			getcgOrderSelectData(val) {
				if (!val) return
				clearTimeout(this.timer)
				this.timer = setTimeout(() => {
					this.$api.get('/InStockTask/GetSourceOrder/' + val).then(res => {
						if (res.status == 200) {
							this.cgselectList = []
							this.cgselectList = res.data
							console.log(this.focusInput)
							if (this.cgselectList && this.cgselectList.length == 1) {
								this.cgOrderVal = this.cgselectList[0].sourceBillNo
								this.$refs.wselectcgdd.filterList = res.data
								this.$refs.wselectcgdd.inputData = this.cgselectList[0].sourceBillNo
								this.setItemdata(this.cgselectList[0])
								this.cgchange(this.cgselectList[0])
								this.$refs.wselectcgdd.optionsShow = false
								this.$refs.wselectcgdd.isShow = false
							} else {
								this.$refs.wselectcgdd.optionsShow = true
								this.$refs.wselectcgdd.isShow = true
							}
							if(this.focusInput !== 'cgdd'){
								this.$refs.wselectcgdd.optionsShow = false
								this.$refs.wselectcgdd.isShow = false
							}
						}
					})
				}, 1000)
			},
			// 采购订单下拉框分页加载
			onBottomPage(val) {},
			// 选中的采购订单号相关物料  如果数据校验失败就取明细带来的信息，不是就去明细信息的
			setItemdata(e) {
				this.availableQty = e.availableQty
				this.cgOrderWLnum = this.$util.sumObjectArrayValues(this.dataList, 'qty')
				this.mxid = e.detailsId
				this.fid = e.id
				this.materialNumber = e.materialNumber
				// 仓库名称
				this.warehouseName = e.stockName
				this.warehouseCode = e.stockCode
				this.erpDetailId = e.erpDetailId
				this.krkNum = e.availableQty
				this.focusInput = 'box'
			},
			// 采购订单下拉选中
			cgchange(e) {
				if (!this.cgOrderVal) {
					return
				}
				this.dataList = [e]
				// 以前已收货数量
				this.setItemdata(e)
			},
			// 扫描框数据重置，光标聚焦
			setSMinputbox() {
				this.focusInput = ''
				setTimeout(() => {
					this.xhNo = ''
					this.focusInput = 'box'
					this.boxNum = ''
				}, 200)
			},
			// 根据箱号查相关信息
			getboxinfo() {
				if (this.timer) {
					clearTimeout(this.timer)
				}
				this.timer = setTimeout(() => {
					if (!this.xhNo) {
						this.setSMinputbox()
						uni.showToast({
							title: '请扫描需要上架的箱号',
							icon: 'none',
							duration: 1500
						})
						return
					}
					if (this.boxstrList.includes(this.xhNo)) {
						this.setSMinputbox()
						uni.showToast({
							title: '该箱号已扫描，请重新输入',
							icon: 'none',
							duration: 1500
						})
						return
					}
					this.focusInput = ''
					//采购订单物料明细和箱物料明细-对比接口，
					this.$api.post('/InStockTask/Contrast', {
						boxBillNos: [this.xhNo.trim()],
						stockCode: this.warehouseCode,
						materialNumber:this.materialNumber,
						taskId: this.fid,
						isPurchase:true,
					}).then(res => {
						if (res.status == 200) {
							if(res.data.boxs[0].details.length>1){
								this.dqboxNO = ''
								this.xhNo = ''
								uni.showToast({
									title: '箱内产品和采购单不一致！',
									icon: 'none',
									duration: 1000
								})
								return
							}
							// 需要带出相关已收货数和已收箱数（这个数量应该是箱子对应单据选择物料的数量）
							// let boxbymaterialQtyobj = res.data.boxs[0].details.find(item => item.materialNumber === this.materialNumber)
							// console.log('物料数量',boxbymaterialQtyobj.qty)
							let totalCount = res.data.boxs[0].totalCount
							// 可入库数量=订单数量-（当前箱子的数量+累计）-以前收货数量-已交
							// let dqkrkNUM = this.cgOrderWLnum - (this.yshNum + totalCount) - this.$util
							// 	.sumObjectArrayValues(this.dataList, 'receiveQty') - this.$util.sumObjectArrayValues(
							// 		this.dataList, 'deliveredQty')
							// 12.5 界面可入库数量=接口第一次返回的可入库数量-已收货数量
							let dqkrkNum = this.$util.sumObjectArrayValues(this.dataList, 'availableQty')
							console.log('可入', parseInt(this.yshNum + totalCount), this.krkNum, )
							if (res.data.boxs.length > 0) {
								if (parseInt(this.yshNum + totalCount) > dqkrkNum) {
									this.setSMinputbox()
									uni.showToast({
										title: '箱内产品数量超过可入库数量',
										icon: 'none',
										duration: 1000
									})
									return
								}
								// 当前箱号里面物料的数量
								this.boxNum = totalCount
								// 已收货数量 累加
								this.krkNum = dqkrkNum - (this.yshNum + totalCount)
								this.yshNum = this.yshNum + totalCount
								this.boxs.push({
									id: 0,
									erpDetailId: this.erpDetailId,
									boxId: res.data.boxs[0].boxId,
									boxBillNo: res.data.boxs[0].boxBillNo
								})
								// 如果查询的箱号正常返回数据，就缓存改箱号信息
								this.boxstrList.push(res.data.boxs[0].boxBillNo)
								//保留当前输入的数据
								this.dqboxNO = res.data.boxs[0].boxBillNo
								this.xhNo = res.data.boxs[0].boxBillNo
								uni.showToast({
									title: '获取成功',
									icon: 'none',
									duration: 1500
								})
							}
						} else {
							this.dqboxNO = ''
							this.xhNo = ''
						}
						this.focusInput = 'box'
					})
				}, 1000)
			},
			// 输入确认
			inputConfirm(val, type) {
				if (val) {
					this.setSMstr(val.target.value)
					if (this.focusTag == 'box') {
						// this.xhNo = val.target.value
						this.getboxinfo()
					}
				}
			},
			// 区分不同的扫描数据、输入数据做处理显示
			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
				}
			},
			// 普通安卓设备碘酒扫描图标扫描
			scanImg(type) {
				if (this.APPdevice == "normalAnroid") {
					this.$util.doScanQrCode().then(res => {
						this.focusInput = type
						this.focusTag = type
						this.getScancode(res.result)
					})
				}
			},
			// 获取扫描的值
			getScancode(code) {
				// 有些PDA会自带换行符，trim函数处理下、
				if (this.focusTag == 'box') {
					this.xhNo = ''
					this.xhNo = code.trim()
					this.getboxinfo()
				}
				if (this.focusTag == 'cgdd') {
					this.cgOrderVal = ''
					this.cgOrderVal = code.trim()
					this.$refs.wselectcgdd.inputData = code.trim()
					this.getcgOrderSelectData(this.cgOrderVal)
				}

			},
			// 輸入失去焦點
			inputblur(val, type) {},
			// 输入聚焦
			inputfocus(val, type) {
				this.focusTag = type
			},
			// 完成/下一单
			completefn() {
				if (!this.cgOrderVal || this.boxstrList.length == 0) {
					uni.showToast({
						title: '请先输入必填值',
						icon: 'none',
						duration: 1500
					})
					return
				}
				// 节流
				if (this.requestStatus) {
					return false;
				}
				this.requestStatus = true;
				this.$api.post('/InStockTask/Receive', {
					id: this.fid,
					boxs: this.boxs,
					details: [{
						id: this.mxid, //明细id
						materialNumber: this.materialNumber,
						receiveQty: this.yshNum,
						erpDetailId: this.erpDetailId
					}]
				}).then(res => {
					if (res.status == 200) {
						uni.showToast({
							title: '成功',
							icon: 'none',
							duration: 1500
						})
						setTimeout(() => {
							uni.navigateTo({
								url: '/pages/warehous/takeDelivery'
							})
						}, 200);
						// this.$router.go(0)
					}
				})
				setTimeout(() => {
					this.requestStatus = false;
				}, 1500);
			},
			goback() {
				uni.navigateTo({
					url: "/pages/warehous/index"
				})
			},
			// 列表上拉加载更多
			queryList(pageNo, pageSize) {
				// console.log('上拉加载', pageNo, pageSize, this.dataList.length)
				// this.$refs.paging.complete(this.dataList)
			}
		}
	}
</script>

<style lang="scss">
	@import "@/static/public.scss";
	::v-deep .uni-select {
		border:none !important;
		height:24px;
		width: 175rpx;
		padding-right: 0;
		padding-left: 3rpx;
		text-align: center;
		margin-left: -7rpx;
	}
</style>