<template>
	<view class="">
		<!-- <com-empty-view v-if="jobList.length==0"></com-empty-view> -->
		<com-blank-view @goScan='openScanPopup' v-if="jobList.length==0"></com-blank-view>
		<view v-if="jobList.length>0" style="padding-bottom: 110rpx;">
			<uni-swipe-action ref="swipeAction">
				<view v-for="(item, index) in jobList" :key="index">
					<uni-swipe-action-item :right-options="detailOptions" @click="swipeClick($event,item)">
						<com-receipt-job-card :dataContent="item" @click='openJobDetail(item)' :isShowSupplierQty='true'
							:isShowBatch='false' :isShowBatchDeliNo='true'></com-receipt-job-card>
					</uni-swipe-action-item>
				</view>
			</uni-swipe-action>
		</view>
		<view class="page-footer" v-if="jobList.length>0">
			<button class="btn_single_clear" hover-class="btn_commit_after" @click="clearAll">清空</button>
			<button class="btn_single_commit" hover-class="btn_commit_after" @click="commit">提交</button>
		</view>
		<receipt-info-popup ref='jobInfoPopup'></receipt-info-popup>
		<receipt-job-list-popup ref="jobListPopup" @selectedItem="selectedItem"></receipt-job-list-popup>
		<win-scan-button @goScan='openScanPopup'></win-scan-button>
		<winScanPackJob :title="scanHintTitle" ref="scanPopup" @getResult='getScanResult'></winScanPackJob>
		<comMessage ref="comMessage"></comMessage>
	</view>
</template>

