<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>
				<work-station :workshopCode="jobContent.workShopCode"
					:productionLineCode="jobContent.detailProductionLineCode"
					:workStationCode="jobContent.detailWorkStationCode"
					:rawLocationCode="jobContent.detailToLocationCode">
				</work-station>
			</view>
		</view>
		<view class="page-main">
			<scroll-view scroll-y="true" class="page-main-scroll">
				<view v-for="(toLocation, index) in detailSource">
					<comIssueDetailCardBatch ref='comIssueDetailCardBatch' :dataContent="toLocation" :settingParam="jobContent"
						@updateData='updateData'>
					</comIssueDetailCardBatch>
					<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="autoCommit()">提交</button>
				</view>
			</view>
		</view>

		<win-scan-button @goScan='openScanPopup'></win-scan-button>
		<!-- <com-scan-issue-pack ref="comScanIssuePack" @closeScan='closeScan' @updateData='updateData'
			@afterScan='afterScan' :locationCode='fromLocationCode'>
		</com-scan-issue-pack> -->
	
		<winScanPackAndLocation :balanceFromInventoryStatuses="false"  ref="scanPopup"
			@getResult='getScanResult' :noShowBalanceMessage="false" @confirm='confirmFromLocation'>
		</winScanPackAndLocation>
		<balance-select ref="balanceSelect" ></balance-select>
		<comMessage ref="comMessage"></comMessage>
	</view>
</template>

