<template>
	<view class="page-wraper">
		<view class="page-header">
			<view class="header_job_top">
				<job-top :dataContent="jobContent"></job-top>
			</view>
			<view class="header_item">
				申请单号 : {{jobContent.requestNumber}}
			</view>
			<u-line color="#D8D8D8" style="margin-bottom: 15rpx;margin-top: 10rpx;"></u-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="">
						<comInventoryDetailCard :dataContent="item" :settingParam="jobContent" @remove="updateData"
							@updateData='updateData'>
						</comInventoryDetailCard>
					</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>
				<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>
		<win-scan-pack-and-location ref="scanPopup" @getResult='getScanResult'></win-scan-pack-and-location>
		<com-message ref="comMessage"></com-message>
	</view>
</template>

<script>
	import {
		takePurchasereturnJob,
		cancleTakeTransferReceiptJob,
		submitPurchaseReturnJob,
		getInventoryMoveJobDetail,
	} from '@/api/request.js';
	import {
		getBasicLocationByCode
	} from '@/api/request2.js';
	import {
		goHome,
		getCurrDateTime,
		navigateBack,
		getPackingNumberAndBatch,
		getInventoryStatusName
	} from '@/common/basic.js';
	import {
		getDetailOption,
		getDetailRemoveOption,
		getDetailEditRemoveOption
	} from '@/common/array.js';

	import winScanButton from '@/mycomponents/scan/winScanButton.vue'
	import winScanPack from '@/mycomponents/scan/winScanPack.vue'
	import requiredLocation from '@/mycomponents/location/requiredLocation.vue'
	import comInventoryDetailCard from '@/pages/inventoryMove/coms/comInventoryDetailCard.vue'
	import comMessage from '@/mycomponents/common/comMessage.vue'
	import winScanPackAndLocation from "@/mycomponents/scan/winScanPackAndLocation.vue"
	import jobTop from '@/mycomponents/job/jobTop.vue'
	
	export default {
		name: 'returnDetail',
		components: {
			winScanButton,
			winScanPack,
			comInventoryDetailCard,
			requiredLocation,
			comMessage,
			winScanPackAndLocation,
			jobTop
		},
		data() {
			return {
				id: '',
				received: false,
				scanCount: 0,
				jobContent: {}, //任务内容
				subList: [], //接口返回的任务subList
				detailSource: [], //绑定在页面上的数据源
				toLocationInfo: {},
				businessTypeInfo: {},
				locationTypeList: [],
				managementList: [],
				
			};
		},
		onLoad(option) {
			this.id = option.id;
			// if (this.id != undefined) {
			// 	//新建的任务自动接收
			// 	if (option.status == "JOB_PENDING") {
			// 		this.receive((callback => {
			// 			this.received = true;
			// 			this.getDetail();
			// 		}));
			// 	} else {
			this.getDetail();
			// 	}
			// }
		},
		//返回首页
		onNavigationBarButtonTap(e) {
			if (e.index === 0) {
				goHome();
			}
		},

		onBackPress(e) {
			//已经接收但是没提交任务
			if (e.from == 'backbutton') {
				if (this.received) {
					//取消承接任务	
					cancleTakeTransferReceiptJob(this.id).then(res => {
						uni.navigateBack();
					}).catch(error => {
						uni.navigateBack();
					})
				} else {
					uni.navigateBack();
				}

				return true;
			}

		},

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

		mounted() {

		},
		methods: {
			//接收
			receive(callback) {
				uni.showLoading({
					title: "加载中....",
					mask: true
				});
				if (this.id != null) {
					takePurchasereturnJob(this.id).then(res => {
						uni.hideLoading();
						callback();
					}).catch(error => {
						uni.hideLoading();
						this.showErrorMessage(error)
					})
				}
			},

			getDetail() {
				var that = this;
				uni.showLoading({
					title: "加载中....",
					mask: true
				});

				getInventoryMoveJobDetail(that.id).then(res => {
					uni.hideLoading();
					if (res.data[0].subList.length > 0) {
						that.jobContent = res.data[0];
						that.subList = res.data[0].subList;
						that.detailSource = that.getDataSource(that.subList)
					} else {
						that.showMessage('列表数据为0');
					}
				}).catch(error => {
					uni.hideLoading()
					this.showErrorMessage(error)
				})

			},

			getDataSource(subList) {
				let items = [];
				subList.forEach(detail => {
					var item = items.find(r =>
						r.itemCode == detail.itemCode)
					if (item == undefined) {
						item = this.createItemInfo(detail);
						let newDetail = this.createDetailInfo(detail); //
						item.subList.push(newDetail);
						items.push(item)
					} else {
						item.qty += detail.qty
						let newDetail = this.createDetailInfo(detail); //
						item.subList.push(newDetail);
					}
				})
				return items;
			},

			createItemInfo(res) {
				let item = {
					itemCode: res.itemCode,
					itemName: res.itemName,
					stdPackQty: res.stdPackQty,
					stdPackUnit: res.stdPackUnit,
					qty: res.qty,
					handleQty: 0,
					uom: res.uom,
					subList: []
				}
				return item;
			},

			createDetailInfo(data) {
				data.scaned = false;
				// data.record = {};
				let detail = data;
				return detail;
			},

			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 = 0;
					for (let detail of item.subList) {
						if (detail.record != undefined) {
							item.handleQty += Number(detail.record.qty)
						}
					}
				}
				this.continueScan()
				this.$forceUpdate();
			},


			//继续扫描
			continueScan() {
				this.scanCount = this.getScanCount();
				if (this.scanCount == this.subList.length) {
					this.closeScanPopup();
				} else {
					this.scanPopupGetFocus();
				}
			},

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

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

			openScanPopup() {
				let fromlocationCode = '';
				let fromlocationList = [];
				for (var i = 0; i < this.detailSource.length; i++) {
					let item = this.detailSource[i];
					item.subList.forEach(l => {
						//重复的库位不往里面插入
						var location = fromlocationList.find(res => res == l.fromLocationCode)
						if (location == undefined) {
							fromlocationList.push(l.fromLocationCode);
						}
						//来源库位赋默认值
						if (fromlocationCode == '') {
							if (!l.scaned) {
								fromlocationCode = l.fromLocationCode;
							}
						}
					})
				}
				this.$refs.scanPopup.openScanPopupForJob(fromlocationCode, fromlocationList, this.jobContent);
			},


			getScanResult(result) {
				try {
					var packingNumber = result.label.packingNumber;
					var batch = result.label.batch;
					var qty = result.label.qty;
					var itemCode = result.label.itemCode;
					var detail = this.detailSource.find(r => r.itemCode == itemCode);
					if (detail == undefined) {
						this.showMessage("物料号【" + itemCode + "】不在列表中")
					} else {
						var itemDetail = detail.subList.find(r => {
							return r.packingNumber == packingNumber &&
								r.batch == batch
						})
						if (itemDetail == undefined) {
							this.showErrorMessage("箱码[" + packingNumber + "]" + "批次[" + batch + "]不在列表中")
						} else {
							if (itemDetail.scaned) {
								this.showMessage("箱码【" + packingNumber + "】已经扫描")
							} else {
								let balanceStatus = getInventoryStatusName(result.balance.inventoryStatus);
								let itemStatus = getInventoryStatusName(itemDetail.inventoryStatus);
								if (itemDetail.inventoryStatus != result.balance.inventoryStatus) {
									if(this.jobContent.allowModifyInventoryStatus=="TRUE"){
										this.showQuestionMessage('实际库存状态[' + balanceStatus + ']与推荐库存状态[' + itemStatus +
											']不一致,是否继续上架?', res => {
												if (res) {
													itemDetail.scaned = true;
													itemDetail.record = this.createRecordInfo(itemDetail, result.balance);
													this.calcHandleQty();
												} else {
													this.scanPopupGetFocus();
												}
											});
									}else {
										this.showQuestionMessage('任务中不允许修改库存状态,实际库存状态[' + balanceStatus + ']与推荐库存状态[' + itemStatus +
											']不一致,不允许转移!', res => {
												this.scanPopupGetFocus();
											});
									}
									
								} else {
									itemDetail.scaned = true;
									itemDetail.record = this.createRecordInfo(itemDetail, result.balance);
									this.calcHandleQty();
								}
							}
						}
					}
					this.scanPopupGetFocus();
				} catch (e) {
					this.showErrorMessage(e.message);
				}
			},

			createRecordInfo(detail, balance) {
				var record = {}
				detail.scaned = true;
				detail.balance = balance;
				detail.RecommendInventoryStatus = detail.inventoryStatus;
				detail.inventoryStatus = balance.inventoryStatus;
				// let record = JSON.parse(JSON.stringify(detail));
				//克隆对象，深度克隆，防止双向绑定同一个变量
				Object.assign(record, detail)
				record.qty = Number(balance.qty);
				return record;
			},

			async commit() {
				//允许部分提交
				if (this.jobContent.allowPartialComplete == "TRUE") {
					this.submitJob();
				} else {
					this.scanCount = this.getScanCount();
					if (this.scanCount < this.subList.length) {
						this.$refs.comMessage.showErrorMessage('请完成扫描后,再进行提交<br>' + "已经扫描[" + this.scanCount +
							"]箱总共[" + this
							.subList.length + "]箱", res => {
								if (res) {
									this.openScanPopup();
								}
							});
					} else {
						this.submitJob();
					}
				}
			},

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

				var itemCodes = []
				this.detailSource.forEach(item => {
					itemCodes.push(item.itemCode)
				})

				var param = {
					itemCode: itemCodes,
					locationCode: this.toLocationCode
				}
				// this.managementList = await getManagementPrecisions(param);

				var params = this.setParams();
				console.log("提交" + JSON.stringify(params))
				submitPurchaseReturnJob(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)
				})
			},


			setParams() {
				var params = {
					requestNumber: this.jobContent.requestNumber,
					jobNumber: '',
					asnNumber: this.jobContent.asnNumber,
					ppNumber: this.jobContent.ppNumber,
					supplierCode: this.jobContent.supplierCode,
					carrierCode: this.jobContent.carrierCode,
					transferMode: this.jobContent.transferMode,
					vehiclePlateNumber: this.jobContent.vehiclePlateNumber,
					fromWarehouseCode: this.jobContent.fromWarehouseCode,
					fromLocationTypes: this.jobContent.fromLocationTypes,
					fromAreaCodes: this.jobContent.fromAreaCodes,
					toWarehouseCode: this.jobContent.toWarehouseCode,
					toLocationTypes: this.jobContent.toLocationTypes,
					status: this.jobContent.status,
					toAreaCodes: this.jobContent.toAreaCodes,
					executeTime: getCurrDateTime(),
					activeDate: getCurrDateTime(),
					available: 1, //是否可用 0不可用,1可用
					requestTime: this.jobContent.requestTime,
					dueTime: getCurrDateTime(),
					expiredTime: this.jobContent.expiredTime,
					departmentCode: this.jobContent.departmentCode,
					interfaceType: "jklxPURCHASE_RETURN", //接口类型
					Number: this.jobContent.Number,
					businessType: this.jobContent.businessType,
					remark: this.jobContent.remark,
					creationTime: this.jobContent.creationTime,
					creatorId: this.jobContent.creatorId,
					creatorName: this.jobContent.creatorName,
					extraProperties: this.jobContent.extraProperties,
					siteId: this.jobContent.siteId,
					Code: "",
					subList: [],

				}

				this.detailSource.forEach(item => {
					item.subList.forEach(detail => {
						if (detail.scaned) {
							detail.record.fromPackingNumber = detail.record.packingNumber
							detail.record.toPackingNumber = detail.record.packingNumber
							detail.record.fromBatch = detail.record.batch
							detail.record.ToBatch = detail.record.batch;
							detail.record.FromContainerNumber = detail.record.ContainerNumber
							detail.record.ToContainerNumber = ""
							detail.record.FromLocationGroupCode = ""
							detail.record.FromAreaCode = ""
							detail.record.ToLocationGroupCode = "";
							detail.record.ToAreaCode = "";
							detail.record.VisualInspectResult = "",
								detail.record.VisualInspectPhotos = "",
								detail.record.FailedReason = ""
							detail.record.SinglePrice = "",
								detail.record.Amount = "",
								detail.record.JobDetailID = detail.record.id,
								detail.record.masterID = this.jobContent.id,
								detail.record.projectCode = "",
								detail.record.Code = ""
							detail.record.interfaceType = "jklxPURCHASE_RETURN"
							params.subList.push(detail.record)
						}
					})
				})

				return params;
			},

			getLocationInfo(locationCode) {
				getBasicLocationByCode(locationCode).then(res => {
					if (res.data.list.length > 0) {
						this.toLocationInfo = res.data.list[0]
					}
				})
			},

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

			showQuestionMessage(message, callback) {
				setTimeout(r => {
					this.scanPopupLoseFocus();
					this.$refs.comMessage.showQuestionMessage(message, res => {
						if (res) {
							callback(res);
						}
					});
				})
			},


			scanPopupGetFocus() {
				this.$refs.scanPopup.packGetFocus();
			},

			scanPopupLoseFocus() {
				this.$refs.scanPopup.packLoseFocus();
			},

			closeScanPopup() {
				this.$refs.scanPopup.closeScanPopup();
			},

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

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

			/**
			 * BlobUrl转blob数据  
			 * @param {Object} url blob URL
			 * @param {Object} callback 回调函数
			 */
			objectURLToBlob(url, callback) {
				const http = new XMLHttpRequest();
				http.open("GET", url, true);
				http.responseType = "blob";
				http.onload = function(e) {
					if (this.status == 200 || this.status === 0) {
						callback(this.response);
					}
				};
				http.send();
			},


			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>
