<!-- 整箱移货上架 -->
<template>
	<view class="shpage zxyhsjpage">
		<!-- 标题栏 -->
		<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 class="redtag">*</text>仓库: </text>
					<text class="t2">{{warehouseName}}</text>
				</view>
			</view>
			<view class="item" :class="{'itembg2':boxstrList&&boxstrList.length>0}"
				:style="{'pointer-events':boxstrList&&boxstrList.length>0?'none':''}">
				<view class="it itsp">
					<text class="t1"><text class="redtag">*</text>目标仓位号: </text>
					<w-select class="wwselectit" v-model='cwNum' defaultValue="模糊搜索" :list='cwselectList'
						valueName='name' keyName="name" @change='cwchange' :filterable='filterable' ref="wselect1"
						@focus="inputfocus($event,'cw')" :focus="focusInput=='cw'" :showClose='true'>
					</w-select>
					<image src="../../static/img/smico.png" class="searchico" @click="scanImg('cw')"></image>
				</view>
			</view>
			<view class="item" :class="{'itembg2':!cwcode}" :style="{'pointer-events':!cwcode?'none':''}">
				<view class="it itsp">
					<text class="t1"><text class="redtag">*</text>箱号: </text>
					<input v-model="boxNo" 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 item2">
				<view class="it2 it50">
					<text class="t1">{{boxstrList.length}}</text>
					<text class="t2">已扫描箱数</text>
				</view>
				<view class="it2 it50">
					<text class="t1 rednum">{{totalNum}}</text>
					<text class="t2">总数量</text>
				</view>

			</view>
		</view>
		<!-- 列表内容-->
		<view class="shlb cgsjrklb jscklb" :style="{'margin-top':heights.top+'px','height':heights.body+'px'}">
			<view class="item" v-for="(item,index) in dataList" :key="index">
				<view class="it">
					<!-- 箱号 -->
					<text class="txt titstr">{{item.boxBillNo}}</text>
					<view v-for="(cit,index) in item.details" class="ibgt" :key="cit.specifications">
						<text class="txt">{{cit.specifications}}</text>
						<view class="txt txtflexnum">
							<text class="txt">{{cit.materialNumber}}</text>
							<text class="txt"> {{cit.qty}}</text>
						</view>
					</view>
				</view>
			</view>
		</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>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				heights: {
					top: 0,
					body: 0,
				},
				focusInput: 'cw', // 自动聚焦
				filterable: true, //下拉模糊搜索是否开启
				warehouseName: '', // 仓库名称 根据箱号带出来的会实时更新
				warehouseCode: '', // 仓库编码
				cwNum: '', // 仓位值
				cwselectList: [], //仓位下拉集合
				cwcode: '', // 仓位code
				boxNo: '', //箱号值
				boxstrList: [], // 缓存的箱号信息（多个）
				totalNum: 0, // 总数量
				dataList: [], // 明细数据
				focusTag: '', // 判断聚焦
				qktkshow: false, //清空二次确认弹框
				qktkTitle: '确定清空上架数量?',
				qktkContent: "清空后页面数据将不保存",
				tjdata: [], // 页面提交数据
				dqboxNO: '', //用来是否保存当前输入箱号的值
				APPdevice: uni.getStorageSync('devicePixelRatio'), // 缓存设备的像素比用来区分普通安卓normalAnroid还是pda
				requestStatus: false, // 请求状态识别变量
				scanTracker: {
					lastScanTime: 0,
					lastScanCode: null
				}, // 源头处理扫码段时间内重复扫
			}
		},
		watch: {
			boxNo(n) {
				if (!n) {
					this.dqboxNO = ''
				}
			},
			// 仓位下拉数据
			cwNum(n, o) {
				if(!n){
					this.cwselectList =[]
					this.cwcode = null
					this.warehouseCode = null
					this.warehouseName = null
					this.orgCode = null
				} else {
					this.getcwList(n)
				}
			}
		},
		onReady() {
			this.heights = this.$util.setlistHeight('.sh_gdInfo', '.footbts')
		},
		onLoad() {
			//获取广播扫码监听
			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,'otherUnderwearIndex')
			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')
			},
			// 完成完成/下一单
			wcNxetFn() {
				if (!this.cwcode || this.boxstrList.length == 0) {
					uni.showToast({
						title: '请先输入必填值',
						icon: 'none',
						duration: 1500
					})
					return
				}
				// 节流
				if (this.requestStatus) {
					return false;
				}
				this.requestStatus = true
				this.$api.post('/MoveBoxRecord/Up_Save', this.tjdata).then(res => {
					if (res.status == 200) {
						uni.showToast({
							title: '成功',
							icon: 'none',
							duration: 1500
						})
						setTimeout(() => {
							uni.navigateTo({
								url: '/pages/otherUnderwear/moveBoxup'
							})
						}, 200);
						// this.$router.go(0)
					}
				})
				setTimeout(() => {
					this.requestStatus = false;
				}, 1500);
			},
			// 清空二次确认
			qktkconfirm() {
				this.boxNo = ''
				this.boxstrList = []
				this.dataList = []
				this.tjdata = []
				this.totalNum = 0
				this.qktkshow = false
				this.focusInput =''
				setTimeout(() =>{
					if(!this.cwcode){
						this.focusInput ='cw'
					} else {
						this.focusInput = 'box'
					}
				}, 200)
			},
			// 区分不同的扫描数据、输入数据做处理显示 box
			setSMstr(str) {
				let lth = str.length - this.dqboxNO.length
				if (lth > 1) {
					// 扫描的值
					this.boxNo = str.substring(this.dqboxNO.length)
				} else {
					this.dqboxNO = str
					this.boxNo = str
				}
			},
			// 输入确认
			inputConfirm(val, type) {
				if (val) {
					if (this.focusTag == 'box') {
						this.setSMstr(val.target.value)
						this.getboxinfo()
					}
				}
			},
			// 輸入失去焦點
			inputblur(val, type) {},
			// 输入聚焦
			inputfocus(val, type) {
				this.focusTag = type
				if (type == 'cw') {
					this.focusInput = 'cw'
				}
			},
			// 获取仓位下拉数据
			getcwList(val) {
				if (!val) return
				this.$api.get('/SysConfig/GetSubUcStockByName', {
					name: val
				}).then(res => {
					if (res.status == 200) {
						this.cwselectList = res.data
						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
						}
					}
				})
			},
			// 仓位下拉选择
			cwchange(e) {
				this.cwcode = e.code
				this.stockId = e.stockId
				this.warehouseCode = e.stockCode
				this.warehouseName = e.stockName
				this.focusInput = 'box'
			},
			// 普通安卓设备碘酒扫描图标扫描
			scanImg(type) {
				if (this.APPdevice == "normalAnroid") {
					this.$util.doScanQrCode().then(res => {
						this.focusInput = type
						this.focusTag = type
						this.getScancode(res.result)
					})
				}
			},
			// 获取扫描的值
			getScancode(code) {
				if (this.focusTag == 'box') {
					// 有些PDA会自带换行符，trim函数处理下
					this.boxNo = ''
					this.boxNo = code.trim()
					this.getboxinfo()
				}
				// 序列号
				if (this.focusTag == 'cw') {
					this.cwNum = ''
					this.cwNum = code.trim()
					this.$refs.wselect1.inputData = code.trim()
					this.getcwList()
					//根据序列号去更新对应的明细规格型号的上架数量的值 扫描一个数量加一，重复扫描要提示
				}
			},
			// 扫描框数据重置，光标聚焦
			setSMinputbox() {
				this.focusInput = ''
				setTimeout(() => {
					this.boxNo = ''
					this.focusInput = 'box'
					this.dqboxNO = ''
				}, 200)
			},
			// 根据箱号获取信息
			getboxinfo() {
				if (!this.boxNo) {
					this.setSMinputbox()
					uni.showToast({
						title: '请扫描需要上架的箱号',
						icon: 'none',
						duration: 1000
					})
					return
				}
				if (this.boxstrList.includes(this.boxNo)) {
					this.setSMinputbox()
					uni.showToast({
						title: '该箱号已扫描',
						icon: 'none',
						duration: 1000
					})
					return
				}
				this.focusInput = ''
				this.$api.get('/SysConfig/GetBox_MoveBoxRecord', {
					boxBillNo: this.boxNo,
				}).then(res => {
					if (res.status == 200) {
						if (res.data.subStockCode) {
							this.setSMinputbox()
							uni.showToast({
								title: '箱号已上架入库',
								icon: 'none',
								duration: 1500
							})
							return
						}
						// 页面提交数据
						let thetotalQty = 0
						thetotalQty = this.$util.sumObjectArrayValues(res.data.details, 'qty')
						this.tjdata.push({
							boxId: res.data.id,
							subStockCode: this.cwcode,
							qty: thetotalQty,
							details: res.data.details
						})
						this.dataList.push(res.data)
						// 总数量
						this.totalNum = this.totalNum + thetotalQty
						// 缓存箱号
						this.boxstrList.push(res.data.boxBillNo)
						// 扫描当前
						this.dqboxNO = res.data.boxBillNo
						this.boxNo = res.data.boxBillNo
						uni.showToast({
							title: '获取成功',
							icon: 'none',
							duration: 1000
						})
					}
					//清空当前框数据 自动聚焦箱号
					this.setSMinputbox()
				})
			},
			goback() {
				uni.navigateTo({
					url: "/pages/otherUnderwear/index"
				})
			}
		}
	}
</script>

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

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