<!-- 发料任务详情 -->
<template>
	<page-meta root-font-size="16px"></page-meta>
	<view class="">
		<view class="top_card">
			<com-job-scan-detail :jobContent="datacontent" :isShowAllCountHint="false" :isShowScanHint="false"
				:allCount="allCount" :scanCount="scanCount">
			</com-job-scan-detail>
		</view>
		<view class="" style="margin-top: 20rpx; margin-left: 20rpx; margin-right: 20rpx;">
			<button type="primary" @click="showRecommend"> 推荐信息</button>
		</view>
		<scroll-view :scroll-top="scrollTop" scroll-y="true" @scrolltoupper="upper" @scrolltolower="lower"
			@scroll="scroll" class="scroll-detail">
			<view class="" style="margin-bottom:120rpx">
				<view class="detail-list margin_top" v-for="(item, index) in details" :key="item.id">
					<uni-swipe-action>
						<uni-swipe-action-item :right-options="options" :auto-close="false"
							@click="swipeClick($event,item,index)" style='background-color: #ffffff;'>
							<view class="detail-content">
								<view class="choose_main">
									<view class="ljh_box">
										<view class="tit_ljh">{{ item.itemCode }}</view>
										<view class="ljh_left desc_ljh">
											<view class="font_xs text_lightblue">{{ item.itemName }}</view>
											<view class="font_xs text_lightblue">{{ item.itemDesc1 }}</view>
										</view>
									</view>
									<view class="list_form">
										<view class="uni-container">
											<uni-table style="overflow-x: hidden;">
												<uni-tr>
													<uni-th width="50">数量</text></uni-th>
													<uni-th width="0" align="center">
													</uni-th>
													<uni-th width="270" align="center">
														<view
															style="display: flex;flex-direction: row;justify-content:center;align-items: center;">
															<com-number-box :ref="'comNumberBox_'+index"
																v-model="item.handledQty" :max="99999" :min="0"
																style='width: 100px;'
																@change="qtyChanged($event,item,index)">
															</com-number-box>
															<text class="text_black">({{item.uom}})</text>
														</view>
													</uni-th>
												</uni-tr>
												<uni-tr>
													<uni-th width="50">箱码</uni-th>
													<uni-th width="0" align="center">
													</uni-th>
													<uni-th width="270" align="center">
														<view class="text_packingCode">
															{{ item.handledPackingCode }}
														</view>
													</uni-th>
												</uni-tr>
												<uni-tr>
													<uni-th width="50">批次</uni-th>
													<uni-th width="0" align="center">
													</uni-th>
													<uni-th width="270" align="center">
														<view class="text_black">{{item.handledLot }}</view>
													</uni-th>
												</uni-tr>
												<uni-tr>
													<uni-th width="70">来源库位</uni-th>
													<uni-th width="0" align="center">
													</uni-th>
													<uni-th width="270" align="center">
														<view class="text_black">
															{{ item.handledFromLocationCode }}
														</view>
													</uni-th>
												</uni-tr>
											</uni-table>
										</view>
									</view>

								</view>
							</view>

						</uni-swipe-action-item>
					</uni-swipe-action>
				</view>
			</view>

		</scroll-view>
		<view class="uni-flex uni-row new_btn_bot">
			<button class="new_clear_btn btn_double" @click="clear()">清空</button>
			<button class="new_save_btn btn_double" @click="submit()">提交</button>
		</view>
		<com-balance ref='issueitems' @selectedItem='selectedBalanceItem'></com-balance>
		<win-scan-button @goScan='openScanPopup'></win-scan-button>
		<win-scan-by-pack ref="scanPopup" @getScanResult='getScanResult'></win-scan-by-pack>
		<recommendList ref="recommendList" title="推荐信息"></recommendList>
		<com-balance ref="balanceItems" @selectedItem='selectedBalanceItem'></com-balance>
		<com-message ref="comMessage" @afterCloseCommitMessage='closeCommitMessage()'
			@afterCloseScanMessage='closeScanMessage'></com-message>
	</view>
</template>

