
<template>
	<view class="page-wraper">
		<view class="">
			<com-blank-view @goScan='getBusinessType' v-if="detailSource.length==0"></com-blank-view>
		</view>
		<view class="page-wraper" v-if="detailSource.length>0">
			<view class="cen_card" style="background-color: #fff; margin:10px 0px 0px 10px;">
				<view class="cell_box uni-flex uni-row">
					<view class="cell_info">
						<view class="text_lightblue">库位</view>
						<view>{{fromLocationCode}}</view>
					</view>
					<view class="cell_info">
						<view class="text_lightblue">包装规格</view>
						<view>{{getPackUnitName(fromPack.packUnit)}}</view>
					</view>
					<view class="cell_info">
						<view class="text_lightblue">包装数量</view>
						<view>{{fromPack.packQty}}{{getUomInfo(fromPack.uom)}}</view>
					</view>
				</view>
			</view>
			<view class="split_line"></view>
			<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" :index="index"
								@removeItem="removeItem(index,item)" @updateData="updateData" @removePack="removePack"
								:isShowFromLocation="false" :isShowToLocation="false">
							</record-com-detail-card>
						</view>
						<view class='split_line'></view>
					</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 class="uni-flex uni-row">
							<text>目标包装规格:</text>
							<view class="uni-flex u-col-center uni-row" @click="showPackage">
								<view class="" style="margin-left: 5rpx;width: 100%;">
									{{toPackUnitShow}}
								</view>
								<u-select v-model="show" mode="single-column" :list="packageList"
									@confirm="confirmSelect">
								</u-select>
							</view>
						</view>

					</view>
					<view class=" uni-flex uni-row">
						<button class="btn_single_commit" hover-class="btn_commit_after" @click="commit">提交</button>
					</view>
				</view>
			</view>
			<win-scan-button @goScan='openScanPopup'></win-scan-button>
		</view>

		<winComScanBalance ref="scanPopup" @getBalance='getScanResult' bussinessCode="OverPackage">
		</winComScanBalance>


		<!-- <win-scan-location ref="scanLocationCode" title="来源库位" @getLocation='getLocation'
			:locationAreaTypeList="fromLocationAreaTypeList"></win-scan-location> -->
		<comMessage ref="comMessage"></comMessage>
	</view>
</template>

