<template>
	<view class="page-wraper">
		<view class="">
			<com-blank-view @goScan='showFromLocationPopup' v-if="fromLocationCode==''"></com-blank-view>
		</view>
		<view class="page-wraper" v-if="fromLocationCode!=''">
			<requiredLocation title="盘点库位" :locationCode="fromLocationCode"
				:isShowEdit="jobContent.allowModifyLocation==1" @getLocation='scanLocationCode'
				:locationTypeList="locationTypeList"></requiredLocation>
			<u-line></u-line>
			<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="">
							<com-count-detail-card :dataContent="item" :index="index" :settingParam="jobContent"
								@removeItem="removeItem(index,item)" @updateData="updateData" @removePack="removePack"
								@editItem="editItem">
							</com-count-detail-card>
						</view>
						<u-line />
					</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="commit">提交</button>
					</view>
				</view>
			</view>
			<win-scan-button @goScan='openScanPopup'></win-scan-button>
		</view>

		<win-scan-pack-and-location ref="scanPopup" @getResult='getScanResult'></win-scan-pack-and-location>
		<win-scan-location ref="scanFromLocationCode" title="盘点库位" @getLocation='getLocation'
			:locationTypeList="fromLocationTypeArray"></win-scan-location>
		<count-qty-edit ref="countQtyEdit" @confirm="editConfirm" :isShowStatus="true" :allowEditStatus="true">
		</count-qty-edit>
		<comMessage ref="comMessage"></comMessage>
	</view>