<script>
	import {
		getUnProducePickDetail,
		takeUnProduceIssueJob,
		cancelTakeUnProduceIssueJob,
		finshUnProducePickJob,
		getBalancesByFilter
	} from '@/api/index.js';
	import {
		getJobStatuStyle,
		getJobStatuDesc,
		showConfirmMsg,
		goHome,
		compareDesc,
		compareStr,
		getCurrDateTime,
		getCurrDateTimeAndT,
		scanSuccessAudio,
		scanFailedAudio,
		guid,
		getRemoveOption
	} from '@/common/basic.js';
	import comMessage from '@/mycomponents/common/comMessage.vue'
	import winScanButton from '@/mycomponents/wincom/winScanButton.vue'
	import winMulitScan from '@/mycomponents/wincom/winMulitScan.vue'
	import comBalance from '@/mycomponents/common/comBalance.vue'
	import comJobScanDetail from '@/mycomponents/comjob/comJobScanDetail.vue'
	import winScanByPack from '@/mycomponents/wincom/winScanByPack.vue'
	import comNumberBox from '@/mycomponents/common/comNumberBox.vue';
	import recommendList from '@/mycomponents/popup/recommendList.vue';
	export default {
		components: {
			comMessage,
			winScanButton,
			winMulitScan,
			comBalance,
			comJobScanDetail,
			winScanByPack,
			comNumberBox,
			recommendList
		},
		data() {
			return {
				id: "",
				datacontent: {},
				details: [], //实际
				facDetails: [],//推荐
				toLocation: '',
				scrollTop: 0,
				old: {
					scrollTop: 0
				},
				ispending: false,
				balancesItem: null,
				currentItem: null,
				currentScanLebel: null,
				allCount: 0,
				scanCount: 0,
				isPack: true,
				titleArray: ['箱标签'],
				options:[],
				recommendQty:0

			}
		},
		filters: {
			statusStyle: function(val) {
				return getJobStatuStyle(val);
			},
			statusColor: function(val) {
				return getJobStatuDesc(val);
			}
		},
		props: {
			itemCode: "",
		},
		onLoad(param) {
			this.id = param.id;
			this.options = getRemoveOption();
			if (param.jobStatus == 1) {
				this.receive((callback => {
					this.getDetail();
				}));
			} else {
				this.getDetail();
			}

		},
		onReady() {},
		//返回首页
		onNavigationBarButtonTap(e) {
			if (e.index === 0) {
				goHome();
			} else if (e.index === 1) {
				window.location.reload();
			}
		},
		//拦截返回按钮事件
		onBackPress(e) {
			//取消承接任务
			if (e.from == 'backbutton') {
				if (this.jobStatus == 2) {
					//取消承接任务	
					cancelTakeUnProduceIssueJob(this.id).then(res => {
						uni.navigateBack();
					}).catch(error => {
						uni.navigateBack();
					})
				} else {
					uni.navigateBack();
				}
				return true;
			}
		},
		mounted() {
			uni.setNavigationBarColor({
				frontColor: '#ffffff',
				backgroundColor: "#5A7CF3 !important"
			})
		},
		methods: {
			swipeClick(e, item, index) {
				let {
					content
				} = e;
				if (content.text === '移除') {
					uni.showModal({
						title: '提示',
						content: '是否移除选择的行?',
						success: res => {
							if (res.confirm) {
								this.details.splice(index, 1)
							}
						}
					});
				}
			},
			
			openScanPopup() {
				// if (this.allCount === this.scanCount) {
				// 	this.showMessage("零件已经全部扫描完成");
				// 	return;
				// }
				this.$refs.scanPopup.openScanPopup();
			},
			//加载零件信息
			getDetail() {
				let that = this;
				if (that.id == undefined) {
					return;
				}
				uni.showLoading({
					title: '加载中...',
					mask: true
				})
				let params = {
					id: that.id,
				};
				getUnProducePickDetail(params)
					.then(item => {
						that.datacontent = item;
						that.facDetails=item.facDetails
						that.details = [];
						uni.hideLoading();
						
					})
					.catch(err => {
						this.showMessage('未查找到详细信息')
						uni.hideLoading();
					});
			},

			showRecommend() {
				this.$refs.recommendList.openScanPopup(this.facDetails)
			},

			getScanResult(result) {
				this.currentItem = result;
				//扫描的ERP料号是否在任务列表中
				let item = this.facDetails.find(r => r.itemCode == result.data.itemCode);
				//在任务列表中
				if (item) {
					//校验箱码是否已经扫描
					let scanItem = this.details.find(r => r.handledPackingCode == result.data.code);
					if (scanItem) {
						scanFailedAudio()
						this.showMessage('扫描箱码[' + result.data.code + "]已经在列表中，请勿重复扫描")
					} else {
						this.getBalance(result, res => {
							if (res.totalCount === 1) {
								this.balancesItem = res.items[0];
								if (this.balancesItem) {
									var addItem = this.setItemInfo(result, this.balancesItem)
									if (item.recommendFromLocationErpCode != addItem.handledFromLocationErpCode) {
										this.showMessage('扫描箱码[' + result.data.code + "]的ERP储位与推荐的不在同一个ERP储位")
									} else {
										if(item.recommendPackingCode!= result.data.code){
											showConfirmMsg("扫描的箱码[" + result.data.code+"]与任务中的箱码["+item.recommendPackingCode+"]不一致，是否添加到列表中",res=>{
												if(res){
													this.details.unshift(addItem)
												}
											})
										}else {
											this.details.unshift(addItem)
										}
									}
								}
							} else {
								this.$refs['issueitems'].openPopup(res.items);
							}
						});

					}
				} else {
					scanFailedAudio()
					//不在任务列表中提示
					this.showMessage('扫描的ERP料号[' + result.data.itemCode + "]不在推荐任务列表中")
				}


			},

			setItemInfo(result, balance) {
				var item = {
					id: guid(),
					itemCode: result.data.itemCode,
					itemName: result.data.itemName,
					itemDesc1: result.data.itemDesc1,
					itemDesc2: result.data.itemDesc2,
					stdPackQty: result.data.stdPackQty,
					masterID: this.datacontent.id,

					recommendContainerCode: "",
					recommendPackingCode: result.data.packingCode,
					recommendSupplierBatch: result.data.supplierBatch,
					recommendArriveDate: result.data.arriveDate,
					recommendProduceDate: result.data.produceDate,
					recommendExpireDate: result.data.expireDate,
					recommendLot: result.data.lot,
					recommendFromLocationCode: balance.locationCode,
					recommendFromLocationArea: balance.locationArea,
					recommendFromLocationGroup: balance.locationCode,
					recommendFromLocationErpCode: balance.locationErpCode,
					recommendFromWarehouseCode: balance.warehouseCode,
					recommendQty: result.data.qty,
					uom: result.data.uom,

					handledContainerCode: "",
					handledPackingCode: result.data.packingCode,
					handledSupplierBatch: result.data.supplierBatch,
					handledArriveDate: result.data.arriveDate,
					handledProduceDate: result.data.produceDate,
					handledExpireDate: result.data.expireDate,
					handledLot: result.data.lot,
					handledFromLocationCode: balance.locationCode,
					handledFromLocationArea: balance.locationArea,
					handledFromLocationGroup: balance.locationCode,
					handledFromLocationErpCode: balance.locationErpCode,
					handledFromWarehouseCode: balance.warehouseCode,
					handledQty: result.data.qty,

					creatorId: guid(),
					creationTime: getCurrDateTimeAndT(),
					tenantId: guid(),
					lastModificationTime: getCurrDateTimeAndT(),
					lastModifierId: guid(),
					number: this.datacontent.number,
					remark: "",
					status: 2,
					reasonCode: "",
					caseCode: "",
					projCapacityCode: "",
					onceBusiCode: "",
					explain: "",
				}
				return item;
			},


			//查询库存记录
			getBalance(result, callback) {
				uni.showLoading({
					title: '扫描中...',
					mask: true
				})
				let params = {
					pageSize: 1000,
					pageIndex: 1,
					packingCode: result.data.code,
					itemCode: result.data.itemCode,
					lot: result.data.lot,
					sortBy: 'PackingCode asc'
				};
				getBalancesByFilter(params)
					.then(res => {
						if (res.totalCount === 0) {
							scanFailedAudio()
							this.showScanMessage('按ERP料号【' + result.data.itemCode + '】箱码【' + result.data
								.code +
								'】批次【' +
								result
								.data.lot + '】未查询到库存信息');
						} else {
							scanSuccessAudio()
							callback(res);
						}
						uni.hideLoading();
					})
					.catch(err => {
						scanFailedAudio()
						this.showScanMessage(err.message);
						uni.hideLoading();
					});
			},


			selectedBalanceItem(balanceItem) {
				var addItem = this.setItemInfo(result, this.balancesItem)
				if (item.recommendFromLocationErpCode != addItem.handledFromLocationErpCode) {
					this.showMessage('扫描箱码[' + result.data.code + "]的ERP储位与推荐的不在同一个ERP储位")
				} else {
					if(item.recommendPackingCode!= result.data.code){
						showConfirmMsg("扫描的箱码[" + result.data.code+"]与任务中的箱码["+item.recommendPackingCode+"]不一致，是否添加到列表中",res=>{
							if(res){
								this.details.unshift(addItem)
							}
						})
					}else {
						this.details.unshift(addItem)
					}
				}

			},
			// //接收
			receive(callback) {
				let params = {
					id: this.id
				};
				takeUnProduceIssueJob(params)
					.then(res => {
						callback(true);
					})
					.catch(err => {
						this.showMessage(err.message);
						callback(false);
					});
			},

			submit() {
				if (this.details.length == 0) {
					this.showMessage('扫描列表为0,请先扫描');
					return;
				}
				var hint = ""
				this.details.forEach(res => {
					var temp = this.facDetails.find(fac => {
						if (res.itemCode == fac.itemCode) {
							return fac
						}
					})
					if (temp && temp.recommendQty < res.handledQty) {
						hint += "ERP料号[" + res.itemCode + "]箱码[" + res.handledPackingCode + "]扫描数量["+res.handledQty+"]大于推荐的数量["+temp.recommendQty+"]"
					}
				})
				if (hint) {
					this.showMessage(hint);
				} else {
					this.finsh();
				}

			},



			finsh() {
				let that = this;
				uni.showLoading({
					title: "提交中...",
					mask: true
				});
				that.datacontent.completeUserId = localStorage.getItem('userId')
				that.datacontent.completeUserName = localStorage.getItem('userName_CN')
				that.datacontent.completeTime = getCurrDateTime();
				that.datacontent.worker = localStorage.userName_CN == "" ? localStorage.userName : localStorage
					.userName_CN;
				that.datacontent.details = that.details;
				let params = JSON.stringify(that.datacontent);
				console.log(params)
				finshUnProducePickJob(that.id, params)
					.then(res => {
						uni.hideLoading();
						if (res != null) {
							that.showCommitSuccessMessage();
						}
					})
					.catch(err => {
						that.showMessage(err.message);
						uni.hideLoading();
					});
			},

			//返回任务列表页
			backJobList(delay) {
				uni.navigateBack()
				// setTimeout(() => {
				// 	uni.navigateTo({
				// 		url: './unProducePick'
				// 	})
				// }, 1000)
			},

			clear() {
				this.scanCount = 0;
				this.currentItem = null;
				this.currentScanLebel = null;
				this.getDetail();
			},
			clearScanLocation() {
				this.currentItem = null;
			},
			showMessage(message) {
				this.$refs.comMessage.showMessage(message);
			},
			showScanMessage(message) {
				this.$refs.comMessage.showScanMessage(message);
			},

			closeScanMessage() {
				this.$refs.scanPopup.getfocus();
			},

			calcScanCount() {
				this.scanCount = this.facDetails.filter(r => r.scaned === true).length;
				this.closeScanPopup();
			},

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

			closeCommitMessage() {
				this.backJobList(0); //点关闭直接返回列表
				uni.hideLoading();
			},

			closeScanPopup() {
				if (this.allCount == this.scanCount) {
					this.$refs.scanPopup.closeScanPopup();
				}
			},


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

			scrollToTop() {
				let that = this;
				// 解决view层不同步的问题
				that.scrollTop = that.old.scrollTop
				this.$nextTick(function() {
					that.scrollTop = 0
				});
			},

			upper: function(e) {
				// console.log(e)
			},
			lower: function(e) {
				// console.log(e)
			},
			scroll: function(e) {
				// console.log(e)
				this.old.scrollTop = e.detail.scrollTop;
			},
			qtyChanged(value, item, index) {
				if (value <= 0) {
					this.showMessage('领料数量不能小于或等于0')
					item.handledQty = this.currentItem.data.qty
					this.$refs['comNumberBox_' + index][0].setValue(item.handledQty);
				} 
				// else if (value > this.currentItem.data.qty) {
				// 	item.handledQty = this.currentItem.data.qty
				// 	this.showMessage("实际领料数量不能大于申请数量")
				// 	this.$refs['comNumberBox_' + index][0].setValue(item.handledQty);
				// }
			},
		}
	}
</script>

<style scoped lang="scss">
</style>