<script>
	import {
		overPackageRecordSubmit,
		getPackUnitByItemCode,
		getBalanceByParams
	} from '@/api/request2.js';
	import {
		deepCopyData,
		goHome
	} from '@/common/basic.js';

	import {
		getInventoryStatusDesc,
		getLocationAreaTypeName,
		getLocationAreaTypeInfo,
		getListLocationAreaTypeDesc,
		getDirectoryItemArray,
		getPackUnitName,
		getUomInfo
	} from '@/common/directory.js';

	import {
		getBusinessType,
		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 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 packageTarget from '@/mycomponents/package/packageTarget.vue'
	import recordComDetailCard from '@/mycomponents/record/recordComDetailCard.vue'
	import packUnit from '@/mycomponents/qty/packUnit.vue'
	import winComScanBalance from '@/mycomponents/scan/winComScanBalance.vue'


	import {
		getCurrDateTime
	} from '@/common/basic.js';

	export default {
		components: {
			winScanButton,
			winScanPack,
			requiredLocation,
			comBlankView,
			winScanLocation,
			winScanPackAndLocation,
			recommendBalance,
			packageTarget,
			recordComDetailCard,
			packUnit,
			winComScanBalance
		},
		onLoad(option){
			uni.setNavigationBarTitle({
				title: option.title
			})
		},
		data() {
			return {
				id: '',
				scanCount: 0,
				detailSource: [], //绑定在页面上的数据源
				fromLocationCode: "",
				isShowLocation: false,
				fromLocationAreaTypeList: [],
				fromInventoryStatuses: [],
				inInventoryStatus: "", //目标入库库存状态
				outInventoryStatus: "", //来源出库库存状态
				businessType: {},
				dataContent: {},
				fromPackUnit: "",
				fromPack: {},
				packageList: [],
				show: false,
				toPackUnitShow: "请选择",
				toPackQty: "",
				itemCode: "",
				resultData: {}
			};
		},
		onLoad() {
			this.getBusinessType();
		},
		//返回首页
		onNavigationBarButtonTap(e) {
			if (e.index === 0) {
				goHome();
			}
		},
		//拦截返回按钮事件
		onBackPress(e) {},

		onPullDownRefresh() {},

		mounted() {},

		methods: {
			getBusinessType(){
				var typeCode = "OverPackage"
				getBusinessType(typeCode, res => {
					if (res.success) {
						this.businessType=res.businessType;
						this.fromInventoryStatuses = getDirectoryItemArray(res.fromInventoryStatuses);
						this.fromLocationAreaTypeList = res.fromLocationAreaTypeList
						this.openScanPopup();
					} else {
						this.showErrorMessage(res.message)
					}
				});
			},
			getUomInfo(uom) {
				let item = getUomInfo(uom);
				if (item == '') {
					return uom;
				} else {
					return item.label
				}
			},
			showPackage() {
				getPackUnitByItemCode(this.itemCode).then(res => {
					if (res.data != null && res.data.list.length > 0) {
						res.data.list.forEach(item => {
							// item.value = item.packQty;
							item.value = item.packUnit;
							item.label = this.getPackUnitName(item.packUnit) + "(" + item.packQty + this
								.getUomInfo(item.uom) + ")";
							item.data = 'a';
						})
						this.packageList = res.data.list
						this.show = true;
					} else {
						this.showErrorMessage("未查找到包装规格");
					}

				}).catch(error => {
					this.showErrorMessage("未查找到包装规格" + error);
				})
			},
			confirmSelect(e) {
				if (this.fromPackUnit == e[0].label) {
					this.showErrorMessage("来源包装规格【" + this.fromPackUnit + "】与目标包装规格【" + e[0].label + "】不能相等")
					return
				}
				// var toPackUnit = e[0].label.split("(")[0]
				// this.toPackUnit = toPackUnit
				// this.toPackQty = e[0].value
				this.toPackUnit = e[0].value
				let pack = this.packageList.filter(r => r.packUnit == this.toPackUnit)[0];
				this.toPackQty = pack.packQty;
				this.toPackUnitShow = e[0].label
			},
			//修改库位
			handleConfirm(fromLocationCode) {
				this.$refs.scanLocationCode.openScanPopupSimulate(fromLocationCode)
			},
			getScanResult(result) {
				this.setData(result);
			},

			setData(result) {
				let balance = result.balance;
				let label = result.label;
				let pack = result.package;
				this.fromPackUnit = pack.packUnit;
				this.fromPack = pack;
				if(this.fromLocationCode&&this.fromLocationCode!=balance.locationCode){
					this.showErrorMessage("箱码[" + balance.packingNumber + "批次[" + balance.batch + "]在库位["+this.fromLocationCode+"]没有库存余额")
					return;
				}
				
				var item = this.detailSource.find(res => {
					if (res.itemCode == balance.itemCode) {
						return res
					}
				})
				if (item == undefined) {
					if (this.itemCode != "" && this.itemCode != balance.itemCode) {
						this.showErrorMessage("请扫描物料为【" + this.itemCode + "】的箱码")
						return;
					}
					var itemp = createItemInfo(balance, pack);
					let newDetail = createDetailInfo(balance, pack); //
					if(balance.lableQty){
						newDetail.handleQty =balance.lableQty
					}
					newDetail.parentNumber =pack.parentNumber;
					newDetail.packingNumber =pack.number
					itemp.subList.push(newDetail);
					this.detailSource.push(itemp)
					this.itemCode = balance.itemCode;
					this.fromLocationCode =balance.locationCode
					this.scanPopupGetFocus()
				} else {
					var detail = item.subList.find(r => {
						if (r.packingNumber == pack.number &&
							r.batch == balance.batch &&
							r.locationCode == balance.locationCode &&
							r.inventoryStatus == balance.inventoryStatus) {
							return r;
						}
					})
					if (detail == undefined) {
						let newDetail = createDetailInfo(balance, pack);
						if(balance.lableQty){
							newDetail.handleQty =balance.lableQty
						}
						newDetail.parentNumber =pack.parentNumber;
						newDetail.packingNumber =pack.number
						item.subList.push(newDetail);
						this.scanPopupGetFocus()
					} 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) {
						this.scanPopupGetFocus()
					}
				});
			},

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

			openScanPopup() {
				if(this.businessType){
					this.$refs.scanPopup.openScanPopup(this.businessType);
				}else {
					this.getBusinessType()
				}
				
			},
			closeScanPopup() {
				if (this.$refs.scanPopup) {
					this.$refs.scanPopup.closeScanPopup();
				}
			},

			scanPopupGetFocus() {
				if (this.$refs.scanPopup) {
					this.$refs.scanPopup.getfocus();
				}
			},
			commit() {
				if (this.detailSource.length > 0 && this.detailSource[0].subList.length > 0) {
					if (!this.toPackUnit || this.toPackUnit == "包装规格") {
						this.showErrorMessage("请选择目标包装规格")
						return;
					}
					this.checkSubmit();

				} else {
					this.showErrorMessage("没有要扫描的数据")
				}
			},

			checkSubmit() {
				
				// this.submitJob()
				var tempHandleQty =0
				this.detailSource.forEach(res=>{
					tempHandleQty =tempHandleQty+res.handleQty
				})
				var toPackQty = this.toPackQty;
				//包装提示
				if (tempHandleQty % toPackQty > 0) {
					// var count = Math.ceil(tempHandleQty / toPackQty);
					this.$refs.comMessage.showQuestionMessage("扫描数量【" + tempHandleQty +
						"】,将有1个非整包,是否提交?", res => {
							if (res) {
								this.submitJob()
							}
						});
				} else {
					this.submitJob()
				}
			},

			submitJob() {
				uni.showLoading({
					title: "提交中....",
					mask: true
				});

				var params = this.setParams();
				console.log("提交" + JSON.stringify(params))
				overPackageRecordSubmit(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("提交成功<br>生成翻包记录<br>", list)
					} else {
						this.showErrorMessage("提交失败[" + res.msg + "]")
					}
				}).catch(error => {
					uni.hideLoading()
					this.showErrorMessage(error)
				})

			},

			setParams() {

				var subList = []
				var creator = this.$store.state.user.id
				this.detailSource.forEach(item => {
					item.subList.forEach(detail => {
						if (detail.scaned) {
							var subItem = deepCopyData(detail);
							subItem.itemCode = detail.itemCode;
							subItem.itemName = detail.package.itemName;
							subItem.itemDesc1 = detail.package.itemDesc1;
							subItem.itemDesc2 = detail.package.itemDesc2;
							
							subItem.fromInventoryStatus = detail.inventoryStatus;
							subItem.fromQty = detail.handleQty
							subItem.fromParentPackingNumber =detail.parentNumber;
							subItem.fromPackingNumber = detail.packingNumber;
							subItem.fromBatch = detail.batch;
							subItem.fromLocationCode = detail.locationCode;
							subItem.fromPackUnit = detail.packUnit;
							subItem.fromPackQty = detail.packQty;

							subItem.toPackQty = this.toPackQty;
							subItem.toPackUnit = this.toPackUnit;
							subItem.package = ""
							subList.push(subItem)
						}
					})
				})
				this.dataContent.subList = subList;
				this.dataContent.creator = creator;
				return this.dataContent;
			},

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

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

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

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

			showCommitSuccessMessage(hint, pointData) {
				this.$refs.comMessage.showSuccessMessage(hint, res => {
					this.detailSource = []
					this.fromLocationCode = '';
					this.dataContent = {}
					this.itemCode=""
					this.toPackUnitShow ="请选择"
					this.toPackQty = ""
					if (pointData.length > 0) {
						uni.navigateTo({
							url: `/pages/point/index?points=${JSON.stringify(pointData)}`
						});
					}

				})
			},

			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)
					}
				}
			},
		}
	}
</script>

<style scoped lang="scss">
	page {
		width: 100%;
		height: 100%;
		background-color: #fff;
	}

	.page-wraper {
		display: flex;
		flex-direction: column;
		width: 100%;
		height: 100%;
	}


	.page-main {
		flex: 1;
		position: relative;
	}

	.page-main-scroll {
		position: absolute;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
	}

	.page-main-list {
		/*  height: 80rpx;
	    line-height: 80rpx; */
		text-align: center;
		background: #e0e0e0;

	}
</style>