<template>
	<view class="page-wraper">
		<view class="page-header">
			<view class="header_job_top">
				<job-top :dataContent="jobContent"></job-top>
			</view>
		</view>
		<view class="page-main">
			<scroll-view scroll-y="true" class="page-main-scroll">
				<view class="detail-list" v-for="(item, index) in detailSource" :key="item.id">
					<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.workShopCode}}
								</view>
							</view>
							<view class="cell_info">
								<view class="text_lightblue">生产线</view>
								<view>
									{{item.subList[0].productionLineCode}}
								</view>
							</view>
							<view class="cell_info">
								<view class="text_lightblue">班组</view>
								<view>
									{{jobContent.team}}
								</view>
							</view>
							<view class="cell_info">
								<view class="text_lightblue">班次</view>
								<view>
									{{jobContent.shift}}
								</view>
							</view>
						</view>
						<view class="split_line"></view>
					</view>
					<view class="">
						<com-product-detail-card :dataContent="item" :settingParam="jobContent" :isShowLocation="false"
							@remove="updateData" @updateData="updateData" :locationTypeList='toLocationTypeList'>
						</com-product-detail-card>
					</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="">
					<locationCompare title="收货库位" :isShowEdit="jobContent.allowModifyLocation=='TRUE'"
						:recommendLocationCode="jobToLocationCode" :locationCode="toLocationCode"
						@getLocation='scanLocationCode' :locationTypeList="toLocationTypeList"></locationCompare>
				</view>
				<view class=" uni-flex uni-row">
					<button class="btn_single_commit" hover-class="btn_commit_after" @click="commit">提交</button>
				</view>
			</view>
		</view>

		<win-scan-button @goScan='openScanPopup'></win-scan-button>
		<win-scan-fg-label ref="scanPopup" @getResult='getScanResult' title='制品标签'></win-scan-fg-label>
		<comMessage ref="comMessage"></comMessage>
	</view>
</template>