<script>
	import {
		getPurchaseReceiptASNJobList,
		takePurchaseReceiptJob,
		cancleTakePurchaseReceiptJob,
		purchaseReceiptJobSubmitASN
	} from '@/api/request2.js';

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

	import {
		getDetailOption,
		getDetailRemoveOption
	} from '@/common/array.js';

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

	import winScanButton from '@/mycomponents/scan/winScanButton.vue'
	import winScanPackJob from "@/mycomponents/scan/winScanPackJob.vue"
	import comReceiptJobCard from '@/pages/purchaseReceipt/coms/comReceiptJobCard.vue'
	import receiptJobListPopup from '@/pages/purchaseReceipt/coms/receiptJobListPopup.vue'
	import receiptInfoPopup from '@/pages/purchaseReceipt/coms/receiptInfoPopup.vue'
	import comBlankView from '@/mycomponents/common/comBlankView.vue'

	export default {
		name: 'purchaseReceiptAsn',
		components: {
			winScanButton,
			winScanPackJob,
			comReceiptJobCard,
			receiptJobListPopup,
			receiptInfoPopup,
			comBlankView
		},
		data() {
			return {
				title: '',
				scanHintTitle: "箱标签/ASN单号",
				jobList: [],
				detailOptions: [],
				detailRemoveOption: [],
			};
		},
		onShow() {},
		onLoad(option) {
			this.title = option.title
			uni.setNavigationBarTitle({
				title: this.title
			})
			this.detailOptions = getDetailOption();
			this.detailRemoveOption = getDetailRemoveOption();
		},
		onNavigationBarButtonTap(e) {
			if (e.index === 0) {
				this.$refs.receiptjob.goHome();
				// this.$refs.receiptjob.refresh();
			} else if (e.index == 1) {
				this.$refs.receiptjob.openFilter();
			}
		},
		onShow() {
			uni.$on('updateData', (data) => {
				this.jobList.forEach(item => {
					if (item.asnNumber == data.asnNumber && item.itemCode == data.itemCode && item.batch == data.batch) {
						if (data.handleQty) {
							item.scaned = true
						} else {
							item.scaned = false
						}
						item.packingNumber = data.packingNumber
						item.packQty = data.packQty
						item.packUnit = data.packUnit
						item.toLocationCode = data.toLocationCode
						item.labelQty = data.labelQty
						item.handleQty = data.handleQty
						item.convertRate = data.convertRate
						item.supplierQty = data.supplierQty
						item.supplierUom = data.supplierUom
						item.packageDOS = data.packList
					}
				})
			})
		},
		methods: {
			openScanPopup() {
				this.$refs.scanPopup.openScanPopup();
			},
			getScanResult(result) {
				uni.showLoading({
					title: "加载中....",
					mask: true
				});
				const asnNumber = result.label.asn || result.label.code
				const isAsn = result.label.code ? true : false
				
				try {
					if (!asnNumber) {
						this.showMessage("标签格式异常，请重新补打标签")
						uni.hideLoading();
						return;
					}
					this.scanMessage = ""
					let filters = []
					// ASN单号
					filters = [{
						column: "asn_number",
						action: "==",
						value: asnNumber
					}, {
						column: "status",
						action: "in",
						value: '1,2',
					}
					// , {
					// 	column: "accept_user_id",
					// 	action: "==",
					// 	value: this.$store.state.user.id
					// },
					]
					getPurchaseReceiptASNJobList({
						filters: filters,
						pageNo: 1,
						pageSize: 100,
					}).then(async res => {
						this.scanMessage = result.scanMessage
						let resultList = res.data.list;
						uni.hideLoading()
						if (resultList.length > 0) {
							// 判断目前是否有已扫描的asn单号
							const asnObj = this.jobList.find(item => item.asnNumber == asnNumber)
							if (resultList[0].acceptUserId && resultList[0].acceptUserId != this.$store.state.user.id) {
								this.showMessage(`ASN单号【${asnNumber}】已经被${resultList[0].acceptUserName}承接`)
								return
							}
							// 如果扫描箱标签
							if (!isAsn) {
								result.label.lookNumber = result.package.number.substring(result.package.number
									.length - 5);
							
								// 扫描的箱标签asn单号不在列表中给个提示
								if (!asnObj) {
									this.$refs.comMessage.showQuestionMessage(`ASN单号【${asnNumber}】不在列表中，是否要按此ASN收货？`, async res => {
										if (res) {
											// 承接任务 // 如果任务状态是待处理的情况需要承接
											if (resultList[0].status == '1') {
												await this.handleTakePurchaseReceiptJob(resultList[0].masterId, () => {
													resultList.forEach(item => {
														item.status = '2'
														item.acceptUserId = 4
													})
												})
											} else if (resultList[0].status == '2') {
												// 如果任务状态是进行中的时候需要判断承接人和登录人是否一致
												if (resultList[0].acceptUserId != this.$store.state.user.id) {
													this.showMessage(`ASN单号【${asnNumber}】已经被${resultList[0].acceptUserName}承接`)
													return
												}
											}
											this.jobList = [...this.jobList, ...resultList]
											const itemObj = this.jobList.find(item => item.asnNumber == asnNumber && item
												.itemCode == result.label.itemCode)
											const packObj = itemObj.packageDOS.find(cur => cur.number == result.label
												.packingNumber)
											if (packObj.requestNumber) {
												this.showMessage(`看板编号【${ result.label.lookNumber}】已经收货`)
												return
											}
											if (packObj.scaned) {
												this.showMessage(`看板编号【${ result.label.lookNumber}】已经扫描`)
												return
											}
											itemObj.scaned = true
											packObj.scaned = true
											packObj.handleQty = result.label.qty
											packObj.packingNumber = result.package.number
											packObj.packQty = Number(result.package.packQty);
											packObj.packUnit = result.package.packUnit
											packObj.labelQty = Number(result.label.qty);
											packObj.convertRate = result.label.convertRate
											packObj.supplierQty = parseFloat(calc.div(parseFloat(packObj.handleQty), parseFloat(packObj.convertRate)).toFixed(5))
											packObj.supplierUom = result.label.purchaseUom
											this.calcHandleQty(this.jobList);
										this.scanPopupGetFocus()
										}else{
											this.scanPopupGetFocus()
										}
									});
								} else {
									// 扫描的箱标签asn单号已经在列表中
									const itemObj = this.jobList.find(item => item.asnNumber == asnNumber && item.itemCode == result
										.label.itemCode)
									if (!itemObj) {
										this.showMessage(`ASN单号【${asnNumber}】物料代码【${result.label.itemCode}】不在列表中 `)
										return
									}
									const packObj = itemObj.packageDOS.find(cur => cur.number == result.label.packingNumber)
									if (!packObj) {
										this.showMessage(
											`ASN单号【${asnNumber}】物料代码【${result.label.itemCode}】不存在看板编号【${ result.label.lookNumber}】`)
										return
									}
									if (packObj.requestNumber) {
										this.showMessage(`看板编号【${ result.label.lookNumber}】已经收货`)
										return
									}
									if (packObj.scaned) {
										this.showMessage(`看板编号【${ result.label.lookNumber}】已扫描`)
										return
									}
									itemObj.scaned = true
									packObj.scaned = true
									packObj.handleQty = result.label.qty
									this.calcHandleQty(this.jobList);
										this.scanPopupGetFocus()
								}

							} else {
								// if (asnObj) {
								// 	this.showMessage("此ASN关联的采购收货任务已扫描")
								// 	return;
								// }
								// 承接任务 // 如果任务状态是待处理的情况需要承接
								if (resultList[0].status == '1') {
									await this.handleTakePurchaseReceiptJob(resultList[0].masterId, () => {
										resultList.forEach(item => {
											item.status = '2'
											item.acceptUserId = this.$store.state.user.id
										})
									})
								} else if (resultList[0].status == '2') {
									// 如果任务状态是进行中的时候需要判断承接人和登录人是否一致
									if (resultList[0].acceptUserId != this.$store.state.user.id) {
										this.showMessage(`ASN单号【${asnNumber}】已经被${resultList[0].acceptUserName}承接`)
										return
									}
								}
								this.jobList = [...this.jobList, ...resultList]
										this.scanPopupGetFocus()
							}
						} else {
							this.showMessage("未查询到此ASN关联的采购收货任务")
						}
					}).catch(error => {
						this.showMessage(error + "\n扫描[" + result.scanMessage + "]")
						
							this.scanPopupGetFocus()
					})
				} catch (e) {
					this.showMessage(e.message)
											this.scanPopupGetFocus()
				}
			},
			calcHandleQty(detailSource) {
				for (let item of detailSource) {
					item.handleQty = new Decimal(0).toNumber();
					// item.qty = new Decimal(0).toNumber();
					for (let detail of item.packageDOS) {
						if (detail != undefined) {
							if (detail.scaned) {
								item.handleQty = calc.add(item.handleQty, detail.handleQty);
							}
							// item.qty = calc.add(item.qty, detail.qty);
						}
					}
				}
			},
			async handleTakePurchaseReceiptJob(id, callback) {
				await takePurchaseReceiptJob(id).then(res => {
					uni.hideLoading();
					callback()
				}).catch(error => {
					uni.hideLoading();
					this.showErrorMessage(error)
				})
			},
			showMessage(message) {
				if (this.$refs.scanPopup) {
					this.$refs.scanPopup.packLoseFocus()
				}
				this.$refs.comMessage.showErrorMessage(message, res => {
					if (res) {
						if (this.$refs.scanPopup) {
							this.$refs.scanPopup.packGetFocus()
						}
					}
				});
			},

			swipeClick(e, dataContent) {
				if (e.content.text == "详情") {
					this.openjobInfoPopup(dataContent);
				} else if (e.content.text == "移除") {
					this.$refs.comMessage.showQuestionMessage("是否要移除当前收货明细?",
						res => {
							if (res) {
								this.jobList = this.jobList.filter(item => item.asnNumber != dataContent.asnNumber || item.itemCode !=
									dataContent.itemCode)
								const isHave = this.jobList.some(item => item.asnNumber == dataContent.asnNumber)
								if (!isHave) {
									//取消承接任务
									cancleTakePurchaseReceiptJob(dataContent.masterId).then(res => {

									}).catch(error => {})
								}
							}
						});
				}
			},
			openjobInfoPopup(item) {
				this.$refs.jobInfoPopup.openPopup(item)
			},
			showErrorMessage(message) {
				if (this.$refs.scanPopup) {
					this.$refs.scanPopup.losefocus();
				}
				setTimeout(r => {
					this.$refs.comMessage.showErrorMessage(message, res => {
						if (res) {
							this.scanPopupGetFocus()
						}
					});
				})
			},
			openJobDetail(item) {
				uni.navigateTo({
					url: './purchaseReceiptAsnDetail?data=' + encodeURIComponent(JSON.stringify(item))
				});
			},
			clearAll() {
				this.$refs.comMessage.showQuestionMessage("是否确认要清空ASN收货列表?",
					async res => {
						if (res) {
							let masterIds = Array.from(new Set(this.jobList.map(item => item.masterId)))
							let index = 0
							//取消承接任务
							await this.handleCancleTakePurchaseReceiptJob(index, masterIds,'clearBtn')
						}
					});
			},
			async handleCancleTakePurchaseReceiptJob(index,masterIds ,from) {
				console.log(33,from)
				if (index <= masterIds.length - 1) {
					await cancleTakePurchaseReceiptJob(masterIds[index]).then(res => {
						this.jobList = []
						index++
						this.handleCancleTakePurchaseReceiptJob(index, masterIds,from)
					}).catch(error => {})
				} else {
					console.log(from)
					if(!from){
						uni.navigateBack({
							delta: 1
						});
					}
				
				}
			},
			commit(){
				let str =''
				let str1 =''
				this.params = []
				let obj = {}
				let obj1 = {}
				this.jobList.forEach(item=>{
					if(item.scaned){
						obj = {...item}
						obj.id = item.masterId
						if(this.params.some(i => i.asnNumber  == item.asnNumber)){
							item.packageDOS.forEach(cur=>{
								if(cur.scaned){
									obj1 = {
										...cur,
										...item,
										packingNumber:cur.number,
										number:'',
										deliNo:item.deliNo,
										itemCode:item.itemCode,
										itemDesc:item.itemDesc,
										itemDesc1:item.itemDesc1,
										itemDesc2:item.itemDesc2,
										itemName:item.itemName,
										backNumber:item.backNumber,
										packQty:cur.packQty,
										packUnit:cur.packUnit,
										purchaseQty:cur.purchaseQty,
										purchaseStdQty:cur.purchaseStdQty,
										purchaseUom:cur.purchaseUom,
										qty:item.qty,
										remark:cur.remark,
										supplierBatch:cur.supplierBatch,
										supplierCode:cur.supplierCode,
										toLocationCode:item.toLocationCode,
										uom:item.uom,
										handleQty:cur.handleQty,
										qty:item.qty,
									}
									obj.subList.push(obj1)
								}
							})
						}else{
							obj.subList=[]
							item.packageDOS.forEach(cur=>{
								if(cur.scaned){
									obj1 = {
										...cur,
										...item,
										packingNumber:cur.number,
										number:'',
										deliNo:item.deliNo,
										itemCode:item.itemCode,
										itemDesc:item.itemDesc,
										itemDesc1:item.itemDesc1,
										itemDesc2:item.itemDesc2,
										itemName:item.itemName,
										backNumber:item.backNumber,
										packQty:cur.packQty,
										packUnit:cur.packUnit,
										purchaseQty:cur.purchaseQty,
										purchaseStdQty:cur.purchaseStdQty,
										purchaseUom:cur.purchaseUom,
										qty:item.qty,
										remark:cur.remark,
										supplierBatch:cur.supplierBatch,
										supplierCode:cur.supplierCode,
										toLocationCode:item.toLocationCode,
										uom:item.uom,
										handleQty:cur.handleQty,
										qty:item.qty,
									}
									obj.subList.push(obj1)
								}
							})
							this.params.push(obj)
						}
					}
					if(item.handleQty>0 && item.handleQty < item.qty){
						str += `ASN单号【${item.asnNumber}】物料代码【${item.itemCode}】实际收货数量【${item.handleQty}】小于任务数量【${item.qty}】，\n`	
					}
					if(!item.handleQty){
						str1 += `ASN单号【${item.asnNumber}】物料代码【${item.itemCode}】实际收货数量为0，\n`	
					}
				})
				this.params.forEach(item=>{
					delete item.packageDOS
					item.subList.forEach(cur=>{
						delete cur.packageDOS,
						delete item.masterId
					})
				})
				//提交
				if(str || str1){
					if(str){
						str = str + '对于未收货部分将创建一个新的收货任务。\n'
					}
					if(str1){
						str1 = str1 +'是否确认提交？'
					}
					this.$refs.comMessage.showQuestionMessage1(str + str1, 'red', res => {
						if (res) {
							this.submitJob()
						}
					});
				}else{
						this.submitJob()
				}
			},
			submitJob(){
				uni.showLoading({
					title: "加载中....",
					mask: true
				});
				purchaseReceiptJobSubmitASN(this.params).then(res => {
					if (res.data) {
						// this.showCommitSuccessMessage("提交成功\n生成采购上架记录\n" + res.data)
						let str =''
						let str1 =''
						res.data.forEach(item=>{
							if(item.isSuccess === 0 || item.isSuccess === '0'){
								str+= `ASN单号【${item.asnNumber}】提交成功，生成采购收货记录，${item.recordNumber}\n`	
							}else{
								str1+= `ASN单号【${item.asnNumber}】提交失败，失败原因：${item.message}\n`
							}
						})
						uni.hideLoading()
						if(str){
							this.showCommitSuccessMessage(str+str1)
						}else{
							this.$refs.comMessage.showErrorMessage(str1);
						}
						
					} else {
						// this.showErrorMessage("提交失败[" + res.msg + "]")
						this.$refs.comMessage.showErrorMessage("提交失败[" + res.msg + "]");
					}
				}).catch(error => {
					uni.hideLoading()
					this.$refs.comMessage.showErrorMessage(error);
				})
			},
			showCommitSuccessMessage(hint) {
				this.$refs.comMessage.showSuccessMessage(hint, res => {
					uni.navigateBack({
						delta:1
					})
				})
			},
			scanPopupGetFocus() {
				if (this.$refs.scanPopup != undefined) {
					this.$refs.scanPopup.packGetFocus();
				}
			},
		},
		onBackPress(options) {
			if (options.from === 'navigateBack') {
				return false;
			}
			if (this.jobList.length > 0) {
				this.$refs.comMessage.showQuestionMessage("是否要放弃当前的扫描信息?",
					async res => {
						if (res) {
							let masterIds = Array.from(new Set(this.jobList.map(item => item.masterId)))
							let index = 0
							//取消承接任务
							await this.handleCancleTakePurchaseReceiptJob(index, masterIds)
						}
					});
				return true
			}

		},
	}
</script>

<style scoped lang="scss">
	.page-footer {
		display: flex;
		justify-content: flex-end;
		background: white;
		padding: 10rpx 20rpx;
		position: fixed;
		width: 100%;
		bottom: 0px;
	}

	.btn_single_commit,
	.btn_single_clear {
		margin: 0px;
	}

	.btn_single_clear {
		margin-right: 20rpx;
	}
</style>