<!-- 采购上架入库 -->
<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 || ysjxNum > 0 }"
				:style="{ 'pointer-events': xhNo || boxstrList.length > 0 || ysjxNum > 0 ? 'none' : '' }"
			>
				<view class="it itsp">
					<text class="t1">
						<text class="redtag">*</text>
						来源单号:
					</text>
					<w-select
						class="wwselectit"
						v-model.trim="lyOrderNo"
						defaultValue="请输入订单号搜索"
						:list="lyselectList"
						valueName="sourceBillNo"
						keyName="sourceBillNo"
						@change="lychange"
						:filterable="filterable"
						optionType="order-cg"
						@onBottomPage="onBottomPage"
						:pagingSet="false"
						:focus="focusInput == 'lydd'"
						@focus="inputfocus($event, 'lydd')"
						:showClose="true"
						ref="wselectlydd"
					></w-select>
					<image src="../../static/img/smico.png" class="searchico" @click="scanImg('cgdd')"></image>
				</view>
			</view>
			<view class="item itembg2">
				<view class="it">
					<!-- t1 -->
					<text class="" style="font-size: 14px;">物料:</text>
					<!-- t2 -->
					<text class="" style="font-size: 14px;">
						{{ krcwInfo.specifications }}
						<text v-if="krcwInfo.waitSlefQty">({{ krcwInfo.waitSlefQty }})</text>
					</text>
				</view>
			</view>
			<view class="item itembg2">
				<view class="it itsp" @click="openkrkTk">
					<!-- t1 -->
					<text class="" style="font-size: 14px;">可入仓位:</text>
					<!-- t1 -->
					<text class="tpleft" style="font-size: 14px; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap">
						{{ krkStrVal }}
					</text>
					<image src="../../static/img/ckgd.png" class="searchico icinfo"></image>
				</view>
			</view>
			<view
				class="item"
				:class="{ itembg2: !lyorderId || !warehouseCode || ysjtotalNum > 0 }"
				:style="{ 'pointer-events': !lyorderId || !warehouseCode || ysjtotalNum > 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"
					></w-select>
					<image src="../../static/img/smico.png" class="searchico" @click="scanImg('cw')"></image>
				</view>
			</view>
			<view class="item" :class="{ itembg2: !subStockCode || !cwNum }" :style="{ 'pointer-events': !subStockCode || !cwNum ? '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/ckxx.png" class="searchico icinfo" @click="daisjboxTk"></image>
					<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">{{ ysjtotalNum }}</text>
					<text class="t2">已上架总数量</text>
				</view>
				<view class="it2 it50">
					<text class="t1">{{ sjNum }}</text>
					<text class="t2">当前上架数量</text>
				</view>
				<view class="it2 it50" @click="xhmodelOpen">
					<text class="t1 rednum">{{ ysjxNum }}</text>
					<text class="t2">已上架箱数</text>
				</view>
			</view>
		</view>
		<!-- 列表内容-->
		<view class="shlb 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">
					<view class="txt titstr gxzxlb">
						<text>{{ item.boxBillNo }}</text>
						<image src="../../static/img/deletico.png" class="deletico" @click="deletItem(item, index)"></image>
					</view>
					<view class="cssj_it">
						<view class="tlinb">
							<text class="txt">{{ item.specifications }}</text>
							<view class="txt txtflexnum">
								<text>{{ item.materialNumber }}</text>
								<text class="txtNum">数量：{{ item.boxMaterialQty }}</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 可入仓位弹框-->
		<u-modal :show="krkshow" title="" @confirm="krkshow = false">
			<view class="boxtkct1" style="max-height: 50vh; overflow-y: auto">
				<view class="cwit">
					<text class="t1 tb">所在仓位:</text>
					<view class="cws">
						<view v-for="(item, index) in krcwInfo.materialSubStocks" class="krcwname">{{ item }}</view>
					</view>
				</view>
				<text class="t1">{{ krcwInfo.specifications }}</text>
				<text class="t1">{{ krcwInfo.materialNumber }}</text>
				<text class="t1">{{ krcwInfo.materialName }}</text>
				<view class="cwit">
					<text class="t1">可入仓位:</text>
					<view class="cws">
						<view v-for="(item, index) in krcwInfo.materialSubStocks" class="krcwname">{{ item }}</view>
					</view>
				</view>
			</view>
		</u-modal>
		<!-- 待上架箱号-->
		<u-modal :show="daixhlistshow" title="待上架箱号" @confirm="daixhlistshow = false">
			<view class="boxtkct">
				<view v-for="(item, index) in daiboxstrList" class="c_item">{{ item.boxBillNo }}</view>
			</view>
		</u-modal>
		<!-- 已上架箱号-->
		<u-modal :show="xhlistshow" title="已上架箱号" @confirm="xhlistshow = false">
			<view class="boxtkct">
				<view v-for="(item, index) in boxstrList" class="c_item">{{ 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 {
			krcwInfo: {
				materialSubStocks: [],
				materialNumber: '',
				specifications: '',
				materialName: '',
				waitSlefQty: ''
			}, // 可入仓位
			krkStrVal: '', //可入库文本显示
			lyselectList: [], // 来源订单列表
			heights: {
				top: 0,
				body: 0
			},
			krkshow: false, // 可入库弹框
			xhlistshow: false, // 箱号查看弹框
			daixhlistshow: false, // 待上架箱号查看弹框
			focusInput: 'lydd', // 自动聚焦
			focusTag: '', //  判斷聚焦
			warehouseName: '', //仓库名称
			cwNum: '', // 仓位号
			cwselectList: [], // 仓位下拉数据
			warehouseCode: '', //仓库id
			subStockCode: '', // 仓位code
			xhNo: '', //箱号
			boxstrList: [], // 缓存的箱号信息（多个）
			daiboxstrList: [], // 待上架箱号信息（多个）
			lyOrderNo: '', // 来源订单号
			lyorderId: '', // 来源订单号Id
			sjNum: 0, //数量（扫码箱子的数量）
			filterable: true,
			ysjtotalNum: 0, //已上架总数量
			ysjxNum: 0, // 已上架箱数
			datalist: [], //列表明细数据，箱号里面的物料信息
			qktkshow: false, //清空二次确认弹框
			qktkTitle: '确定清空已收货数量?',
			qktkContent: '清空后页面数据将不保存',
			fid: '', // 来源单号
			instockType:null,
			orgCode: '', // 组织编码
			dqboxNO: '', //用来是否保存当前输入箱号的值
			APPdevice: uni.getStorageSync('devicePixelRatio'), // 缓存设备的像素比用来区分普通安卓normalAnroid还是pda
			requestStatus: false, // 请求状态识别变量
			scanTracker: {
				lastScanTime: 0,
				lastScanCode: null
			}, // 源头处理扫码段时间内重复扫
			detailsId: '', //明细ID
			customerCode: '' // 客户编码
		};
	},
	watch: {
		boxNo(n) {
			if (!n) {
				this.dqboxNO = '';
			}
		},
		cwNum(n, o) {
			console.log('1232321232323')
			if (!n) {
				this.cwselectList = [];
				this.subStockCode = null;
				// this.orgCode = null;
			} else {
				this.subStockCode = null;
				// this.orgCode = null;
				this.getcwList(n);
			}
		},
		// 采购订单号实时输入监听
		lyOrderNo(n, o) {
			if (n) {
				this.getlyOrderSelectData(n);
			} else {
				this.krkStrVal = '';
				this.warehouseCode = '';
				this.warehouseName = '';
				this.cwNum = '';
				this.$refs.wselect1.inputData = '';
				this.cwselectList = [];
				this.daiboxstrList = [];
				this.orgCode="";
				this.krcwInfo = {
					materialSubStocks: [],
					materialNumber: '',
					specifications: '',
					materialName: '',
					waitSlefQty: ''
				};
			}
		}
	},
	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, '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');
		},
		// 查看可入库详情弹框
		openkrkTk() {
			if (this.krcwInfo.materialSubStocks && this.krcwInfo.materialSubStocks.length > 0) {
				this.krkshow = true;
			}
		},
		// 待上架弹框
		daisjboxTk() {
			if (!this.lyorderId) return;
			this.$api
				.post('/InStockTask/GetReceiveBox', {
					taskId: this.lyorderId,
					materialNumber: this.krcwInfo.materialNumber
				})
				.then((res) => {
					if (res.status == 200) {
						this.daiboxstrList = [];
						this.daiboxstrList = res.data;
						if (this.daiboxstrList.length > 0) {
							this.daixhlistshow = true;
						} else {
							uni.showToast({
								title: '没有待上架箱数据',
								icon: 'none',
								duration: 1000
							});
						}
					}
				});
		},
		// 获取采购订单下拉数据
		getlyOrderSelectData(val) {
			if (!val) return;
			clearTimeout(this.timer);
			this.timer = setTimeout(() => {
				this.$api.get('/InStockTask/GetSourceOrder/' + val +"&").then((res) => {
					if (res.status == 200) {
						this.lyselectList = [];
						this.lyselectList = res.data && res.data.length>0? res.data.filter(element => element.waitSlefQty > 0):[]
						
						if (this.lyselectList && this.lyselectList.length == 1) {
							this.lyOrderNo = this.lyselectList[0].sourceBillNo;
							this.$refs.wselectlydd.filterList = res.data;
							this.$refs.wselectlydd.inputData = this.lyselectList[0].sourceBillNo;
							this.setItemdata(this.lyselectList[0]);
							this.lychange(this.lyselectList[0]);
							this.$refs.wselectlydd.optionsShow = false;
							this.$refs.wselectlydd.isShow = false;
						} else {
							this.$refs.wselectlydd.optionsShow = true;
							this.$refs.wselectlydd.isShow = true;
						}
						if (this.focusInput !== 'lydd') {
							this.$refs.wselectlydd.optionsShow = false;
							this.$refs.wselectlydd.isShow = false;
						}
						// console.log(this.instockType,'=this.instockType=')
					}
				});
			}, 1000);
		},
		// 来源订单选择监听
		lychange(e) {
			if (!this.lyOrderNo) {
				return;
			}
			console.log(1111111111111,'=============')
			// console.log(e,'===============>>>')
			this.setItemdata(e);
		},
		// 选中的来源订单号相关物料
		setItemdata(e) {
			console.log(e,'==============e==============')
			this.lyorderId = e.id;
			this.detailsId = e.detailsId;
			this.customerCode = e.customerCode;
			this.instockType = e.instockType;
			this.orgCode =e.orgCode;
			// 仓库名称
			this.warehouseName = e.stockName;
			this.warehouseCode = e.stockCode;
			this.krcwInfo = {
				materialSubStocks: e.materialSubStocks,
				specifications: e.specifications,
				materialNumber: e.materialNumber,
				materialName: e.materialName,
				waitSlefQty: e.waitSlefQty
			};
			if (e.materialSubStocks && e.materialSubStocks.length > 0) {
				this.krkStrVal = '';
				e.materialSubStocks.forEach((it) => {
					this.krkStrVal = this.krkStrVal + it + ',';
				});
			}
			this.focusInput = 'cw';
		},
		// 来源订单下拉框分页加载
		onBottomPage(val) {},
		// 打开查看箱号
		xhmodelOpen() {
			if (this.boxstrList.length > 0) {
				this.xhlistshow = true;
			}
		},
		// 完成/下一单
		completefn() {
			if (!this.cwNum || !this.ysjtotalNum || !this.ysjxNum || this.boxstrList.length == 0) {
				uni.showToast({
					title: '请先输入必填值',
					icon: 'none',
					duration: 1000
				});
				return;
			}
			let thedetails = [];
			thedetails = this.datalist.map((it) => {
				return {
					detailsId: this.detailsId,
					customerCode: this.customerCode,
					taskId: it.taskId,
					boxId: it.boxId,
					sourceBillNo: it.sourceBillNo,
					supplierId: it.supplierId,
					orgId: it.orgId,
					materialNumber: it.materialNumber,
					qty: it.boxMaterialQty,
					serialNumbers: it.serialNumbers,
					erpDetailId: it.erpDetailId
				};
			});
			// 节流
			if (this.requestStatus) {
				return false;
			}
			this.requestStatus = true;
			this.$api
				.post('/InStock/Shelf', {
					orgCode: this.orgCode,
					stockCode: this.warehouseCode,
					subStockCode: this.subStockCode,
					instockType:this.instockType,
					details: thedetails
				})
				.then((res) => {
					if (res.status == 200) {
						uni.showToast({
							title: '成功',
							icon: 'none',
							duration: 1000
						});
						setTimeout(() => {
							uni.navigateTo({
								url: '/pages/warehous/cgPutOnsale'
							});
						}, 200);
						// this.$router.go(0)
					}
				});
			setTimeout(() => {
				this.requestStatus = false;
			}, 1500);
		},
		// 清空二次确认
		qktkconfirm() {
			this.xhNo = '';
			this.sjNum = 0;
			this.ysjtotalNum = 0;
			this.ysjxNum = 0;
			this.qktkshow = false;
			this.boxs = [];
			this.boxstrList = [];
			this.datalist = [];
		},
		// 刪除明细信息
		deletItem(item, index) {
			// 如果删掉了当前箱子的明细数据就为0
			let idxtag = this.boxstrList.indexOf(item.boxBillNo);
			if (this.boxstrList[0] == item.boxBillNo) {
				this.sjNum = 0;
			}
			if (idxtag !== -1) {
				this.boxstrList.splice(idxtag, 1);
			}
			this.datalist.splice(index, 1);
			if (this.datalist.length == 0) {
				this.sjNum = 0;
			}
			// 从新计算箱数和上架总数量，还有是否已经完全删除的箱子
			this.setNum(this.datalist);
		},
		// 计算缓存已上架总数量 已上架箱数 已经扫描箱号集合
		setNum(list) {
			// 已上架总数量 累加
			let total = 0;
			this.ysjtotalNum = this.$util.sumObjectArrayValues(this.datalist, 'boxMaterialQty');
			// 已上架箱数 累加 （和明细挂钩）
			let thexs = [];
			thexs = list.map((item, index) => {
				return item.boxBillNo;
			});
			this.ysjxNum = Array.from(new Set(thexs)).length;
			// 如果查询的箱号正常返回数据，就缓存改箱号信息
			this.boxstrList = thexs;
			uni.setStorageSync('boxstrList', this.boxstrList);
		},
		// 普通安卓设备碘酒扫描图标扫描
		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.xhNo = '';
				this.xhNo = code.trim();
				this.getboxinfo();
			}
			// 仓位
			if (this.focusTag == 'cw') {
				this.cwNum = '';
				this.cwNum = code.trim();
				this.$refs.wselect1.inputData = code.trim();
				this.getcwList();
			}
			if (this.focusTag == 'lydd') {
				// 有些PDA会自带换行符，trim函数处理下
				this.lyOrderNo = '';
				this.lyOrderNo = code.trim();
				console.log('扫描数据', code.trim());
				this.getlyOrderSelectData(this.lyOrderNo);
			}
		},
		// 获取仓位数据
		getcwList(val) {
			console.log('123232')
			if (!val) return;
			this.$api
				.get('/SysConfig/GetSubUcStockByName', {
					name: val,
					stockCode: this.warehouseCode,
					orgCode:this.orgCode,
				})
				.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, type) {
			console.log(e,'=====================>')
			console.log(this.instockType,'===============>')
			this.subStockCode = e.code;
			// this.orgCode = e.erpOrgCode;
		},
		// 輸入失去焦點
		inputblur(val, type) {
			this.focusTag = type;
		},
		// 输入聚焦
		inputfocus(val, type) {
			this.focusTag = type;
			if (type == 'cw') {
				this.focusInput = 'cw';
			}
		},
		// 输入确认
		inputConfirm(val, type) {
			if (val) {
				this.setSMstr(val.target.value);
				if (this.focusTag == 'box') {
					// this.xhNo = val.target.value
					setTimeout(() => {
						this.getboxinfo();
					}, 20);
				}
			}
		},
		// 区分不同的扫描数据、输入数据做处理显示
		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;
			}
		},
		// 通过箱号获取对应的单据信息和列表明细信息
		getboxOrderInfo(boxBillNo) {
			const _this = this;
			this.focusInput = '';
			this.$api
				.post('/InStock/GetTaskByBox', {
					boxBillNo: boxBillNo,
					stockCode: this.warehouseCode,
					taskId: this.lyorderId,
					materialNumber: this.krcwInfo.materialNumber
				})
				.then((res) => {
					if (res.status == 200) {
						this.fid = res.data.taskId;
						this.lyOrderNo = res.data.sourceBillNo;
						// 明细数据 （每次新扫箱子物料明细信息往前添加）
						if (res.data.details && res.data.details.length > 0) {
							// 当前箱子的总数
							this.sjNum = this.$util.sumObjectArrayValues(res.data.details, 'boxMaterialQty');
							res.data.details.forEach((it) => {
								it.boxBillNo = boxBillNo;
								it.boxId = res.data.boxId;
								it.taskId = res.data.taskId;
								it.sourceBillNo = res.data.sourceBillNo;
								it.stockCode = _this.warehouseCode;
								it.subStockCode = _this.subStockCode;
								it.erpDetailId = it.erpDetailId;
								it.materialNumber = it.materialNumber;
							});
							this.datalist = res.data.details.concat(this.datalist);
							console.log('列表数据', this.datalist);
						}
						// 来源单号
						this.lyOrderNo = res.data.sourceBillNo;
						// 缓存箱号
						this.boxstrList.push(boxBillNo);
						this.setNum(this.datalist);
						uni.showToast({
							title: '获取成功',
							icon: 'none',
							duration: 1500
						});
						//保留当前输入的数据
						this.dqboxNO = boxBillNo;
						this.xhNo = boxBillNo;
						this.focusInput = 'box';
					} else {
						this.setSMinputbox();
					}
				});
		},
		// 扫描框数据重置，光标聚焦
		setSMinputbox() {
			this.focusInput = '';
			setTimeout(() => {
				this.xhNo = '';
				this.dqboxNO = '';
				this.focusInput = 'box';
				console.log('箱光标', this.focusInput);
			}, 200);
		},
		// 根据箱号查相关信息
		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.setSMinputbox();
					uni.showToast({
						title: '该箱号已扫描',
						icon: 'none',
						duration: 1000
					});
					return;
				}
				this.getboxOrderInfo(this.xhNo);
			}, 1000);
		},
		goback() {
			uni.navigateTo({
				url: '/pages/warehous/index'
			});
		}
	}
};
</script>

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

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