<script>
	import {
		getManagementPrecisions
	} from '@/common/balance.js';

	import {
		getProductReceiptJobDetail,
		takeProductReceiptJob,
		cancleTakeProductReceiptJob,
		productReceiptJobsubmit,
		getPrintProductReceiptList,
		getBalanceToPackage,
		batchPrintingLable
	} from '@/api/request2.js';
	import {
		goHome,
		navigateBack,
		getPackingNumberAndBatch,
		getSwitchInfoByCode
	} from '@/common/basic.js';

	import {
		getDirectoryItemArray,
		getInventoryStatusName
	} from '@/common/directory.js';

	import {
		getDataSource,
		createRecordInfo,
		calcHandleQty,
		getScanCount
	} from '@/common/detail.js';

	import {
		Decimal
	} from 'decimal.js'; //引入

	import {
		calc
	} from '@/common/calc'

	import winScanButton from '@/mycomponents/scan/winScanButton.vue'
	import locationCompare from '@/mycomponents/location/locationCompare.vue'
	import winScanFgLabel from "@/mycomponents/scan/winScanFgLabel.vue"
	import comDetailCard from "@/mycomponents/detail/comDetailCard.vue"
	import jobTop from '@/mycomponents/job/jobTop.vue'
	import comProductDetailCard from "@/pages/productReceipt/coms/comProductDetailCard.vue"
	import storage from '@/common/utils/storage.js'

	export default {
		name: 'receipt_detail',
		components: {
			winScanButton,
			comDetailCard,
			locationCompare,
			winScanFgLabel,
			jobTop,
			comProductDetailCard,
		},
		data() {
			return {
				id: '',
				receiptJob: {},
				toLocationCode: '',
				isShowPackingCode: true,
				scanCount: 0,
				jobContent: {}, //任务内容
				subList: [], //接口返回的任务subList
				detailSource: [], //绑定在页面上的数据源
				toLocationTypeList: [],
				managementList: [],
				jobStatus: "",
				jobToLocationCode: "",
				fgList: [],
				itemCode: "",
				scanedPackingNumber: ''
			};
		},
		onLoad(option) {
			this.id = option.id;
			this.scanedPackingNumber = option.scaned || '';
			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") {
					//取消承接任务	
					cancleTakeProductReceiptJob(this.id).then(res => {
						uni.navigateBack();
					}).catch(error => {
						uni.navigateBack();
					})
				} else {
					uni.navigateBack();
				}

				return true;
			}

		},

		onPullDownRefresh() {
			this.getDetail();
			uni.stopPullDownRefresh();
		},

		mounted() {

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

			getDetail() {
				var that = this;
				uni.showLoading({
					title: "加载中....",
					mask: true
				});
				getProductReceiptJobDetail(that.id).then(res => {
					uni.hideLoading();
					if (res.data == null) {
						that.showMessage('未获取到详情');
					} else {
						if (res.data.subList.length > 0) {
							that.jobContent = res.data;
							that.subList = res.data.subList;
							that.jobStatus = res.data.status
							that.jobToLocationCode = that.subList[0].toLocationCode
							if(that.jobContent.allowModifyLocation=='FALSE'){
								that.toLocationCode = that.subList[0].toLocationCode
							}
							that.toLocationTypeList = getDirectoryItemArray(that.jobContent.toLocationTypes)
							that.detailSource = getDataSource(that.subList)
							that.detailSource.forEach(r => {
								r.subList.forEach(s => {
									if (this.scanedPackingNumber && this.scanedPackingNumber == s
										.packingNumber) s.scaned = true
								})
							})


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

			getScanResult(result) {
				//TODO缺少零件号的对应关系
				let that = this;
				if (that.detailSource.length > 0) {
					let item = that.detailSource[0]; //应该按零件号查找
					result.uom = item.uom;
					if (item.subList.length > 0) {
						let subItem = item.subList[0];
						subItem.scaned = true;
						if (subItem.fgList == undefined) {
							subItem.fgList = [];
						}

						if (subItem.fgList.length == 0) {
							subItem.fgList.push(result);
							that.calcFgQty(this.detailSource);
						} else {
							var itemIndex = subItem.fgList.findIndex(r =>
								r.itemCode == result.itemCode &&
								r.productDate == result.productDate &&
								r.order == result.order);
							if (itemIndex == -1) {
								subItem.fgList.push(result);
								that.calcFgQty(this.detailSource);
							} else {
								this.showQuestionMessage("标签【" + result.content + '】已经扫描，是否移除', confirm => {
									subItem.fgList.splice(itemIndex, 1)
									that.calcFgQty(this.detailSource);
								})
							}
						}

						setTimeout(r => {
							this.scanPopupGetFocus();
						}, 500)
					}
				}
			},

			calcFgQty() {
				let that = this;
				that.detailSource.forEach(item => {
					item.subList.forEach(pack => {
						pack.handleQty = new Decimal(0).toNumber();
						pack.fgList.forEach(fg => {
							if (fg != null) {
								fg.qty = new Decimal(fg.qty).toNumber();
								pack.handleQty = calc.add(pack.handleQty, fg.qty);
								// item.qty = calc.add(item.qty, detail.qty);
							}
						})
						// 扫满箱后应该自动提交
						if (pack.scaned && pack.qty == pack.fgList.length) {
							this.commit()
						}
					})
				})
			},

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

			openScanPopup() {
				var itemCode = this.detailSource[0].subList[0].itemCode

				// itemCode = "015553147"
				console.log("物料", itemCode)
				this.$refs.scanPopup.openScanPopup(itemCode);
			},

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

			scanLocationCode(location, code) {
				this.toLocationCode = code
				this.detailSource.forEach(item => {
					item.subList.forEach(detail => {
						detail.toLocationCode = code
					})
				})
			},

			checkLocation() {
				var isPass = true;
				if (this.toLocationCode == "" || this.toLocationCode == null) {
					this.showMessageHint('请扫描收货库位', callback => {
						this.$refs.comScanLocation.showLocation();
					})
					return isPass = false;
				}
				return isPass;
			},

			showMessageHint(hint, callback) {
				this.$refs.comMessage.showErrorMessage(hint, res => {
					if (res) {
						callback()
					}
				});
			},
			//打印功能
			print() {
				let _this = this
				let packingNumber = []
				this.detailSource.forEach(item => {
					item.subList.forEach(detail => {
						if (detail.scaned) {
						// var info = getPackingNumberAndBatch(this.managementList, detail.itemCode,
						// 	detail.packingNumber, detail.batch);
						// detail.toPackingNumber = info.packingNumber;
							packingNumber.push(detail.packingNumber)
						}
					})
				})
				// #ifdef APP			
				getPrintProductReceiptList({
					packingNumber: packingNumber.join(','),
					type: 'MakeLabel'
				}).then(res => {
					console.log('打印', res)
					let pointData = []
					res.data.forEach(item => {
						pointData.push({
							barcodeString: item.barcodeString, //标签
							itemCode: item.itemCode || '', //物品代码
							itemName: item.itemName || '', //物品名称
							itemDesc1: item.itemDesc1 || '', //物品描述
							relateNumber: item.relateNumber || '', //relateNumber包装号
							batch: item.batch || '', //批次
							productionLineCode: item.productionLineCode || '', //生产线
							shiftCode: item.shiftCode || '', //班次
							qty: item.qty || '', //数量
							printTimes: item.printTimes || '' //打印时间
						})
					})
					console.log('pointData', pointData)

					uni.navigateTo({
						url: `/pages/pointProductReceipt/index?points=${JSON.stringify(pointData)}`
					});

				}).catch(error => {
					_this.showErrorMessage(error)
				})
				// #endif
				// #ifdef H5
				getBalanceToPackage({
					packingNumber: packingNumber.join(',')
				}).then(res => {
					console.log('PC打印', res)
					_this.getH5BatchPrintingLable(res.data.number)

				}).catch(error => {
					_this.showErrorMessage(error)
				})

				// #endif

			},

			getH5BatchPrintingLable( number) {
				let _this = this
				batchPrintingLable(number).then(resLable => {
					console.log('batchPrintingLable', resLable)
					const webUrl = `${import.meta.env.VITE_JMREPORT_BASE_URL}/jmreport/view/922734157577715712`
					const webData = {
						token: storage.getStorage(storage.constant.token),
						asn_number: resLable.data
					}
					uni.navigateTo({
						url: `/pages/pointProductReceipt/webview?url=${webUrl}&webData=${JSON.stringify(webData)}`
					});
				})
			},
			commit() {
				// this.scanCount = getScanCount(this.subList);
				// if (this.scanCount == 0) {
				// 	this.showErrorMessage("扫描数为0,请先扫描")
				// 	return;
				// }
				//校验库位、
				if (!this.checkLocation()) {
					return
				}
				var valiDate =getSwitchInfoByCode("fgProductReceipCommitValidate")
				this.detailSource.forEach(item => {
					item.subList.forEach(subitem => {
						if(valiDate){
							if (subitem.handleQty == undefined) {
								this.showMessage("还没扫码成品不能提交")
							} else {
								if (subitem.handleQty != subitem.packQty) {
									this.showQuestionMessage('制品数量不等于包装数量,是否继续提交?', res => {
										if (res) {
											this.submitJob();
										}
									});
								} else {
									this.submitJob();
								}
							}
						}else {
							subitem.handleQty=subitem.qty
							subitem.scaned = true
							this.submitJob();
						}
						
					})
				})
			},

			submitJob() {
				uni.showLoading({
					title: "提交中....",
					mask: true
				});
				var itemCodes = []
				this.detailSource.forEach(item => {
					itemCodes.push(item.itemCode)
				})
				getManagementPrecisions(itemCodes, this.toLocationCode, res => {
					if (res.success) {
						this.managementList = res.list;
						var params = this.setParams();
						console.log("提交参数", JSON.stringify(params));
						productReceiptJobsubmit(params).then(res => {
							uni.hideLoading()
							if (res.data) {
								this.showCommitSuccessMessage("提交成功<br>生成装配收货记录<br>" + res.data, )
							} else {
								this.showErrorMessage("提交失败[" + res.msg + "]")
							}
						}).catch(error => {
							uni.hideLoading()
							this.showErrorMessage(error)
						})
					} else {
						uni.hideLoading();
						this.showErrorMessage(res.message);
					}
				});
			},

			setParams() {
				var subList = []
				var creator = this.$store.state.user.id
				this.detailSource.forEach(item => {
					item.subList.forEach(detail => {
						if (detail.scaned) {
							var info = getPackingNumberAndBatch(this.managementList, detail.itemCode,
								detail.packingNumber, detail.batch);
							detail.toPackingNumber = info.packingNumber;
							detail.toBatch = info.batch;
							detail.toContainerNumber = '';
							detail.toInventoryStatus = detail.inventoryStatus
							detail.toLocationCode = this.toLocationCode
							detail.available = 'TRUE'
							if (detail.fgList) {
								detail.fgList.forEach(res => {
									res.outsideItemCode = res.itemCode
									res.outsideProduceDate = res.productDate
									res.outsideSerialNumber = res.order
									res.lowerLim=res.content
								})
							}else {
								detail.fgList=[]
							}
							subList.push(detail)
						}
					})
				})
				this.jobContent.available = 'TRUE'
				this.jobContent.subList = subList
				this.jobContent.creator = creator;
				return this.jobContent;
			},


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

			scanPopupLoseFocus() {
				if (this.$refs.scanPopup != undefined) {
					this.$refs.scanPopup.losefocus();
				}
			},

			showMessage(message) {
				setTimeout(r => {
					this.scanPopupLoseFocus();
					this.$refs.comMessage.showMessage(message, res => {
						if (res) {
							this.scanPopupGetFocus();
						}
					});
				})
			},

			showErrorMessage(message) {
				setTimeout(r => {
					this.scanPopupLoseFocus();
					this.$refs.comMessage.showErrorMessage(message, res => {
						if (res) {
							this.scanPopupGetFocus();
						}
					});
				})
			},

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

			showQuestionMessage(hint, callback) {
				this.$refs.comMessage.showQuestionMessage(hint, res => {
					if (res) {
						callback(true)
					}
				});
			}
		}
	}
</script>

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