</template>

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

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

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

	import {
		getBusinessType,
	} from '@/common/record.js';

	import {
		balanceByLocation
	} from '@/common/balance.js';

	import winScanButton from '@/mycomponents/scan/winScanButton.vue'
	import winScanPack from '@/mycomponents/scan/winScanPack.vue'
	import requiredLocation from '@/mycomponents/location/requiredLocation.vue'
	import comCountDetailCard from '@/pages/count/coms/comCountDetailCard.vue'
	import comBlankView from '@/mycomponents/common/comBlankView.vue'
	import winScanPackAndLocation from "@/mycomponents/scan/winScanPackAndLocation.vue"
	import winScanLocation from "@/mycomponents/scan/winScanLocation.vue"
	import countQtyEdit from "@/mycomponents/qty/countQtyEdit.vue"

	export default {
		name: 'receipt_detail',
		components: {
			winScanButton,
			winScanPack,
			comCountDetailCard,
			requiredLocation,
			comBlankView,
			winScanPackAndLocation,
			winScanLocation,
			countQtyEdit
		},
		data() {
			return {
				id: '',
				receiptJob: {},
				received: false,
				isShowPackingCode: true,
				scanCount: 0,
				jobContent: {}, //任务内容
				subList: [], //接口返回的任务subList
				detailSource: [], //绑定在页面上的数据源
				locationTypeList: [],
				toLocationInfo: {},
				businessTypeInfo: {},
				fromLocationTypeArray: [],
				toLocationTypeArray: [],
				fromLocationInfo: {},
				fromLocationCode: "",
				businessType: {},
				itemEditInfo: {}
			};
		},
		onLoad(option) {
			var typeCode = "Count"
			getBusinessType(typeCode, res => {
				if (res.success) {
					this.businessType = res.businessType;
					this.fromlocationTypeList = res.fromlocationTypeList;
					this.tolocationTypeList = res.tolocationTypeList;
					this.showFromLocationPopup();
				} else {
					this.showErrorMessage(res.message)
				}
			});

		},
		//返回首页
		onNavigationBarButtonTap(e) {
			if (e.index === 0) {
				goHome();
			}
		},
		//拦截返回按钮事件
		onBackPress(e) {
			//已经接收但是没提交任务
		},

		onPullDownRefresh() {
			uni.stopPullDownRefresh();
		},

		mounted() {},
		methods: {
			calcScanCount(closeScan) {
				let items = this.subList.filter(r => {
					if (r.scaned) {
						return r;
					}
				})
				this.scanCount = items != null ? items.length : 0;
				if (this.scanCount == this.subList.length) {
					this.closeScanPopup();
				}
			},

			calcHandleQty() {
				for (let item of this.detailSource) {
					item.handleQty = new Decimal(0).toNumber();
					item.qty = new Decimal(0).toNumber();
					for (let detail of item.subList) {
						if(detail!=undefined){
							if(detail.scaned){
								item.handleQty = calc.add(item.handleQty,detail.handleQty);
							}
							item.qty = calc.add(item.qty,detail.qty); 
						}
					}
				}
				this.$forceUpdate();
			},
			selectedItem(item) {
				if (item.locationCode != this.fromLocationCode) {
					this.showErrorMessage("来源库位[" + this.fromLocationCode + "]无库存")
					return;
				}
			},
			openScanPopup() {
				if (this.fromLocationCode == "") {
					this.showFromLocationPopup();
					return
				}
				this.$refs.scanPopup.openScanPopupForType(this.fromLocationCode, this.businessType);
			},

			showFromLocationPopup() {
				this.$nextTick(() => {
					this.$refs.scanFromLocationCode.openScanPopup();
				})

			},

			getLocation(location) {
				this.getfromLocationCode(location)
			},

			getfromLocationCode(location) {
				this.fromLocationInfo = location;
				this.fromLocationCode = location.code;

				//查询库位下的库存
				balanceByLocation(this.fromLocationCode, res => {
					this.subList = res.data.list;
					this.detailSource = getDataSource(this.subList);

				});
			},

			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();
			},

			removeItem(index, item) {
				this.detailSource.splice(index, 1)
			},

			updateData() {
				this.calcHandleQty();
			},

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

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

			getScanResult(result) {
				try {
					var packingNumber = result.balance.packingNumber;
					var batch = result.balance.batch;
					var qty = result.balance.qty;
					var itemCode = result.balance.itemCode;
					var inventoryStatus = result.balance.inventoryStatus;
					var detail = this.detailSource.find(r => r.itemCode == itemCode);
					//检查物料号是否存在
					if (detail == undefined) {
						//物料号不存在，创建物料号数据添加到列表。设置为已经扫描
						this.addNewItemCodeToList(result)
					} else {
						//物料号存在，查询是否在任务列表中

						this.itemEditInfo = detail.subList.find(item => {
							if (item.packingNumber == packingNumber &&
								item.batch == batch &&
								item.inventoryStatus == inventoryStatus) {
								return item;
							}
						})

						if (this.itemEditInfo == undefined) {
							//不在任务列表中，提示是否添加到列表
							this.addExistItemCodeToList();
						} else {
							//在列表中，更新已扫描状态，
							if (this.itemEditInfo.scaned) {
								this.$refs.comMessage.showSelectMessageModal("箱码【" + packingNumber + "】已经完成盘点,是否要编辑数量",
									res => {
										if (res) {
											this.$refs.countQtyEdit.openEditPopup(this.itemEditInfo,
												detail.subList);
										} else {
											this.scanPopupGetFocus();
										}
									})
							} else {
								this.itemEditInfo.scaned = true;
								this.itemEditInfo.packQty = result.package.packQty;
								this.itemEditInfo.packUnit = result.package.packUnit;
								this.itemEditInfo.record = this.createRecordInfo(this.itemEditInfo, result.balance);
								this.$refs.countQtyEdit.openEditPopupShowSeconds(this.itemEditInfo);
								this.calcHandleQty();
							}
						}
					}
				} catch (e) {
					this.showErrorMessage(e.message)
				}
			},

			addNewItemCodeToList(result) {
				var item = this.createAddItemInfo(result.balance, result.package);
				let newDetail = this.createAddDetailInfo(result.balance, result.package); //
				item.subList.push(newDetail);
				this.detailSource.push(item)
			},

			createRecordInfo(detail, balance) {
				var record = {}
				detail.scaned = true;
				detail.balanceQty = Number(balance.qty);
				detail.inventoryStatus = balance.inventoryStatus;
				// let record = JSON.parse(JSON.stringify(detail));
				//克隆对象，深度克隆，防止双向绑定同一个变量
				Object.assign(record, detail)
				record.fromLocationCode = this.fromLocationCode;
				return record;
			},
			addExistItemCodeToList(detail, result) {
				detail.qty = calc.add(detail.qty,detail.qty)
				let newDetail = this.createAddDetailInfo(result.balance, result.package); //
				detail.subList.push(newDetail);
			},

			createAddItemInfo(balance, pack) {
				let item = {
					itemCode: balance.itemCode,
					itemName: pack.itemName,
					packQty: pack.packQty,
					packUnit: pack.packUnit,
					qty: balance.qty,
					handleQty: 0,
					uom: pack.uom,
					subList: []
				}
				return item;
			},

			createAddDetailInfo(balance, pack) {
				var detail = {
					scaned: true,
					balanceQty: balance.qty,
					toInventoryStatus: balance.inventoryStatus,
					fromLocationCode: balance.locationCode,
					id: "",
					countDetailNumber: "",
					ownerCode: balance.OwnerCode,
					packingNumber: balance.packingNumber,
					containerNumber: pack.containerNumber,
					batch: balance.batch,
					inventoryStatus: balance.inventoryStatus,
					itemCode: balance.itemCode,
					itemName: pack.itemName,
					itemDesc1: pack.itemDesc1,
					itemDesc2: pack.itemDesc2,
					projectCode: "",
					qty: balance.qty,
					uom: balance.uom,
					masterID: "",
					Number: "",
					remark: "",
					creationTime: "",
					creatorId: "",
					creatorName: "",
					siteId: ""
				}

				return detail;
			},

			editItem(val) {
				var detail = this.detailSource.find(r => r.itemCode == val.itemCode);
				this.$refs.countQtyEdit.openEditPopup(val,
					detail.subList);
			},

			editConfirm() {
				this.calcHandleQty();
				this.scanPopupGetFocus();
			},

			scanLocationCode(location, code) {
				this.$refs.comMessage.showQuestionMessage("是否把所有的目标库位都变成默认库位[" + code + "]", res => {
					this.toLocationCode = code
					this.detailSource.forEach(item => {
						item.subList.forEach(detail => {
							detail.toLocationCode = code
						})
					})
				})

			},

			commit() {
				if (this.fromLocationCode == "") {
					this.showMessage("请先选择目标库位")
					return;
				}
				//允许部分提交
				if (this.jobContent.allowPartialComplete == "TRUE") {
					uni.showLoading({
						title: "提交中....",
						mask: true
					});

					var params = this.setParams();
					console.log("提交" + JSON.stringify(params))
					// (this.id, params).then(res => {
					// 	uni.hideLoading()
					// 	if (res.data) {
					// 		var hint = res.data.Number;
					// 		this.showCommitSuccessMessage("提交成功" + hint, )

					// 	} else {
					// 		this.showErrorMessage("提交失败[" + res.msg + "]")
					// 	}
					// }).catch(error => {
					// 	uni.hideLoading()
					// 	this.showErrorMessage(error)
					// })
				} else {
					this.calcScanCount();
					if (this.scanCount < this.subList.length) {
						this.showMessage('请完成扫描后,再进行提交<br>' + "已经扫描[" + this.scanCount + "]总共[" + this.subList.length +
							"]");
					}
				}

			},

			setParams() {
				var params = {
					requestNumber: this.jobContent.requestNumber,
					jobNumber: "",
					asnNumber: this.jobContent.asnNumber,
					ppNumber: this.jobContent.ppNumber,
					supplierCode: this.jobContent.supplierCode,
					receiptDock: this.jobContent.receiptDock,
					carrierCode: this.jobContent.carrierCode,
					transferMode: this.jobContent.transferMode,
					vehiclePlateNumber: this.jobContent.vehiclePlateNumber,
					fromWarehouseCode: this.toLocationInfo.WarehouseCode,
					toWarehouseCode: this.toLocationInfo.warehouseCode,
					outTransaction: this.businessTypeInfo.outTransactionType, //出库事务类型
					inTransaction: this.businessTypeInfo.inTransactionType, //入库事务类型
					executeTime: "2023-08-4 16:30:11", //执行时间
					activeDate: "2023-08-4 16:30:11", //生效时间
					available: "1", //是否可用 0不可用,1可用
					requestTime: this.jobContent.requestTime,
					dueTime: "2023-08-4 16:30:11", //截止时间
					departmentCode: this.jobContent.departmentCode,
					userPositionCode: "", //岗位
					interfaceType: "jklxPURCHASE_RECEIPT", //接口类型
					number: this.jobContent.number,
					businessType: this.jobContent.businessType,
					remark: this.jobContent.remark,
					creationTime: this.jobContent.creationTime,
					creatorld: this.jobContent.creatorld,
					creatorName: this.jobContent.creatorName,
					extraProperties: this.jobContent.extraProperties,
					siteld: this.jobContent.siteld,
					code: "",
					subList: [

					],
				}

				this.detailSource.forEach(res => {
					res.subList.forEach(res1 => {
						if (res1.scaned) {
							res1.FromLocationGroupCode = "";
							res1.FromAreaCode = "";
							res1.ToLocationGroupCode = this.toLocationInfo.LocationGroupCode;
							res1.ToAreaCode = this.toLocationInfo.AreaCode;
							res1.VisualInspectResult = ""; //目检结果
							res1.VisualInspectPhotos = ""; //目检照片
							res1.FailedReason = ""; //不合格原因
							res1.MassDefect = ""; //质量缺陷
							res1.SinglePrice = ""; //单价
							res1.Amount = ""; //金额
							res1.Code = "";
							res1.JobDetailID = res1.id;
							res1.interfaceType = "jklxPURCHASE_RECEIPT";
							params.subList.push(res1)
						}
					})
				})

				return params;
			},

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

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

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

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

			showCommitSuccessMessage(hint) {
				this.$refs.comMessage.showSuccessMessage(hint, res => {
					navigateBack(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>
