<template>
	<view class="page-wraper">
		<view class="page-header">
			<view class="header-view">
				<view class="header_job_top">
					<job-top :dataContent="jobContent"></job-top>
				</view>
				<view class="cen_card" style="padding: 5rpx;">
					<view class="cell_box uni-flex uni-row">
						<view class="cell_info">
							<view class="text_lightblue">发货类型</view>
							<view>{{jobContent.deliverType}}</view>
						</view>

						<view class="cell_info">
							<view class="text_lightblue">客户代码</view>
							<view>{{jobContent.customerCode}}</view>
						</view>

						<view class="cell_info">
							<view class="text_lightblue">目标库位</view>
							<view>{{toLocationCode}}</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<view class="page-main">
			<scroll-view scroll-y="true" class="page-main-scroll">
				<view>
		
				</view>
				<view v-for="(toLocation, index) in detailSource">
				<comDeliverDetailCardBatch ref='comIssueDetailCardBatch' :dataContent="toLocation" :settingParam="jobContent"
					@updateData='updateData' :allowBiggerQty='allowBiggerQty'>
				</comDeliverDetailCardBatch>
					<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>
				<view class=" uni-flex uni-row">
					<button class="btn_single_commit" hover-class="btn_commit_after" @click="submit()">提交</button>
				</view>
			</view>
		</view>

		<win-scan-button @goScan='openScanPopup'></win-scan-button>
		<!-- <comScanDeliverPackBatch ref="comScanIssuePack" @closeScan='closeScan' @updateData='updateData'>
		</comScanDeliverPackBatch> -->
		
		<winScanPackAndLocation :balanceFromInventoryStatuses="false" :toLocationCode="jobToLocationCode" ref="scanPopup"
			@getResult='getScanResult' :noShowBalanceMessage="false" @confirm='confirmFromLocation'>
		</winScanPackAndLocation>
		<comMessage ref="comMessage"></comMessage>
	</view>
</template>

