<template>
	<view class="page-wraper">
		<view class="page-header">
			<view class="header-view uni-flex space-between u-col-center">
				<view class="task_number left uni-flex">
					<text> {{mDate}} </text>
					<view class="time"> {{jobContent.deliNo}} </view>
				</view>
				<view class="task_number">
					<text> {{mTime}} </text>
				</view>
			</view>
		</view>
		
		<view class="page-main">
			<scroll-view scroll-y="true" class="page-main-scroll">
				<com-repleish-detail-card-time :dataContent="jobContent" ></com-repleish-detail-card-time>
				<uni-swipe-action ref="swipeAction" style="margin-top: 10px;"
					    v-for="(item,index) in jobContent.recordList">
					<uni-swipe-action-item
						:right-options="item.scaned? [{
		text: '移除',
		style: {
			backgroundColor: '#F56C6C'
		}
	}]:[]"   @click="itemCoceClick($event,item,index)">
						<view :class="item.scaned?'scan_view':''" style="background-color: #ffffff; border-bottom: 1upx solid #EEEEEE;">
							<view class="uni-flex uni-row space-between" style="align-items: center">
								<!-- uni-inline-item 暂时拿掉-->
								<view style="word-break: break-all;">
									<pack :isShowPackingNumberProps="true"  :packingCode="item.fromPackingNumber"></pack>
									<batch :batch="item.fromBatch"></batch>
									<location title="来源库位" :locationCode="item.fromLocationCode"></location>
							<!-- <recommend :isShowPackingNumberProps="true"  :isShowPack="true" :detail="item" :isShowLocation="false" :isShowFromLocation="true"  :isShowToLocation="false"></recommend> -->
								</view>
								
								<compare-qty style="margin-right: 20rpx;" :dataContent="item" :handleQty="Number(item.handleQty)" :isShowRecommendQty="false" :isShowStatus="false">
								</compare-qty>
							</view>
						</view>
					</uni-swipe-action-item>
				</uni-swipe-action>
			</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="">
					<requiredLocation ref='comScanLocation' title="目标库位" :locationCode="toLocationCode"
						@getLocation='scanLocationCode' :isShowEdit="jobContent.allowModifyLocation == 'TRUE'"
						:locationAreaTypeList="toLocationAreaTypeList"></requiredLocation>
				</view>
				<view class=" uni-flex uni-row">
					<button class="btn_single_commit" hover-class="btn_commit_after" @click="clickSubmit">提交</button>
				</view>
			</view>
		</view>

		<win-scan-button @goScan='openScanDetailPopup'></win-scan-button>
		<win-com-scan-balance ref="scanPopup" @getBalance='getPackScanResult'
			:verifyCategory='false'
			:isCheckLocationBalance="false"
			:bussinessCode="jobContent.businessType">
		</win-com-scan-balance>
		<!-- <com-scan-replish-pack-time ref="comScanIssuePack" @closeScan='closeScan' @updateData='updateData'>
		</com-scan-replish-pack-time> -->
		<comMessage ref="comMessage"></comMessage>
	</view>
</template>

