<!-- 发料任务详情 -->
<template>
	<page-meta root-font-size="16px"></page-meta>
	<view class="">
		<view class="top_card">
			<com-job-scan-detail :jobContent="datacontent" :allCount="allCount" :isShowScanHint="false"
				allCountHint="箱数">
			</com-job-scan-detail>
		</view>
		<scroll-view scroll-y="true" @scrolltoupper="upper" @scrolltolower="lower" @scroll="scroll"
			class="scroll-detail">
			<view class="" v-for="(item, index) in details" :key="index">
				<view class="detail-list margin_top">
					<!-- 单选卡片 -->
					<view class="detail-content">
						<view class="choose_main">
							<view class="ljh_box">
								<view class="tit_ljh">{{ item.itemCode }}</view>
								<view class="ljh_left">
									<view class="font_xs text_lightblue">{{ item.itemName }}</view>
									<view class="font_xs text_lightblue">{{ item.itemDesc1 }}</view>
								</view>
							</view>

							<view class="list_form hold_form">
								<view class="uni-container">
									<uni-table style="">
										<uni-tr>
											<uni-th width="100" align="center">
												<text
													style="font-weight:800; font-size: 35rpx; color: black; ">推荐</text>
											</uni-th>
											<uni-th width="120" align="center">来源</uni-th>
											<uni-th width="120" align="center">目标</uni-th>
										</uni-tr>

										<uni-tr>
											<uni-td width="100" align="center">箱码</uni-td>
											<uni-td width="120" align="center">
												{{item.recommendFromPackingCode}}</uni-td>
											<uni-td width="120" align="center"> {{item.recommendToPackingCode}}</uni-td>
										</uni-tr>
										<uni-tr>
											<uni-td width="100" align="center">批次</uni-td>
											<uni-td width="120" align="center">{{item.recommendFromLot}}</uni-td>
											<uni-td width="120" align="center">{{item.recommendToLot}}</uni-td>
										</uni-tr>
										<uni-tr>
											<uni-td width="100" align="center">库位</uni-td>
											<uni-td width="120" align="center">
												{{item.recommendFromLocationCode}}</uni-td>
											<uni-td width="120" align="center">
												{{item.recommendToLocationCode}}</uni-td>
										</uni-tr>
										<uni-tr>
											<uni-td width="100" align="center">数量({{item.uom}})</uni-td>
											<uni-td width="120" align="center">{{item.recommendFromQty}}</uni-td>
											<uni-td width="120" align="center">{{item.recommendToQty}}</uni-td>
										</uni-tr>

									</uni-table>
								</view>
							</view>

							<view class="list_form hold_form">
								<view class="uni-container">
									<uni-table style="">
										<uni-tr>
											<uni-th width="100" align="center">
												<text style="font-weight:800; font-size: 35rpx; color: black; ">库移
												</text>
											</uni-th>
											</uni-th>
											<uni-th width="120" align="center">来源</uni-th>
											<uni-th width="120" align="center">目标</uni-th>
										</uni-tr>

										<uni-tr>
											<uni-td width="100" align="center">箱码</uni-td>
											<uni-td width="120" align="center">
												{{item.transferLibFromPackingCode}}</uni-td>
											<uni-td width="120" align="center">
												{{item.transferLibToPackingCode}}</uni-td>
										</uni-tr>
										<uni-tr>
											<uni-td width="100" align="center">批次</uni-td>
											<uni-td width="120" align="center">{{item.transferLibFromLot}}</uni-td>
											<uni-td width="120" align="center">{{item.transferLibToLot}}</uni-td>
										</uni-tr>
										<uni-tr>
											<uni-td width="100" align="center">库位</uni-td>
											<uni-td width="120" align="center">
												{{item.transferLibFromLocationCode}}</uni-td>
											<uni-td width="120" align="center">
												{{item.transferLibToLocationCode}}</uni-td>
										</uni-tr>
										<uni-tr>
											<uni-td width="100" align="center">数量({{item.uom}})</uni-td>
											<uni-td width="120" align="center">{{item.transferLibFromQty}}</uni-td>
											<uni-td width="120" align="center">{{item.transferLibToQty}}</uni-td>
										</uni-tr>

									</uni-table>
								</view>
							</view>

							<view class="list_form hold_form">
								<view class="uni-container">
									<uni-table style="">
										<uni-tr>
											<uni-th width="100" align="center">
												<text
													style="font-weight:800; font-size: 35rpx; color: black; ">实际</text></uni-th>
											<uni-th width="120" align="center">来源</uni-th>
											<uni-th width="120" align="center">目标</uni-th>
										</uni-tr>

										<uni-tr>
											<uni-td width="100" align="center">箱码</uni-td>
											<uni-td width="120" align="center"> {{item.handledFromPackingCode}}</uni-td>
											<uni-td width="120" align="center"> {{item.handledToPackingCode}}</uni-td>
										</uni-tr>
										<uni-tr>
											<uni-td width="100" align="center">批次</uni-td>
											<uni-td width="120" align="center">{{item.handledFromLot}}</uni-td>
											<uni-td width="120" align="center">{{item.handledToLot}}</uni-td>
										</uni-tr>
										<uni-tr>
											<uni-td width="100" align="center">库位</uni-td>
											<uni-td width="120" align="center">
												{{item.handledFromLocationCode}}</uni-td>
											<uni-td width="120" align="center"> {{item.handledToLocationCode}}</uni-td>
										</uni-tr>
										<uni-tr>
											<uni-td width="100" align="center">数量({{item.uom}})</uni-td>
											<uni-td width="120" align="center">{{item.handledFromQty}}</uni-td>
											<uni-td width="120" align="center">{{item.handledToQty}}</uni-td>
										</uni-tr>

									</uni-table>
								</view>
							</view>

						</view>
						<view class="choose_marked" v-if="item.scaned">
							<image src="@/static/image_marked.svg"></image>
						</view>
					</view>
				</view>
				<view class="" style="margin-left: 50rpx; margin-right: 50rpx;">
					<button type="primary" size="default" @click="recommend"> 推荐库存</button>
				</view>
			</view>

		</scroll-view>
		<view class="uni-flex uni-row new_btn_bot" v-if="showBtn">
			<button class="new_clear_btn btn_double" @click="clear()">清空</button>
			<button class="new_save_btn btn_double" @click="submit()">提交</button>
		</view>
		<selectClickList ref="selectPopup" title="推荐信息" @select="selectPlan"></selectClickList>
		<winScanButtonTop @goScan='openScanPopupTo' title="箱码"></winScanButtonTop>
		<win-scan-button @goScan='openLocationTo' title="目标库位"></win-scan-button>
		<win-scan-by-pack ref="scanPopupTo" @getScanResult='getScanResultTo' title="箱码"></win-scan-by-pack>
		<winScanLocationCode ref="locationTo" title="目标库位" @getLocation="geToLocation"></winScanLocationCode>
		<com-message ref="comMessage" @afterCloseCommitMessage='closeCommitMessage()'
			@afterCloseScanMessage='closeScanMessage'></com-message>
	</view>
