<template>
	<view class="page-wraper">
		<view class="">
			<com-blank-view @goScan='openScanPopup' v-if="detailSource.length==0"></com-blank-view>
		</view>

		<view class="page-wraper" v-if="detailSource.length>0">
			<view class="page-main">
				<scroll-view scroll-y="true" class="page-main-scroll">
					<view class="detail-list" v-for="(item, index) in detailSource" :key="item.id">
						<view class="">
							<record-com-detail-card :dataContent="item" @removeItem="removeItem(index,item)"
								@updateData="updateData" @removePack='updateData' :isShowToLocation="false"
								:isShowPackingNumberProps="true" :isShowFromLocation="false" :isShowParentToLocation="false">
							</record-com-detail-card>
						</view>
					</view>
					<view class="uni-flex uni-row" style="margin-left: 30rpx;margin-top: 10rpx; ">

						<text style="font-size: 35rpx; margin-right: 20rpx;">拆出数量 :</text>
						<numbeIntegerrBox :min="1" :step="1"  :max="9999999" @change="calcQty($event,splitCount)" :value="splitCount">
						</numbeIntegerrBox>
						<uom :uom="detailSource[0].uom"></uom>
					</view>
				</scroll-view>
			</view>

			<view class="page-footer">
				<view class="uni-flex u-col-center space-between padding_10"
					style="background-color:ghostwhite; width: 100%; ">
					<view class="">
					</view>
					<view class=" uni-flex uni-row">
						<button class="btn_single_commit" hover-class="btn_commit_after"
							@click="$throttle(commit,2000,this)()">提交</button>
					</view>
				</view>
			</view>

			<win-scan-button @goScan='openScanPopup'></win-scan-button>
		</view>

		<win-scan-pack ref="scanPopup" @getResult='getScanResult' headerType='HPQ,HMQ'></win-scan-pack>
		<comMessage ref="comMessage"></comMessage>
	</view>
</template>