<script>
	import {
		takeRepleinshJob,
		cancleTakeRepleinshJob,
		getRepleinshTimeJobDetail,
		repleinshTimeJobSubmit
	} from '@/api/request2.js';
	import pack from '@/mycomponents/balance/pack.vue'
	import batch from '@/mycomponents/balance/batch.vue'
	import location from '@/mycomponents/balance/location.vue'
	import compareQty from '@/mycomponents/qty/compareQty.vue'

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

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

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

	import {
		getManagementPrecisions
	} from '@/common/balance.js';
	import {
		dateFormat,

	} from '@/common/basic.js';
	import item from '@/mycomponents/item/item.vue'
	
	import requiredLocation from '@/mycomponents/location/requiredLocation.vue'
	import jobDetailPopup from '@/mycomponents/job/jobDetailPopup.vue'
	import winScanButton from '@/mycomponents/scan/winScanButton.vue'
	import comRepleishDetailCardTime from '@/pages/repleinsh/coms/comRepleishDetailCardTime.vue'
	import winComScanBalance from '@/mycomponents/scan/winComScanBalance.vue'
	import jobTop from '@/mycomponents/job/jobTop.vue'
	import recommend from '@/mycomponents/recommend/recommend.vue'
	import {
		getBusinessType,
	} from '@/common/record.js';
	export default {
		name: 'issueDetail',
		components: {
			compareQty,
			item,
			jobDetailPopup,
			winScanButton,
			comRepleishDetailCardTime,
			winComScanBalance,
			requiredLocation,
			jobTop,
			pack,
			batch,
			location,
			recommend,
		},
		data() {
			return {
				id: '',
				jobContent: {}, //任务内容
				subList: [], //接口返回的任务subList
				detailSource: [], //绑定在页面上的数据源
				detailOptions: [],
				scanOptions: [],
				toLocationCode: '',
				toLocationAreaTypeList: [],
				jobStatus: "",
				scanMessage: "",
				businessType:{}
			};
		},

		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") {
					//取消承接任务	
					cancleTakeRepleinshJob(this.id).then(res => {
						uni.navigateBack();
					}).catch(error => {
						uni.navigateBack();
					})
				} else {
					uni.navigateBack();
				}

				return true;
			}

		},

		watch: {
			locationTypes(newVal) {
				let value = newVal;
			},
		},
		mounted: function() {

		},
		computed: {
			mDate() {
				if (!this.jobContent.day) {
					return ''
				}
				let date = dateFormat(this.jobContent.day)
				let dateArr = date.split(' ')[0].split('-')
				return `${dateArr[1]}-${dateArr[2]}`
			},
			mTime() {
				console.log('this.jobContent.day', this.jobContent.day)
				if (!this.jobContent.day) {
					return ''
				}
				let date = dateFormat(this.jobContent.day)
				let dateArr = date.split(' ')[1].split(':')
				return `${dateArr[0]}:${dateArr[1]}`
			}
		},
		methods: {
			//接收
			receive(callback) {
				if (this.id != null) {
					takeRepleinshJob(this.id).then(res => {
						callback();
					}).catch(error => {
						this.showErrorMessage(error)
					})
				}
			},
			getBusinessType(){
				getBusinessType(this.jobContent.businessType, res => {
					if (res.success) {
						this.businessType = res.businessType;
						// this.fromInventoryStatuses = getDirectoryItemArray(res.fromInventoryStatuses);
						// this.fromLocationAreaTypeList = res.fromLocationAreaTypeList
						// this.showFromLocationPopup();
					} else {
						this.showErrorMessage(res.message)
					}
				});
			},
			getDetail() {
				var that = this;
				uni.showLoading({
					title: "加载中....",
					mask: true
				});
				getRepleinshTimeJobDetail(that.id).then(async res => {
					console.log('详情', res)
					uni.hideLoading();
					if (res.data == null) {
						that.showMessage('未获取到详情');
					} else {
						that.jobContent = res.data;
						this.jobContent.recordList = [];
						that.toLocationCode = res.data.toLocationCode
						that.jobStatus = res.data.status
						that.getBusinessType()
						// that.detailSource =await  getDataSource(that.detailSource, [res.data])
						// if (res.data.subList.length > 0) {
						// 	that.jobContent = res.data;
						// 	that.jobStatus = res.data.status
						// 	that.subList = res.data.subList;
						// 	that.toLocationCode = that.subList[0].toLocationCode

						// 	that.toLocationAreaTypeList = getDirectoryItemArray(that.jobContent.toAreaTypes)
						// 	that.detailSource =await  getDataSource(that.detailSource, that.subList)
						// 	if (that.scanMessage) {
						// 		this.$refs.comScanIssuePack.openScanPopupForJobSimulate(this.detailSource, this
						// 			.jobContent, that.scanMessage);
						// 	}

						// 	let timer = setTimeout(r => {
						// 		that.resizeCollapse();
						// 		if (timer) {
						// 			timer = null
						// 			clearTimeout(timer)
						// 		}
						// 	}, 1000)
						// } else {
						// 	that.showMessage('列表数据为0');
						// }
					}
				}).catch(error => {
					uni.hideLoading()
					this.showErrorMessage(error)
				})
			},

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

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

			clickSubmit() {
			// 未料数量unexecutedQty
			// 已补料数量qty
				let requestQty = this.jobContent.unexecutedQty+this.jobContent.qty
				if(this.jobContent.qty>=requestQty){
					// 已完成
				}else{
					//部分完成
					let handleQty = this.jobContent.recordList.reduce((prev, item) => prev + Number(item['handleQty']),0)
					if(handleQty>requestQty){
						showConfirmMsg("拆包信息还没提交，是否要重新扫描?",res=>{
							if(res){
								//防止重复点击
								this.$throttle(this.submitJob, 2000, this)()
							}
						})
					}else{
						//防止重复点击
						this.$throttle(this.submitJob, 2000, this)()
					}
				}
				
			},


			submit() {
				var scanCount = this.getScanCount(this.subList);

				// //允许部分提交
				// if (this.jobContent.allowPartialComplete == "TRUE") {
				// 	// 如果扫描数是0，提示扫描数为0，是否提交，点击确定提交，取消提示消失
				// 	if (scanCount == 0) {
				// 		this.$refs.comMessage.showQuestionMessage("扫描数为0,是否提交?", res => {
				// 			if (res) {
				// 				this.setSubmitParamsAndSubmit();
				// 			}
				// 		})
				// 	} else {
				// 		this.setSubmitParamsAndSubmit();
				// 	}
				// } else {
				//不允许部分提交，扫描数必须等于任务数量才可以提交
				if (scanCount == 0) {
					this.showErrorMessage("扫描数为0,请先扫描")
				} else {
					this.setSubmitParamsAndSubmit();
				}
				// }
			},

			setSubmitParamsAndSubmit() {
				//目前任务只到一个库位
				this.submitJob();
				//使用在途库，不查询管理模式
				// if (this.jobContent.useOnTheWayLocation == 'TRUE') {
				// 	this.submitJob();
				// } else {
				// 	//获取管理模式，封装参数
				// 	getManagementPrecisions(itemCodes, locationCode, res => {
				// 		if (res.success) {
				// 			this.managementList = res.list;
				// 			this.submitJob();
				// 		} else {
				// 			uni.hideLoading();
				// 			this.showErrorMessage(res.message);
				// 		}
				// 	});
				// }
			},

			submitJob() {
				uni.showLoading({
					title: "提交中....",
					mask: true
				});
				
				if (!this.jobContent.recordList || this.jobContent.recordList.length == 0) {
					uni.hideLoading()
					this.showErrorMessage("请扫描您需要提交的按便次补料任务")
					return
				}
				repleinshTimeJobSubmit(this.jobContent).then(res => {
					uni.hideLoading()
					if (res.data) {
						this.showCommitSuccessMessage("提交成功\n" + res.data)
					} else {
						this.showErrorMessage("提交失败[" + res.msg + "]")
					}
				}).catch(error => {
					uni.hideLoading()
					this.showErrorMessage(error)
				})

			},

			setParams() {
				var commitSubList = []
				var creator = this.$store.state.user.id
				this.detailSource.forEach(toLocationCode => {
					toLocationCode.Items.forEach(item => {
						item.Locations.forEach(fromLocation => {
							fromLocation.Batchs.forEach(batch => {
								let subItem = batch.detail;

								if (subItem != undefined) {
									if (batch.Records.length > 0) {
										subItem.recordList = [];
										batch.Records.forEach(r => {
											let record = {};
											record.handleQty = r.qty;
											record.fromBatch = r.batch;
											record.fromContainerNumber = r
												.containerNumber;

											record.toContainerNumber = r
												.containerNumber;
											record.toInventoryStatus = r
												.inventoryStatus;
											record.toLocationCode = this
												.toLocationCode;
											record.supplierCode = r.supplierCode;

											record.fromParentPackingNumber = r
												.parentPackingNumber;

											record.fromPackingNumber = r
												.packingNumber;
											record.toPackingNumber = r
												.packingNumber;
											record.toPackUnit = r.packUnit;
											record.toBatch = r.batch;
											subItem.recordList.push(record);
										})
										commitSubList.push(deepCopyData(subItem));
									}
								}
							})
						})
					})
				})

				this.jobContent.subList = commitSubList
				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) {
				let requestLocation = this.detailSource.find(r => r.toLocationCode == record.toLocationCode);
				let item = requestLocation.Items.find(r => r.itemCode == record.itemCode);
				let itemHandleQty = 0;
				if (item != undefined) {
					item.Locations.forEach(l => {
						let batch = l.Batchs.find(b => (b.packingNumber == record.packingNumber || b
								.packingNumber == null || b.packingNumber == '') && b.batch ==
							record.batch);
						let handleQty = 0;
						if (batch != undefined) {
							batch.Records.forEach(res => {
								handleQty = calc.add(handleQty, res.qty)
							})
							batch.handleQty = handleQty;
							itemHandleQty = calc.add(itemHandleQty, handleQty)
							this.$refs.comScanIssuePack.calcBatchHandleQty(batch)
						}
					})
				}

				// item.handleQty=itemHandleQty;
			},

			scanPopupGetFocus() {
				if (this.$refs.scanPopup != undefined) {
					this.$refs.scanPopup.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();
			},
			itemCoceClick(e, item, index) {
				if (e.content.text == "移除") {
					this.jobContent.recordList.splice(index, 1);
				}
			},
			getPackScanResult(result) {
				console.log('扫描结果',result)
				this.jobContent.recordList.push({
					scaned:true,
					uom:this.jobContent.uom,
					handleQty:result.package.qty,// 提交数量
					toPackingNumber:'',// 到包装号
					toContainerNumber:'',//  到器具号
					toBatch:'',//  到批次
					toLocationCode:this.jobContent.toLocationCode,//  到库位代码
					toInventoryStatus:this.jobContent.inventoryStatus,//  库存状态
					supplierCode:result.package.supplierCode,//  供应商
					fromPackingNumber:result.label.packingNumber,//  从包装号
					fromContainerNumber:'',// 从器具号
					fromBatch:result.package.batch,//  从批次
					fromParentPackingNumber:result.package.parentNumber,// 从父包装
					fromLocationCode:result.balance.locationCode,//   从库位代码
					
				})
				
			},
			openScanDetailPopup() {
				var datacontent = {}
				//克隆对象，深度克隆，防止双向绑定同一个变量
				// Object.assign(datacontent, this.detailSource);
				// this.$refs.comScanIssuePack.openScanPopup(this.detailSource, this.jobContent);
				console.log('打开',this.businessType)
				this.$refs.scanPopup.openScanPopup(this.businessType);
				this.scanPopupGetFocus();
			},
			closeScanPopup() {
				this.updateCommitBtn();
			},
			scanLocationCode(location, code) {
				this.toLocationCode = code
			},
			getScanCount(subList) {
				var scanCount = 0;
				this.detailSource.forEach(toLocationCode => {
					toLocationCode.Items.forEach(item => {
						item.Locations.forEach(fromLocation => {
							fromLocation.Batchs.forEach(batch => {
								let subItem = batch.detail;
								if (batch.Records.length > 0) {
									scanCount = calc.add(scanCount, batch.Records.length)
								}
							})
						})
					})
				})
				return scanCount;
			}


		}
	};
</script>

<style scoped lang="scss">
	.page-header .header-view {
		display: flex;
		flex-direction: row;
		background-color: #fff;
		font-size: 35rpx;
		padding: 10rpx 20rpx;
		border-radius: 4px;
	}

	.left {
		display: flex;

		.time {
			margin-left: 10rpx;
			text-align: center;
			background-color: #DA8910;
			min-width: 40rpx;
			height: 40rpx;
			border-radius: 50%;
			color: white;
		}
	}
</style>