<script>
	import {
		getDeliverDetail,
		takeDeliverJob,
		cancleTakeDeliverJob,
		deliverJobSubmit
	} from '@/api/request2.js';


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

	import {
		goHome,
		navigateBack,
		getRemoveOption,
		getCurrDateTime,
		getPackingNumberAndBatch,
		deepCopyData,
		compareAsc,
	} from '@/common/basic.js';


	import {
		getTreeDataSource,
		calcTreeHandleQty,
		getScanCount,
		getThreeDataSource,
		getDataSource,
		calcHandleQty,
	} from '@/common/detail.js';
	import {
		getManagementPrecisions
	} from '@/common/balance.js';


	import jobDetailPopup from '@/mycomponents/job/jobDetailPopup.vue'
	import winScanButton from '@/mycomponents/scan/winScanButton.vue'
	import comDeliverDetailCardBatch from '@/pages/deliver/coms/comDeliverDetailCardBatch.vue'
	import comScanDeliverPackBatch from '@/pages/deliver/coms/comScanDeliverPackBatch.vue'
	import jobTop from '@/mycomponents/job/jobTop.vue'
	import winScanPackAndLocation from "@/mycomponents/scan/winScanPackAndLocation.vue"

	export default {
		name: 'issueDetail',
		components: {
			jobDetailPopup,
			winScanButton,
			comDeliverDetailCardBatch,
			comScanDeliverPackBatch,
			jobTop,
			winScanPackAndLocation
		},
		data() {
			return {
				id: '',
				jobContent: {}, //任务内容
				subList: [], //接口返回的任务subList
				detailSource: [], //绑定在页面上的数据源
				detailOptions: [],
				scanOptions: [],
				status: "",
				toLocationCode: "",
				jobStatus: "",
				allowBiggerQty:"TRUE",//开启数量校验提示
			};
		},

		props: {

		},

		onLoad(option) {
			uni.setNavigationBarTitle({
				title: option.title + '详情'
			})
			this.id = option.id;
			if (this.id != undefined) {
				//新建的任务自动接收
				if (option.status == "1") {
					this.receive((callback => {
						this.getDetail();
					}));
				} else {
					this.getDetail();
				}
			}
		},

		onNavigationBarButtonTap(e) {
			if (e.index === 0) {
				goHome();
			}
		},

		//拦截返回按钮事件
		onBackPress(e) {
			//已经接收但是没提交任务
			if (e.from == 'backbutton') {
				if (this.jobStatus == "2") {
					//取消承接任务	
					cancleTakeDeliverJob(this.id).then(res => {
						uni.navigateBack();
					}).catch(error => {
						uni.navigateBack();
					})
				} else {
					uni.navigateBack();
				}

				return true;
			}

		},

		methods: {
			//接收
			receive(callback) {
				if (this.id != null) {
					takeDeliverJob(this.id).then(res => {
						callback();
					}).catch(error => {
						this.showErrorMessage(error)
					})
				}
			},

			getDetail() {
				var that = this;
				uni.showLoading({
					title: "加载中....",
					mask: true
				});
				getDeliverDetail(that.id).then(res => {
					uni.hideLoading();
					if (res.data && res.data.subList.length > 0) {
						that.jobContent = res.data;
						that.jobStatus = res.data.status;
						that.subList = res.data.subList;
						// that.detailSource = res.data;
							that.detailSource = getThreeDataSource(that.jobContent)
						that.toLocationCode = that.subList[0].toLocationCode
						that.allowBiggerQty = res.data.allowBiggerQty;
						that.resizeCollapse();
					} else {
						that.showMessage('未获取到详情');
					}
				}).catch(error => {
					uni.hideLoading()
					this.showErrorMessage(error)
				})
			},

			closeScan() {
				this.resizeCollapse();
			},

			resizeCollapse() {
				this.$nextTick(r => {
					this.$refs.comIssueDetailCardBatch.forEach(r => {
						r.resizeCollapse();
					})
				});
			},


	getScanResult(result, managementTypeParams) {
				this.managementType = managementTypeParams
				if(managementTypeParams == "BY_BATCH" ||managementTypeParams == "BY_QUANTITY" ){
					this.setDataBatch(result)
				}else{
					this.setData(result)
				}	
			},
			setDataBatch(result) {
				try {
					let that = this
					this.balanceinfo =  result.balance
					var packingNumber = result.label.packingNumber;
					var batch = result.label.batch;
					var qty = result.label.qty;
					var itemCode = result.label.itemCode;
					var locationCode = result.fromLocationCode;
					
					if (!result.balance) {
						this.showMessage("没有库存余额")
						return;
					}
					// var inventoryStatus = "OK";
					var detail = this.detailSource.find(r => r.itemCode == itemCode);
			
					if (detail == undefined) {
						this.showErrorMessage("物料号【" + itemCode + "】不在列表中")
					} else {
						
						var itemDetail = detail.subList.find(r => {
								return r.batch == batch &&
									r.fromLocationCode == result.fromLocationCode
							})
							if (itemDetail == undefined) {
								var isExit;
								for (let subItem of detail.subList) {
									var item;
									// for (let pack of subItem.packList) {
									// 	if (pack.batch == batch) {
									// 		item = pack;
									// 		isExit = pack;
									// 		break;
									// 	}
									// }
									// if (item != undefined) {
									// 	subItem.scaned = true
									// 	subItem.handleQty = 0;
									// 	item = undefined
									// }
								}
								if (isExit == undefined) {
									// this.showErrorMessage("批次【" + batch + "】库位【" + result
									// 	.fromLocationCode + "】不在列表中")
									detail.subList.push({
										scaned:true,
										fromLocationCode:this.fromLocationCode,
										toLocationCode:this.toLocationCode,
										batch:result.label.batch,
										handleQty:result.label.qty,
										qty:result.balance.qty,
										inventoryStatus:result.balance.inventoryStatus,
										toLocation:result.balance.toLocation,
										balance:result.balance,
										balanceQty:result.balance.qty,
										packQty:result.package.packQty,
										packUnit:result.package.packUnit,
										uom:result.balance.uom,
										// packList:[{
										// 	scaned : true,
										// 	handleQty : Number(result.label.qty),
										// 	toLocationCode :  result.balance.toLocationCode,
										// }]
									})
									detail.handleQty = 0
									detail.qty = 0
									detail.subList.forEach(item=>{
										detail.handleQty = calc.add(detail.handleQty,item.handleQty)
										detail.qty = calc.add(detail.qty,item.qty)
										// item.packList.forEach(cur=>{
										// 	cur.handleQty =  calc.add(detail.handleQty,item.handleQty)
										// })
									})
									setTimeout(r => {
										that.resizeCollapse();
										that.$forceUpdate()
									}, 100)
								} else {
									if (!isExit.cancleScanedHiht && isExit.scaned) {
										// this.showMessage("批次【" + batch + "】已经扫描")
									} else {
										isExit.scaned = true
										let qty = 0;
										if (result.balance != null) {
											qty = Number(result.balance.qty);
										} else {
											qty = Number(result.label.qty);
										}
										isExit.handleQty = Number(result.label.qty);
										isExit.toLocationCode = this.toLocationCode;
									}
									itemDetail.handleQty = calc.add(itemDetail.handleQty,result.label.qty);
									detail.handleQty = 0
									detail.balance = result.balance,
									detail.subList.forEach(item=>{
										detail.handleQty = calc.add(detail.handleQty,item.handleQty)
										// item.packList.forEach(cur=>{
										// 	cur.handleQty =  calc.add(detail.handleQty,item.handleQty)
										// })
									})
									// calcHandleQtyAdd(this.detailSource, result.label);
								}
								this.continueScan()
								this.$forceUpdate()
							} else {
								var scanedLength = 0;
								// itemDetail.packList.forEach(res => {
								// 	if (res.scaned) {
								// 		scanedLength++;
								// 	}
								// })
								//大哥让加的
								itemDetail.fromInventoryStatus = result.balance.inventoryStatus;
						
								if (itemDetail.scaned ) {
									// this.showMessage("箱码【" + packingNumber + "】已经扫描")
										// calcHandleQtyAdd(this.detailSource, result.label);
										itemDetail.balance=result.balance
										itemDetail.balanceQty=result.balance.qty
										itemDetail.uom=result.balance.uom,
										itemDetail.handleQty = calc.add(itemDetail.handleQty,result.label.qty);
										detail.handleQty = 0
										detail.subList.forEach(item=>{
											detail.handleQty = calc.add(detail.handleQty,item.handleQty)
										})
								} else {
									itemDetail.scaned = true;
									this.detailSource[0].subList.sort(compareAsc('scaned')); //按扫描信息排序
									itemDetail.handleQty = result.label.qty;
									itemDetail.scaned = true
									itemDetail.balance=result.balance
									itemDetail.balanceQty=result.balance.qty
									itemDetail.uom=result.balance.uom
									itemDetail.packQty=result.package.packQty
									itemDetail.packUnit=result.package.packUnit
									itemDetail.fromlocationCode=this.fromLocationCode
									itemDetail.toLocationCode=this.toLocationCode
									// itemDetail.toInventoryStatus = "OK"
									// itemDetail.packList.forEach(pac => {
									// 	pac.scaned = true
									// 	pac.handleQty = Number(result.label.qty);
									// 	pac.toLocationCode = result.balance.toLocationCode;
									// })
									detail.handleQty = 0
									detail.subList.forEach(item=>{
										detail.handleQty = calc.add(detail.handleQty,item.handleQty)
										// item.packList.forEach(cur=>{
										// 	cur.handleQty =  calc.add(detail.handleQty,item.handleQty)
										// })
									})
									// calcTreeHandleQty(this.detailSource);
									this.continueScan()
									this.$forceUpdate()
								}
							}
					}
					this.detailSource.forEach(item => {
						item.subList.forEach(detail => {
							detail.packingNumber = ''
						})
					})
				} catch (e) {
					this.showMessage(e.message)
				}
			},
			//继续扫描
			continueScan() {
				this.scanCount = getScanCount(this.subList);
				if (this.scanCount == this.subList.length) {
					this.closeScanPopup();
				} else {
					this.scanPopupGetFocus();
				}
			},
			submit() {
				uni.showLoading({
					title: "提交中....",
					mask: true
				});

				//目前任务只到一个库位
				var itemCodes = []
				//目前任务只到一个库位
				var itemCodes = []
				let locationCode = this.detailSource[0].subList[0].toLocationCode
				this.detailSource.forEach(toLocation => {
					itemCodes.push(toLocation.itemCode)
				})
				
				//获取管理模式，封装参数
				getManagementPrecisions(itemCodes, locationCode, res => {
					if (res.success) {
						this.managementList = res.list;
						this.managementType = this.managementList &&  this.managementList[0] ? this.managementList[0].ManagementPrecision : 'BY_PACKAGING'
					
						this.submitJob();
					} else {
						uni.hideLoading();
						// this.showErrorMessage(res.message);
					}
				});
				// //使用在途库，不查询管理模式
				// if (locationCode == null) {
				// 	this.submitJob();
				// } else {
				// 	//获取管理模式，封装参数
				// 	getManagementPrecisions(itemCodes, locationCode, res => {
				// 		if (res.success) {
				// 			this.managementList = res.list;
				// 			this.submitJob();
				// 		} else {
				// 			uni.hideLoading();
				// 			this.showErrorMessage(res.message);
				// 		}
				// 	});
				// }
			},

			checkCount() {
			let str=""
			this.detailSource.forEach(detail => {
				detail.Items.forEach(item => {
					var taskQty =0;
					item.taskQty =calc.add(taskQty,item.qty)
					var totalQty =0;
					item.Locations.forEach(lco => {
						lco.Batchs.forEach(batch => {
							batch.Records.forEach(record => {
								if(record){
									var hanleQty =record.qty?record.qty:0
									totalQty = calc.add(totalQty,hanleQty)
								}
								
							})
						})
					})
					//实际扫描的数量
					item.totalQty =totalQty
					
				})
			})
			//如果允许部分提交任务有扫描记录就可以直接提交；如果不允许部分执行，任务数量和提交数量不一致给出提示
			this.detailSource.forEach(detail=>{
				detail.Items.forEach(item=>{
					if(this.jobContent.allowPartialComplete=="FALSE"){
						if(item.taskQty!=item.totalQty){
							str += `物料号【${item.itemCode}】任务数量【${item.taskQty}】与实际提交数量【${item.totalQty}】不一致\n`
						}
					}
				})
			})
			
			if(str){
				str = '不允许提交\n' + str
				this.showErrorMessage(str)
			}
			
			return str?false:true
			},
			checkCountBatch() {
				let str = ""
				let str1 = ""
				let str2 = ""
				this.detailSource.forEach(detail => {
					var taskQty = 0;
					var totalQty = 0;
					detail.subList.forEach(item => {
						if(item.scaned){
							item.taskQty=0
							item.totalQty=0
							item.taskQty =calc.add(item.taskQty,item.qty)
							item.totalQty =calc.add(item.totalQty,item.handleQty)
								if (this.jobContent.allowSmallerQty == "FALSE") {
									if(item.handleQty!=item.taskQty){
										str +=	`批次【${item.batch}】提交数量【${item.handleQty}】与任务物料数量【${item.taskQty}】不一致\n`
									}
								}
								if (this.allowBiggerQty == 'FALSE') {
									if (	item.taskQty < 	item.totalQty) {
										str1 += '数量[' + item.totalQty + ']不允许大于任务数量[' + item.taskQty + ']'
									}
								}
								if(item.handleQty>item.balance.qty){
									str2 +=	`批次【${item.batch}】提交数量【${item.handleQty}】不可以大于库存数量【${item.balance.qty}】`
								}
						}
					
					})
				})
			

				if (str) {
					str = '不允许提交\n' + str
					this.showErrorMessage(str)
				}
				if (str1) {
					str1 = '不允许提交\n' + str1
					this.showErrorMessage(str1)
				}
				if (str2) {
					str2 = '不允许提交\n' + str2
					this.showErrorMessage(str2)
				}
				return str || str1 || str2 ? false : true

			},

			submitJob() {
				var params = this.setParams()
				console.log("提交参数", params);
				const isTrue = params.subList.some(item=>{
					console.log(item.recordList.some(cur=>cur.scaned))
					return item.recordList.some(cur=>cur.scaned) == true
				})
				if(!isTrue){
						uni.hideLoading()
						this.showErrorMessage("请扫描您需要提交的发货任务")
						return
				}
				// return;
				// if (params.subList.length == 0) {
				// 	uni.hideLoading()
				// 	this.$refs.comMessage.showConfirmMessageModal('请扫描箱码')
				// 	return
				// }
				if(this.managementType == "BY_BATCH" ||this.managementType == "BY_QUANTITY" ){
					if (!this.checkCountBatch()) {
						uni.hideLoading()
						return;
					}
				}else{
					if (!this.checkCount()) {
						uni.hideLoading()
						return;
					}
				}
				deliverJobSubmit(params).then(res => {
					uni.hideLoading()
					if (res.data) {
						
						this.showCommitSuccessMessage("提交成功\n生成发货记录\n" + res.data)
					} else {
						this.showErrorMessage("提交失败[" + res.msg + "]")
					}
				}).catch(error => {
					uni.hideLoading()
					this.showErrorMessage(error)
				})
			},

			setParams() {
				var subList = []
				var createTime = getCurrDateTime();
				var creator = this.$store.state.user.id
				this.detailSource.forEach(toLocationCode => {
					let obj = {...toLocationCode}
					delete obj.subList
					obj.recordList = []
					let obj1 ={}
					let arr = toLocationCode.subList.filter(item=>item.scaned)
					arr.forEach(record=>{
						obj1.scaned =record.scaned;
						obj1.handleQty =record.handleQty;
						obj1.fromLocationCode =record.fromLocationCode;
						obj1.fromInventoryStatus =record.fromInventoryStatus;
						obj1.copyContent =record.copyContent;
						obj1.toContainerNumber = record.ContainerNumber;
						obj1.toInventoryStatus =record.inventoryStatus;
						obj1.toLocationCode = record.toLocationCode;
						obj1.supplierCode = record.supplierCode;
						obj1.toPackingNumber ='';
						obj1.packingNumber = ''
						obj1.fromPackingNumber = '';
						obj1.toBatch = record.batch;
						obj1.toPackingNumber = '';
						obj1.packingNumber = '';
						obj1.fromPackingNumber ='';
						obj.recordList.push(obj1)
					})
					subList.push(obj)
				})
				this.jobContent.subList = subList
				this.jobContent.createTime = createTime;
				this.jobContent.creator = creator;
				return this.jobContent;
			},

			cancel() {
				let that = this;
				this.$refs.comMessage.showQuestionMessage('是否要清空已扫描的物料和目标库位信息?', res => {
					if (res) {
						that.clearInfo();
					}
				});
			},

			clearInfo() {
				this.dataContent.itemCodeList.forEach(res => {
					if (res.recommendList != null) {
						res.recommendList.forEach(res1 => {
							if (res1.locationCodeList != null) {
								res1.locationCodeList.forEach(res2 => {
									if (res2.packingCodeList != null) {
										res2.packingCodeList.forEach(res3 => {
											res3.itemCode = "";
											res3.qty = 0;
										})
									}
								})
							}

						})
					}

				})
			},

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

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

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

			showCommitSuccess() {
				this.$refs.comMessage.showCommitSuccess();
			},

			showCommitSuccessMessage(hint) {
				this.$refs.comMessage.showSuccessMessage(hint, res => {
					navigateBack(1)
				})
			},

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


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


			closeScanMessage() {
				this.scanPopupGetFocus();
			},
			confirm(data) {
				this.dataContent = data;
			},
			confirmResult(result) {
				this.dataContent = result;
				this.$forceUpdate();
			},
			// openScanDetailPopup() {
			// 	var datacontent = {}
			// 	//克隆对象，深度克隆，防止双向绑定同一个变量
			// 	// Object.assign(datacontent, this.detailSource);
			// 	this.$refs.comScanIssuePack.openScanPopup(this.detailSource, this.jobContent);
			// },
			closeScanPopup() {
				// this.updateCommitBtn();
			},
			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.fromLocationCode = fromLocationCode
				this.$refs.scanPopup.openScanPopupForJob(fromLocationCode, fromlocationList, this.jobContent);
			},
			
		},
		confirmFromLocation(fromLocationCodeParams){
			this.fromlocationCode = fromLocationCodeParams
		}
	};
</script>

<style scoped lang="scss">
	.uni-numbox__value {
		width: 40px;
	}

	button[disabled] {
		background-color: #3C9CFF;
		color: #fff;
		opacity: 0.7;
	}


	// /deep/ .input-value {
	// 	font-size: 16px;
	// }

	// /deep/ .uni-collapse-item__title-text {
	// 	font-size: 16px;
	// }

	// /deep/ .uni-collapse-item--border {
	// 	border-bottom-width: 0px;
	// 	border-bottom-color: #ebeef5;
	// }

	// /deep/ .uni-collapse-item--border {
	// 	border-bottom-width: 1px;
	// 	border-bottom-color: #ebeef5;
	// }
</style>