<script>
	import {
		goHome,
		showConfirmMsg,
		getCurrDateTime
	} from '@/common/basic.js';

	import {
		splitPackageRecordForYtSubmit
	} from '@/api/request2.js';

	import {
		calc
	} from '@/common/calc.js';

	import {
		getInventoryStatusDesc,
		getDirectoryItemArray
	} from '@/common/directory.js';

	import {
		createItemInfo,
		createDetailInfo,
		calcHandleQty
	} from '@/common/record.js';

	import winScanButton from '@/mycomponents/scan/winScanButton.vue'
	import winScanPack from '@/mycomponents/scan/winScanPack.vue'
	import requiredLocation from '@/mycomponents/location/requiredLocation.vue'
	import recordComDetailCard from '@/mycomponents/record/recordComDetailCard.vue'
	import comBlankView from '@/mycomponents/common/comBlankView.vue'
	import winScanLocation from "@/mycomponents/scan/winScanLocation.vue"
	import winScanPackAndLocation from "@/mycomponents/scan/winScanPackAndLocation.vue"
	import recommendBalance from '@/mycomponents/balance/recommendBalance.vue'
	import comPackageRecord from '@/pages/package/coms/comPackageRecord.vue'
	import uom from '@/mycomponents/qty/uom.vue'
	import numberBox from '@/mycomponents/qty/numberBox.vue'
	import numbeIntegerrBox from '@/mycomponents/qty/numbeIntegerrBox.vue'

	export default {
		components: {
			winScanButton,
			winScanPack,
			requiredLocation,
			comBlankView,
			winScanLocation,
			winScanPackAndLocation,
			recommendBalance,
			recordComDetailCard,
			comPackageRecord,
			uom,
			numberBox,
			numbeIntegerrBox
		},
		data() {
			return {
				id: '',
				detailSource: [], //绑定在页面上的数据源
				fromLocationCode: "",
				toLocationCode: "",
				fromLocationAreaTypeList: [],
				inInventoryStatus: "", //目标入库库存状态
				outInventoryStatus: "", //来源出库库存状态
				businessType: {},
				dataContent: {},
				currentItemCode: "",
				toPackingNumber: "",
				itemCode: "",
				splitCount: 1,
				typeCode: "SplitPackage",
			};
		},
		onLoad(option) {
			uni.setNavigationBarTitle({
				title: option.title
			})

			this.openScanPopup();
		},
		//返回首页
		onNavigationBarButtonTap(e) {
			if (e.index === 0) {
				goHome();
			}
		},
		//拦截返回按钮事件
		onBackPress(e) {},

		onPullDownRefresh() {},

		mounted() {},
		methods: {
			openScanPopup() {
				setTimeout(res=>{
					if (this.detailSource.length > 0) {
						showConfirmMsg("拆标签信息还没提交，是否要重新扫描?", res => {
							if (res) {
								this.clearData();
								this.$refs.scanPopup.openScanPopup("");
							}
						})
					} else {
						this.$refs.scanPopup.openScanPopup("");
					}
				},100)
			},

			getScanResult(result) {
				this.setData(result);
			},

			setData(result) {
				let balance = result.balance;
				let label = result.label;
				let itemCode = result.label.itemCode
				let batch = result.label.batch;
				let pack = result.package;
				pack.qty = result.label.qty;
				pack.inventoryStatus = "OK"
				this.fromPackUnit = pack.packUnit;
				this.fromPack = pack;

				var item = this.detailSource.find(res => {
					if (res.itemCode == itemCode) {
						return res
					}
				})
				if (item == undefined) {
					if (this.itemCode != "" && this.itemCode != itemCode) {
						this.showErrorMessage("请扫描物料为【" + this.itemCode + "】的箱码")
						return;
					}
					var itemp = createItemInfo(pack, pack);
					itemp.handleQty = 0
					let newDetail = createDetailInfo(pack, pack); //
					newDetail.handleQty = 0
					newDetail.scaned = false
					newDetail.packingNumber = pack.number
					itemp.subList.push(newDetail);
					this.detailSource.push(itemp)
					this.itemCode = itemCode;
					this.closeScanPopup()
				} else {
					// var detail = item.subList.find(r => {
					// 	if (r.packingNumber == pack.packingNumber &&
					// 		r.batch == batch) {
					// 		return r;
					// 	}
					// })
					// if (detail == undefined) {
					// 	let newDetail = createDetailInfo(pack, pack);
					// 	newDetail.packingNumber=pack.number
					// 	newDetail.handleQty = 0
					// 	item.subList.push(newDetail);
					// 	this.closeScanPopup()
					// } else {
					// 	if (detail.scaned == true) {
					// 		this.showErrorMessage("箱码[" + detail.packingNumber + "批次[" + balance.batch + "]重复扫描")
					// 	}
					// }
				}
				this.calcHandleQty();
			},

			calcHandleQty() {
				calcHandleQty(this.detailSource)
				this.$forceUpdate();
			},


			showErrorMessage(message) {
				this.$refs.comMessage.showErrorMessage(message, res => {
					if (res) {

					}
				});
			},

			updateData() {
				this.calcHandleQty();
				for (var i = 0; i < this.detailSource.length; i++) {
					let item = this.detailSource[i];
					if (item.qty == 0) {
						this.detailSource.splice(i, 1)
					}
				}
			},
			removeItem(index, item) {
				this.detailSource.splice(index, 1)
			},

			closeScanPopup() {
				if (this.$refs.scanPopup != undefined) {
					this.$refs.scanPopup.closeScanPopup();
				}
			},

			scanPopupGetFocus() {
				if (this.$refs.scanPopup != undefined) {
					this.$refs.scanPopup.getfocus();
				}
			},

			commit() {
				if (this.detailSource.length > 0 && this.detailSource[0].subList.length > 0) {

					if (this.splitCount <= 0) {
						this.showErrorMessage("拆出数量必须大于0")
						return;
					}
					if (this.splitCount > this.detailSource[0].qty) {
						this.showErrorMessage("拆出数量不能大于标签数量")
						return;
					}
					uni.showLoading({
						title: "提交中....",
						mask: true
					});

					var params = this.setParams();
					console.log("提交" + JSON.stringify(params))
					splitPackageRecordForYtSubmit(params).then(res => {
						uni.hideLoading()
						if (res.data) {

							let list = []
							res.data.forEach(item => {
								list.push({
									itemCode: item.itemCode, // 物品代码
									itemName: item.itemName, // 物品名称
									packName: item.packName, // 包装名称
									packageCode: item.toPackingNumber, // 包装号
									batch: item.toBatch, //批次
									parentNumber: item.parentNumber, //父包装号
									itemType: item.itemType, //物料类型
									asnNumber: item.asnNumber, //ASN
									supplierCode: item.supplierCode, // 供应商
									qty: item.qty, // 数量
									printTimes: getCurrDateTime(), // 打印时间
									productionLineCode: item.productionLineCode, //生产线
									barcodeString: item.barcodeString, // 标签信息
									barcodeBase64: '',
								})
							})
							this.showCommitSuccessMessage("提交成功\n生成拆标签记录\n", list)

						} else {
							this.showErrorMessage("提交失败[" + res.msg + "]")
						}
					}).catch(error => {
						uni.hideLoading()
						this.showErrorMessage(error)
					})
				} else {
					this.showErrorMessage("没有要提交的数据")
				}

			},

			setParams() {
				var subList = []
				var creator = this.$store.state.user.id
				this.detailSource.forEach(item => {
					item.subList.forEach(detail => {
						var subItem = {};
						Object.assign(subItem, detail)
						subItem.itemCode = subItem.itemCode;
						subItem.itemName = detail.package.itemName;
						subItem.itemDesc1 = detail.package.itemDesc1;
						subItem.itemDesc2 = detail.package.itemDesc2;

						subItem.fromInventoryStatus = subItem.inventoryStatus;
						subItem.toInventoryStatus = subItem.inventoryStatus;

						subItem.fromQty = subItem.qty
						subItem.toQty = this.splitCount

						subItem.fromPackingNumber = subItem.packingNumber;
						subItem.toPackingNumber = subItem.packingNumber;

						subItem.fromBatch = subItem.batch;
						subItem.toBatch = subItem.batch;
						subItem.locationCode = detail.locationCode;
						subItem.package = ""
						subItem.Records = ""
						subList.push(subItem)

					})
				})

				this.dataContent.subList = subList;
				this.dataContent.creator = creator;
				return this.dataContent;
			},

			showMessage(message) {
				this.$refs.comMessage.showMessage(message, res => {
					if (res) {}
				});
			},

			showScanMessage(message) {
				this.$refs.comMessage.showScanMessage(message);
			},

			afterCloseMessage() {
				this.scanPopupGetFocus();
			},

			closeScanMessage() {
				this.scanPopupGetFocus();
			},

			showCommitSuccessMessage(hint, pointData) {
				this.$refs.comMessage.showSuccessMessage(hint, res => {
					this.clearData();
					if (pointData.length > 0) {
						uni.navigateTo({
							url: `/pages/point/index?points=${JSON.stringify(pointData)}`
						});
					}
				})
			},

			clearData() {
				this.detailSource = []
				this.fromLocationCode = '';
				this.currentItemCode = ""
				this.dataContent = {}
				this.itemCode = ""
				this.splitCount = 1
			},

			calcQty(val) {
				this.splitCount = val;
			},

		}
	}
</script>

<style scoped lang="scss">

</style>