</template>

<script>
	import {
		getCoatingIssueDetail,
		takeCoatingIssueJob,
		cancelTakeCoatingIssueJob,
		finshCoatingIssueJob,
		getRecommendBalance,
		balances,
		getBalanceRemoveInAndOut
	} from '@/api/index.js';
	import {
		getJobStatuStyle,
		getJobStatuDesc,
		showConfirmMsg,
		goHome,
		compareDesc,
		compareStr,
		getCurrDateTime,
		navigateBack,
		scanSuccessAudio,
		scanFailedAudio
	} from '@/common/basic.js';
	import comMessage from '@/mycomponents/common/comMessage.vue'
	import winScanButton from '@/mycomponents/wincom/winScanButton.vue'
	import winScanButtonTop from '@/mycomponents/wincom/winScanButtonTop.vue'
	import winScanButtonBottom from '@/mycomponents/wincom/winScanButtonBottom.vue'

	import winMulitScan from '@/mycomponents/wincom/winMulitScan.vue'
	import comJobScanDetail from '@/mycomponents/comjob/comJobScanDetail.vue'
	import winScanByPack from '@/mycomponents/wincom/winScanByPack.vue'
	import comNumberBox from '@/mycomponents/common/comNumberBox.vue';
	import winScanLocationCode from '@/mycomponents/wincom/winScanLocationCode.vue';
	import selectClickList from "@/mycomponents/popup/selectClickList.vue"

	export default {
		components: {
			comMessage,
			winScanButton,
			winScanButtonTop,
			winScanButtonBottom,
			winMulitScan,
			comJobScanDetail,
			winScanByPack,
			comNumberBox,
			winScanLocationCode,
			selectClickList
		},
		data() {
			return {
				id: "",
				datacontent: {},
				details: {},
				toLocation: '',
				scrollTop: 0,
				old: {
					scrollTop: 0
				},
				ispending: false,
				balancesItem: null,
				allCount: 0,
				isPack: true,
				titleArray: ['箱标签'],
				jobStatus: "",
				toLocationInfo: {},
				handleToPackingCodeLocationCode: "",
				showBtn: true
			}
		},
		props: {
			itemCode: "",
		},
		onLoad(param) {
			this.id = param.id;
			this.getDetail();
		},
		//返回首页
		onNavigationBarButtonTap(e) {
			if (e.index === 0) {
				if (this.datacontent.isClaims && this.datacontent.claimsUserId == localStorage.getItem('userId')) {
					//取消承接任务	
					cancelTakeCoatingIssueJob(this.id).then(res => {}).catch(error => {})
				}
				goHome();
			} else if (e.index === 1) {
				window.location.reload();
			}
		},
		//拦截返回按钮事件
		onBackPress(e) {
			//已经接收但是没提交任务
			if (e.from == 'backbutton') {
				if (this.datacontent.isClaims && this.datacontent.claimsUserId == localStorage.getItem('userId')) {
					//取消承接任务	
					cancelTakeCoatingIssueJob(this.id).then(res => {
						uni.navigateBack();
					}).catch(error => {
						uni.navigateBack();
					})
				} else {
					uni.navigateBack();
				}
				return true;
			}
		},
		mounted() {
			uni.setNavigationBarColor({
				frontColor: '#ffffff',
				backgroundColor: "#5A7CF3 !important"
			})
		},
		methods: {
			openScanPopupTo() {
				this.$refs.scanPopupTo.openScanPopup();
			},
			openLocationTo() {
				this.$refs.locationTo.openScanPopup()
			},

			geToLocation(locationInfo) {
				var current = this.details[0]
				if (locationInfo.code != current.recommendToLocationCode) {
					scanFailedAudio()
					this.showMessage(" 扫描目标库位[" + locationInfo.code + "]与推荐目标库位[" + current
						.recommendToLocationCode + "]不一致,请重新扫描")
					return;
				}
				scanSuccessAudio()
				current.handledToLocationCode = locationInfo.code
				current.handledToLocationArea = locationInfo.areaCode
				current.handledToLocationGroup = locationInfo.locationGroupCode
				current.handledToLocationErpCode = locationInfo.erpLocationCode
			},
			//加载零件信息
			getDetail() {
				let that = this;
				if (that.id == undefined) {
					return;
				}
				uni.showLoading({
					title: '加载中...',
					mask: true
				})
				let params = {
					id: that.id,
				};
				getCoatingIssueDetail(params)
					.then(item => {
						uni.hideLoading();
						console.log('item', item);
						that.datacontent = item;
						that.jobStatus = item.jobStatus;
						that.details = item.details;
						if (that.details != null) {
							that.details.forEach(
								r => {
									r.scaned = false;
									r.scanDate = new Date()
									r.handledFromContainerCode = r.recommendFromContainerCode
									r.handledFromPackingCode = r.recommendFromPackingCode
									r.handledFromSupplierBatch = r.recommendFromSupplierBatch
									r.handledFromArriveDate = r.recommendFromArriveDate
									r.handledFromProduceDate = r.recommendFromProduceDate
									r.handledFromExpireDate = r.recommendFromExpireDate
									r.handledFromLot = r.recommendFromLot
									// r.handledFromLocationCode = r.recommendFromLocationCode
									// r.handledFromLocationArea = r.recommendFromLocationArea
									// r.handledFromLocationGroup = r.recommendFromLocationGroup
									// r.handledFromLocationErpCode = r.recommendFromLocationErpCode
									// r.handledFromWarehouseCode = r.recommendFromWarehouseCode
									r.handledFromQty = r.recommendFromQty
									// r.handledToQty = r.handledFromQty
								}
							);
							that.ispending = item.jobStatus === 2;
							this.allCount = that.details.length;
							this.setReceived();
						}

					})
					.catch(err => {
						uni.hideLoading();
						this.showMessage('未查找到详细信息')

					});
			},
			setReceived() {
				//是否承接
				//已经承接
				if (this.datacontent.isClaims) {
					this.datacontent.jobStatus = 2
					//承接并且承接人是自己显示，不是自己隐藏
					if (this.datacontent.claimsUserId == localStorage.getItem('userId')) {
						this.showBtn = true
					} else {
						this.showBtn = false
					}
				} else {
					//未承接，调用承接接口，承接成功后显示按钮
					this.receive((callback => {
						if (callback) {
							this.datacontent.isClaims = true;
							this.datacontent.jobStatus = 2
							this.showBtn = true
							this.datacontent.claimsUserName = localStorage.getItem('userName')
							this.datacontent.claimsUserId = localStorage.getItem('userId')
						} else {
							this.showBtn = false
							this.datacontent.isClaims = false;
							this.datacontent.jobStatus = 1
							this.datacontent.claimsUserId = ""
						}
					}));
				}
			},

			getScanResultTo(result) {
				var fromData = result.data;
				var data = this.details.filter(r => r.itemCode == result.data.itemCode)
				if (data.length == 0) {
					scanFailedAudio()
					this.showMessage("扫描的箱码[" + fromData.code + "]的物品不在列表中")
					return;
				}
				if (this.jobStatus == 30) {
					if (fromData.code == this.details[0].recommendFromPackingCode) {
						scanFailedAudio()
						this.showMessage("请先完成库移后在扫描箱码")
					} else {
						scanFailedAudio()
						setTimeout(res => {
							showConfirmMsg("扫描的箱码[" + fromData.code + "]与推荐的箱码[" + this.details[0]
								.recommendFromPackingCode +
								"]不一致,是否继续发料?",
								res => {
									if (res) {
										this.setData(result, data, fromData)
									}
								})
						})
					}
				} else {
					this.setData(result, data, fromData)
				}

			},
			setData(result, data, fromData) {
				this.getBalance(result, res => {
					if (res.totalCount > 0) {
						var balancesItem = res.items[0];
						var item = data[0];
						if (balancesItem.lot == item.recommendToLot) {
							scanSuccessAudio()
							item.handledToContainerCode = balancesItem.containerCode
							item.handledToPackingCode = balancesItem.packingCode
							item.handledToSupplierBatch = balancesItem.supplierBatch
							item.handledToArriveDate = balancesItem.arriveDate
							item.handledToProduceDate = balancesItem.produceDate
							item.handledToExpireDate = balancesItem.expireDate
							item.handledToLot = balancesItem.lot
							item.handledToWarehouseCode = balancesItem.warehouseCode
							item.handledToQty = balancesItem.qty
							item.stdPackQty = balancesItem.stdPackQty

							item.handledFromContainerCode = balancesItem.containerCode
							item.handledFromPackingCode = balancesItem.packingCode
							item.handledFromSupplierBatch = balancesItem.supplierBatch
							item.handledFromArriveDate = balancesItem.arriveDate
							item.handledFromProduceDate = balancesItem.produceDate
							item.handledFromExpireDate = balancesItem.expireDate
							item.handledFromLot = balancesItem.lot
							item.handledFromWarehouseCode = balancesItem.warehouseCode
							item.handledFromQty = balancesItem.qty
							item.handledFromLocationCode = balancesItem.locationCode
							item.handleToPackingCodeLocationCode = balancesItem.locationCode
						} else {
							scanFailedAudio()
							showConfirmMsg("箱码[" + fromData.code + "]的批次[" + balancesItem.lot + "]与推荐目标批次[" + item
								.recommendToLot + "]不一致,是否继续发料", res => {
									if (res) {
										item.handledToContainerCode = balancesItem.containerCode
										item.handledToPackingCode = balancesItem.packingCode
										item.handledToSupplierBatch = balancesItem.supplierBatch
										item.handledToArriveDate = balancesItem.arriveDate
										item.handledToProduceDate = balancesItem.produceDate
										item.handledToExpireDate = balancesItem.expireDate
										item.handledToLot = balancesItem.lot
										item.handledToWarehouseCode = balancesItem.warehouseCode
										item.handledToQty = balancesItem.qty
										item.stdPackQty = balancesItem.stdPackQty

										item.handledFromContainerCode = balancesItem.containerCode
										item.handledFromPackingCode = balancesItem.packingCode
										item.handledFromSupplierBatch = balancesItem.supplierBatch
										item.handledFromArriveDate = balancesItem.arriveDate
										item.handledFromProduceDate = balancesItem.produceDate
										item.handledFromExpireDate = balancesItem.expireDate
										item.handledFromLot = balancesItem.lot
										item.handledFromWarehouseCode = balancesItem.warehouseCode
										item.handledFromQty = balancesItem.qty
										item.handledFromLocationCode = balancesItem.locationCode
										item.handleToPackingCodeLocationCode = balancesItem.locationCode
									}
								})
						}
						this.closeScanPopup()
						this.$forceUpdate()
					}
				});
			},


			//查询库存记录
			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,
					// inventoryStatus: 2, //库存状态默认2
					// locationTypes: [2, 3],
					// sortBy: 'PackingCode asc'

				};
				if (this.details[0].recommendFromPackingCode == result.data.code) {
					balances(params)
						.then(res => {
							if (res.totalCount === 0) {
								scanFailedAudio()
								this.showScanMessage('按箱码【' + result.data.code + '】未查询到库存信息');
							} else {
								callback(res);
							}
							uni.hideLoading();
						})
						.catch(err => {
							scanFailedAudio()
							this.showScanMessage(err.message);
							uni.hideLoading();
						});
				} else {
					getBalanceRemoveInAndOut(params)
						.then(res => {
							if (res.totalCount === 0) {
								scanFailedAudio()
								this.showScanMessage('按箱码【' + result.data.code + '】未查询到库存信息');
							} else {
								callback(res);
							}
							uni.hideLoading();
						})
						.catch(err => {
							scanFailedAudio()
							this.showScanMessage(err.message);
							uni.hideLoading();
						});
				}
			},

			recommend() {
				var itemCode = this.details[0].itemCode
				var productLine = this.details[0].prodLine
				if (!itemCode) {
					this.showMessage("物料为空")
					return;
				}
				if (!productLine) {
					this.showMessage("生产线为空")
					return;
				}

				uni.showLoading({
					title: "加载中",
					mask: true
				})

				getRecommendBalance(itemCode, productLine, true).then(res => {
					uni.hideLoading()
					if (res.length > 0) {
						this.$refs.selectPopup.openScanPopup(res)
					} else {
						this.showMessage("暂无推荐库存")
					}
				}).catch(error => {
					uni.hideLoading()
					this.showMessage(error)
				})
			},

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

			submit() {
				let that = this;
				if (that.details.length === 0) {
					this.showMessage('该任务没有要上架的零件');
					return;
				}
				if (!that.details[0].handledToPackingCode) {
					this.showMessage('请先扫描箱码');
					return;
				}
				if (!that.details[0].handledToLocationCode) {
					this.showMessage('请先扫描目标库位');
					return;
				}
				that.finsh();

			},


			finsh() {
				let that = this;
				uni.showLoading({
					title: "提交中...",
					mask: true
				});
				let params = that.details[0];
				// console.log("提交",JSON.stringify(params))
				finshCoatingIssueJob(that.id, params.id, params)
					.then(res => {
						uni.hideLoading();
						that.showCommitSuccessMessage();
					})
					.catch(err => {
						that.showMessage(err.message);
						uni.hideLoading();
					});
			},

			clear() {
				this.handleToPackingCodeLocationCode = ""
				this.getDetail();
			},
			showMessage(message) {
				this.$refs.comMessage.showMessage(message);
			},
			showScanMessage(message) {
				this.$refs.comMessage.showScanMessage(message);
			},

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

			closeCommitMessage() {
				navigateBack(1)
				uni.hideLoading();
			},

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

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

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

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

			scroll: function(e) {
				// console.log(e)
				this.old.scrollTop = e.detail.scrollTop;
			},
			qtyChanged(value, item, index) {
				if (value <= 0) {
					this.showMessage('发料数量不能小于或等于0')
					item.handledQty = item.defaultHandleQty
					this.$refs['comNumberBox_' + index][0].setValue(item.handledQty);
				} else if (value > item.defaultHandleQty) {
					item.handledQty = item.defaultHandleQty
					this.showMessage('发料数量不能大于叫料数量:' + item.handledQty)
					this.$refs['comNumberBox_' + index][0].setValue(item.handledQty);
				}
			},
		}
	}
</script>

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