<script>
	import {
		takeIssueJob,
		cancleTakeIssueJob,
		getIssueJobDetail,
		issueJobSubmit
	} from '@/api/request2.js';

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

	import {
		getDataSource
	} from '@/pages/issue/js/issue.js';

	import {
		getManagementPrecisions
	} from '@/common/balance.js';
	import {
		calc
	} from '@/common/calc.js';
	
	
	import {
		getTreeDataSource,
		calcTreeHandleQty,
		getScanCount,
		getThreeDataSource
	} from '@/common/detail.js';
	
	import {
		calcHandleQtyAdd
	} from '@/common/record.js';

	import jobDetailPopup from '@/mycomponents/job/jobDetailPopup.vue'
	import comIssueDetailCard from '@/pages/issue/coms/comIssueDetailCard.vue'
	import comIssueDetailCardBatch from '@/pages/issue/coms/comIssueDetailCardBatch.vue'
	import winScanButton from '@/mycomponents/scan/winScanButton.vue'
	import comScanIssuePack from '@/pages/issue/coms/comScanIssuePack.vue'
	import jobTop from '@/mycomponents/job/jobTop.vue'
	import workStation from '@/mycomponents/workStation/workStation.vue'
	import balanceSelect from '@/mycomponents/balance/balanceSelect.vue'
	import winScanPackAndLocation from "@/mycomponents/scan/winScanPackAndLocation.vue"

	export default {
		name: 'issueDetail',
		components: {
			jobDetailPopup,
			winScanButton,
			comIssueDetailCard,
			comScanIssuePack,
			jobTop,
			workStation,
			balanceSelect,
			comIssueDetailCardBatch,
			winScanPackAndLocation
		},
		data() {
			return {
				id: '',
				jobContent: {}, //任务内容
				subList: [], //接口返回的任务subList
				detailSource: [], //绑定在页面上的数据源
				detailOptions: [],
				scanOptions: [],
				jobStatus: "",
				scanMessage: '',
				managementList: [],
				managementType: "",
				fromLocationCode:''
			};
		},

		props: {

		},

		onLoad(option) {
			uni.setNavigationBarTitle({
				title: option.title + '详情'
			});
			this.id = option.id;
			this.scanMessage = option.scanMessage || '';
			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") {
					//取消承接任务	
					cancleTakeIssueJob(this.id).then(res => {
						uni.navigateBack();
					}).catch(error => {
						uni.navigateBack();
					})
				} else {
					uni.navigateBack();
				}

				return true;
			}

		},

		watch: {
			locationTypes(newVal) {
				let value = newVal;
			},
		},
		mounted: function() {
			// this.resizeCollapse();
		},

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

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

			getDetail() {
				var that = this;
				uni.showLoading({
					title: "加载中....",
					mask: true
				});
				getIssueJobDetail(that.id).then(res => {
					uni.hideLoading();
					if (res.data == null) {
						that.showMessage('未获取到详情');
					} else {
						if (res.data.subList.length > 0) {
							// res.data.allowModifyLocation = 'FALSE'
							that.jobContent = res.data;
							that.jobStatus = res.data.status
							that.subList = res.data.subList;
							that.detailSource = getThreeDataSource(that.jobContent)
							that.jobContent.detailToLocationCode = res.data.subList[0].toLocationCode
							that.toLocationCode= res.data.subList[0].toLocationCode
							that.fromLocationCode = that.subList[0].fromLocationCode
							
							that.detailSource.forEach(r => {
								r.subList.forEach(s => {
									s.isRecommTaskItem = true//为推荐任务
								})
							})
							//任务中已经扫描，模拟扫描赋值
							if (this.scanMessage) {
								this.openScanPopupSimulate(this.scanMessage);

							}
							setTimeout(r => {
								that.resizeCollapse();
							}, 100)
							// that.detailSource.forEach(r => {
							// 	r.subList.forEach(s => {
							// 		if (this.scanedPackingNumber && this.scanedPackingNumber == s
							// 			.packingNumber) {
							// 			s.scaned = true
							// 			s.cancleScanedHiht = true
							// 			//模拟扫描功能
							// 			this.openScanPopupSimulate(s);
							// 			this.scanedPackingNumber = ''
							// 		}
							// 	})
							// })

						} else {
							that.showMessage('列表数据为0');
						}
					}
				}).catch(error => {
					uni.hideLoading()
					this.showErrorMessage(error)
				})
			},

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

			getScanResult(result, managementTypeParams) {
				this.managementType = managementTypeParams
				let array1 = []//记录推荐的库位
				let array2 = []//记录推荐的批次
				this.detailSource.forEach(item=>{
					item.subList.forEach(cur=>{
						array1.push(cur.fromLocationCode)
						array2.push(cur.batch)
					})
				})
				// 扫描的库位是否在
				const obj1 = array1.find(item=>item == result.fromLocationCode)
				const obj2 =  array2.find(item=>item == result.label.batch)
				if(this.jobContent.allowModifyLocation == 'FALSE'){
					if(!obj1){
						this.showErrorMessage(`不可以扫描推荐库位【${array1.join(',')}】以外的库位`)
						return
					}
				}
				if(this.jobContent.allowModifyBatch == 'FALSE'){
					if(!obj2){
						this.showErrorMessage(`不可以扫描推荐批次【${array2.join(',')}】以外的批次`)
						return
					}
				}
				if(!obj1){
					this.recommendQty = 0
				}else{
					this.recommendQty = result.balance.qty
				}
				// this.managementType = managementTypeParams
				if(managementTypeParams == "BY_BATCH" ||managementTypeParams == "BY_QUANTITY" ){
					this.setDataBatch(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:0,
										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,
										isRecommTaskItem:false,//不是推荐任务中的任务
										// 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.isRecommTaskItem = true//是推荐任务中的数量
									// 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 = []
				let locationCode = this.detailSource[0].toLocationCode
				this.detailSource.forEach(toLocation => {
					itemCodes.push(toLocation.itemCode)
				})

				//获取管理模式，封装参数
				getManagementPrecisions(itemCodes, locationCode, res => {
					if (res.success) {
						this.managementList = res.list;
						this.submitJob();
					} else {
						uni.hideLoading();
						this.showErrorMessage(res.message);
					}
				});

			},

			submitJob() {
				var params = this.setParams()
				console.log(params)
				
				// if (!params.subList || params.subList.length == 0) {
				// 	uni.hideLoading()
				// 	this.showErrorMessage("请扫描您需要提交的发料任务")
				// 	return
				// }
				const isTrue = params.subList.some(item=>{
					return item.recordList.some(cur=>cur.scaned) == true
				})
			
				if(!isTrue){
						uni.hideLoading()
						this.showErrorMessage("请扫描您需要提交的发料任务")
						return
				}
				
				console.log("提交参数", params);
				issueJobSubmit(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 arr = []
					toLocationCode.subList.forEach(record=>{
						if(record.scaned){
							let obj = {...record}
								obj.recordList = []
								let obj1 ={}
								obj1.supplierCode = record.supplierCode;
								obj1.batch = record.batch;
								obj1.copyContent =record.copyContent;
								obj1.fromInventoryStatus =record.fromInventoryStatus;
								obj1.fromLocationCode =record.fromLocationCode;
								obj1.handleQty =record.handleQty;
								obj1.inventoryStatus =record.fromInventoryStatus;
								obj1.packQty =record.packQty;
								obj1.packUnit =record.packUnit;
								obj1.packingNumber =record.packingNumber;
								obj1.qty =record.qty;
								obj1.scaned =record.scaned;
								obj1.toLocationCode =record.toLocationCode;
								obj1.fromPackingNumber ='';
								obj1.fromBatch = record.batch;
								obj1.toBatch  = record.batch;
								obj1.toInventoryStatus   = record.inventoryStatus;
								obj1.toPackingNumber  ="";
								obj1.packingNumber  = "";
								
								let single_price = record.balance.singlePrice == null ? 0 : record.balance.singlePrice;
								
								obj1.singlePrice = single_price;
								obj1.amount = single_price *record.qty;
								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) {
				this.detailSource.forEach(item=>{
						item.handleQty = 0
					item.subList.forEach(cur=>{
					item.handleQty = calc.add(cur.handleQty,item.handleQty)
					})
				})
			},

			afterScan() {
				this.resizeCollapse();
				// this.autoCommit()
			},
			
			autoCommit(){
					// this.$throttle(this.submit, 2000, this)()
					// this.jobContent.allowSmallerQty = 'FALSE'
					// this.jobContent.allowBiggerQty = 'FALSE'
				let str=""
				let str1=""
				let str2=""
				let str3=""
				let isTrue = true
				this.detailSource.forEach(detail => {
					const isScaned  = detail.subList.some(cur=>cur.scaned)
					if(isScaned){
						if(parseFloat(detail.handleQty)<parseFloat(detail.qty)){
							str +=	`物料号【${detail.itemCode}】提交数量【${detail.handleQty}】不允许小于任务数量【${detail.qty}】`
						}
						if(parseFloat(detail.handleQty)>parseFloat(detail.qty)){
							str1 +=	`物料号【${detail.itemCode}】提交数量【${detail.handleQty}】不允许大于任务数量【${detail.qty}】`
						}
					}
					
					detail.subList.forEach(item => {
						if(item.scaned){
							if(parseFloat(item.handleQty)>parseFloat(item.balance.qty)){
								str2 +=	`物料号【${detail.itemCode}】批次【${item.batch}】提交数量【${parseFloat(item.handleQty)}】不可以大于库存数量【${item.balance.qty}】`
							}
						}
						if(item.isRecommTaskItem){//扫描推荐任务中的任务时候才有这个提示
							item.handleQty = item.handleQty || 0
							if(item.handleQty == 0 && isTrue){
								isTrue = false
								str3 = '推荐的箱码没扫,'
							}
							if(parseFloat(item.handleQty)!=parseFloat(item.qty)){
								str3 +=	`物料号【${detail.itemCode}】批次【${item.batch}】扫描数量【${parseFloat(item.handleQty)}】和任务数量【${item.qty}】不一致`
							}
							
						}
					})
				})
				if (this.jobContent.allowSmallerQty == "FALSE") {
					if (str) {
						str = '不允许提交\n' + str
						this.showErrorMessage(str)
						return
					}
				}
				if (this.jobContent.allowBiggerQty == 'FALSE') {
					if (str1) {
						str1 = '不允许提交\n' + str1
						this.showErrorMessage(str1)
						return
					}
				}
				
				if (str2) {
					str2 = '不允许提交\n' + str2
					this.showErrorMessage(str2)
					return
				}
				console.log(str3)
				if(str3){
					str3 = str3+",是否提交"
					this.$refs.comMessage.showQuestionMessage1(str3, 'red', res => {
						if (res) {
							//防止重复点击
							this.$throttle(this.submit, 2000, this)()
						} else {
							this.scanPopupGetFocus()
						}
					});
				}else {
					//防止重复点击
					this.$throttle(this.submit, 2000, this)()
				}
			},

			scanPopupGetFocus() {
				if (this.$refs.comScanIssuePack) {
					this.$refs.comScanIssuePack.getfocus();
				}
			},

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

			openScanPopupSimulate(scanMessage) {
				this.$refs.comScanIssuePack.openScanPopupForJobSimulate(this.detailSource, this.jobContent, scanMessage);
			},

			closeScanPopup() {
				// this.updateCommitBtn();
			},
			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>