<template>
	<view>
		<uni-popup ref="popup" :maskClick='false'>
			<view class="">
				<view class="popup_box">
					<view class="pop_title">
						扫描箱码
						<text class="fr" @click="closeScanPopup()">关闭</text>
					</view>

					<!-- 	<view class="uni-flex uni-row" style="align-items: center;
						background-color: #fff; 
						margin-left: 20rpx;
						margin-right: 20rpx;
						margin-top: 8rpx;
						border-radius: 8rpx;">
						<view class="uni-center" style="width: 25%; ">
							来源库位
						</view>
						<view class="" style="width: 75%; padding: 8rpx;">
							<uni-combox :candidates="fromLocationList" v-model="fromLocationCode" placeholder="请选择库位"
								@confirm="fromLocationUpdate"></uni-combox>
						</view>
					</view> -->

					<view class="">
						<view class="">
							<win-com-scan ref="comscan" placeholder="箱标签" @getResult="onScan" :clearResult="true"
								headerType="HPQ,HMQ" :isShowHistory="false">
							</win-com-scan>

							<view style="width: 100%;">
								<view style="width: 100%;" v-if="issueRecord.length>0">
									<view class="uni-flex uni-row space-between u-col-center">
										<view class="" style="padding: 10rpx;">
											历史记录
										</view>
										<view class="" style="padding-right: 10rpx;">
											<u-icon :name="expendIcon" size="35rpx" @click="expands()"></u-icon>
										</view>
									</view>
									<u-line class='line_color' style='padding-top: 10rpx;padding-bottom: 20rpx;'>
									</u-line>
									<scroll-view scroll-y="true" class="scroll-view"
										v-if="expand&&issueRecord.length>0">
										<view class="uni-flex u-col" v-for="(record,index) in issueRecord">
											<view style="width: 100%;">
												<uni-swipe-action ref="swipeAction">
													<uni-swipe-action-item @click="swipeClick($event,record,index)"
														:right-options="scanOptions">
														<view style="padding: 0px 10px">
															<balance :dataContent="record" :isShowFromLocation="false"
																:isShowStatus='true' :isShowStdPack="false"></balance>
														</view>
													</uni-swipe-action-item>
												</uni-swipe-action>
												<u-line class='line_color'></u-line>
											</view>
										</view>
									</scroll-view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</uni-popup>
		<balance-select ref="balanceSelect" @onSelectItem='selectBalanceItem'></balance-select>
		<comMessage ref="comMessage"></comMessage>
		<balance-qty-edit ref="balanceQtyEdit" @confirm="confirm" :isShowStatus="true"></balance-qty-edit>
	</view>
</template>

<script>
	import winComScan from '@/mycomponents/scan/winComScan.vue'
	import balance from '@/mycomponents/balance/balance.vue'
	import balanceQtyEdit from '@/mycomponents/qty/balanceQtyEdit.vue'
	import balanceSelect from '@/mycomponents/balance/balanceSelect.vue'

	import {
		getDetailOption,
		getDetailEditRemoveOption
	} from '@/common/array.js';
	import {
		getWorkShopLineStation,
		getBalanceByFilter,
		getBalanceByParams,
	} from '@/api/request2.js';

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

	import {
		uniqueArray
	} from '@/common/basic.js';

	import {
		getBalanceByManagementPrecision
	} from '@/common/balance.js';
	import {
		getDirectoryItemArray
	} from '../../../common/directory.js';


	import {
		getLabelInfo
	} from '@/common/label.js';

	export default {
		name: 'winScanPack',
		components: {
			winComScan,
			balance,
			balanceQtyEdit,
			balanceSelect
		},
		props: {
			title: {
				type: String,
				default: ''
			},

		},
		data() {
			return {
				dataContent: {},
				jobContent: {},
				expendIcon: 'arrow-down',
				show: false,
				scanList: [],
				toLocation: null,
				toLocationCode: '',
				fromLocationList: [],
				fromLocationCode: '',
				fromLocation: null,
				issueRecord: [], //发料历史
				expand: true,
				scanOptions: {},
				editItem: {},
				positionList: [],
				defaultValueList: [],
				label: {},
				fromInventoryStatuses: "",
				packageInfo: {},
				toLocationAreaTypeList: []

			}
		},
		created() {

		},
		watch: {},
		mounted() {
			this.detailOptions = getDetailOption();
			this.scanOptions = getDetailEditRemoveOption();
		},
		methods: {
			openScanPopup(content, jobcontent) {
				this.issueRecord = [];
				this.dataContent = content;
				this.jobContent = jobcontent;
				this.initData();
				this.$refs.popup.open('bottom')
				setTimeout(res => {
					this.getfocus();
				}, 500)
			},

			openScanPopupForJobSimulate(content, jobcontent, scanMessage) {
				this.issueRecord = [];
				this.dataContent = content;
				this.jobContent = jobcontent;
				this.initData();
				getLabelInfo(scanMessage, this.headerType, callback => {
					if (callback.success) {
						this.onScan(callback);
					} else {
						this.showErrorMessage(callback.message)
					}

				})
			},

			closeScanPopup() {
				this.losefocus()
				this.$refs.popup.close();
				this.$emit("closeScan")
				//清除数据,恢复默认值
				// Object.assign(this.$data, this.$options.data());
			},

			initData() {
				let that = this;
				that.fromLocationList = [];
				if (that.dataContent != null) {
					that.fromInventoryStatuses = this.jobContent.outInventoryStatuses
					that.toLocation =that.dataContent.subList;
					that.toLocationCode = that.dataContent.subList[0].toLocationCode;
					that.toLocationAreaTypeList = getDirectoryItemArray(this.jobContent.toAreaTypes)
					// that.fromLocationList = that.getFromLocationList();
				}
			},

			showBalanceSelect(items) {
				this.$refs.balanceSelect.openPopup(items);
			},

			// getFromLocationList() {
			// 	let list = [];
			// 	let location = this.dataContent.find(r => r.toLocationCode == this.toLocationCode);
			// 	if (location != undefined) {
			// 		location.Items.forEach(item => {
			// 			item.Locations.forEach(f => {
			// 				list.push(f.fromLocationCode)
			// 			})
			// 		})
			// 		//去掉重复库位
			// 		list = uniqueArray(list);
			// 		this.fromLocationCode = list[0];

			// 		return list;
			// 	} else {
			// 		this.$refs.comMessage.showErrorMessages('需求库位【' + this.toLocationCode + '】不存在', res => {
			// 			this.toLocationCode = '';
			// 		});
			// 	}
			// },

			fromLocationUpdate(fromlocation) {
				let location = this.fromLocationList.find(r => r == fromlocation)
				if (location == undefined) {
					this.fromLocationCode = ''
					this.showErrorMessage('发料库位【' + fromlocation + '】不存在', res => {
						this.getfocus();
					})
				}
			},

			onScan(result) {
				console.log(11,result)
				if (!result.package) {
					this.showErrorMessage('扫描数据错误[' + result.label.code + "]",
						res => {
							this.getfocus();
						}
					)
					return;
				}
				if (this.toLocation && result.package.packUnit) {
					let item = this.toLocation.find(r => r.itemCode == result.package.itemCode);
					if (!item) {
						this.showErrorMessage('扫描物料代码不属于该任务',
							res => {
								this.getfocus();
							});
						return
					}
					if (result.package.packUnit !== item.packUnit) {
						// this.$refs.comMessage.showQuestionMessage(
						// 	`扫描物料包装【${result.package.packUnit}】与任务推荐包装规格【${item.packUnit}】不一致.是否要继续发料?`, res => {
						// 		if (res) {
						// 			this.getToLocationBalance(result)
						// 		}
						// 	});
						this.getToLocationBalance(result)
					} else {
						this.getToLocationBalance(result)
					}
				}else{
					this.getToLocationBalance(result)
				}
			},

			//查询到目标库位的库存余额
			getToLocationBalance(result) {
				uni.showLoading({
					title: '查询中',
					mask: true
				})
				var filters = []
				if (result.package.parentNumber) {
					var packingNumber = result.package.parentNumber + "," + result.package.number;
					filters.push({
						column: "packingNumber",
						action: "in",
						value: packingNumber
					})
				} else {
					filters.push({
						column: "packingNumber",
						action: "==",
						value: result.package.number
					})
				}

				filters.push({
					column: "itemCode",
					action: "==",
					value: result.package.itemCode
				})
				filters.push({
					column: "batch",
					action: "==",
					value: result.package.batch
				})

				filters.push({
					column: "areaType",
					action: "in",
					value: this.toLocationAreaTypeList.join(',')
				})


				var params = {
					filters: filters,
					pageNo: 1,
					pageSize: 100,
				}
				getBalanceByFilter(params).then(res => {
					uni.hideLoading()
						this.queryBalance(result);
					// if (res.data.list.length > 0) {
					// 	this.showErrorMessage("包装在库位【" + res.data.list[0].locationCode + "】已有库存余额",
					// 		res => {
					// 			this.getfocus();
					// 		});
						
					// } else {
					// 	this.queryBalance(result);
					// }
					// callback(res.data)
				}).catch(err => {
					uni.hideLoading()
					this.showErrorMessage(err.message,
						res => {
							this.getfocus();
						});
				})
			},

			queryBalance(result) {
				try {
					let that = this;
					// if (that.fromLocationCode == '') {
					// 	that.showErrorMessage('请选择来源库位', res => {
					// 		that.$refs.toLocationCombox.onFocus();
					// 	});
					// 	return;
					// }
					let packageInfo = result.package;
					let itemCode = result.label.itemCode;
					let packingCode = result.label.packingNumber;
					let lot = result.label.batch;
					let item = that.toLocation.find(r => r.itemCode == itemCode);
					if (item == undefined) {
						that.showErrorMessage('未查找到物料【' + itemCode + '】的发料明细',
							res => {
								that.getfocus();
							}
						)
						return;
					} else {

					item.scaned = true
						var params = {
							itemCode: result.package.itemCode,
							batch: result.label.batch,
							packingNumber: result.label.packingNumber,
							parentPackingNumber: result.package.parentNumber,
							inventoryStatus: this.jobContent.outInventoryStatuses.split(','),
							areaType: this.jobContent.fromAreaTypes.split(','),
							bussinessCode: this.jobContent.businessType
						}
						uni.showLoading({
							title: '查询中',
							mask: true
						})
						getBalanceByParams(params).then(res => {
							if (res.data.length == 0) {
								var status = getInventoryStatusDesc(params.inventoryStatus)
								var areaType = getListLocationAreaTypeDesc(params.areaType)
								var hint =
									"按物料号 [" + params.itemCode + "] \n" +
									"包装号 [" + params.packingNumber + "] \n" +
									"批次 [" + params.batch + "] \n" +
									"状态 [" + status + "] \n" +
									"库区 [" + areaType + "] \n" +
									"未查找到库存余额"
								this.showErrorMessage(hint,
									res => {
										this.getfocus();
									})
							} else if (res.data.length == 1) {
								result.balance = res.data[0]
								if (result.label.packingNumber != result.balance.packingNumber) {
									result.balance.qty = Number(result.label.qty)
								} else {
									result.balance.qty = Number(result.balance.qty)
								}
								this.afterGetBalance(result.label, result.balance, result.package);
							} else {
								//多条记录
								this.$refs.balanceSelect.openPopup(res.data);
							}
							uni.hideLoading()
						}).catch(error => {
							uni.hideLoading()
							this.showErrorMessage(error,
								res => {
									this.getfocus();
								})
						})
					}
				} catch (e) {
					uni.hideLoading();
					this.showErrorMessage(e.stack,
						res => {
							this.getfocus();
						})

				}
			},

			selectBalanceItem(balance) {
				this.afterGetBalance(balance, balance, this.packageInfo);
			},

			afterGetBalance(label, balance, packageInfo) {
				try {
					let that = this;
					let itemCode = label.itemCode;
					let packingCode = label.packingNumber;
					let lot = label.batch;
					let item = that.toLocation.find(r => r.itemCode == itemCode);
					item.scaned =true
					that.fromLocationCode = balance.locationCode;
					// let fromLocation = item.Locations.find(l => l.fromLocationCode == that.fromLocationCode);
					//如果库存余额中的库位与任务推荐的不一致
					if (item.fromLocation!=that.fromLocationCode) {
						// let batch = fromLocation.Batchs.find(r => r.batch == lot);
						if (item.batch != undefined) {
							// if (batch.Records == undefined) {
							// 	batch.Records = [];
							// }

							// let record = batch.Records.find(r => r.packingNumber == packingCode);
							that.addRecord(item.batch, label, balance, packageInfo)
						} else {
							if (this.jobContent.allowModifyBatch == "TRUE") {
								this.showQuestionMessage('在【' + that.fromLocationCode + '】库位下,批次【' + lot +
									'】不是推荐批次,是否要继续发料?', res => {
										if (res) {
											let batch = that.createBatchInfo(label, balance, packageInfo);
											if (fromLocation.Batchs.length > 0) {
												batch.detail = fromLocation.Batchs[0].detail;
											}
											fromLocation.Batchs.unshift(batch);
											this.getfocus();
										}
									})
							} else {
								that.showErrorMessage('未查找到批次【' + lot + '】的发料明细',
									res => {
										that.getfocus();
									});
							}
						}
					} else {
						if (this.jobContent.allowModifyLocation == "TRUE") {
							this.showQuestionMessage("扫描物料[" + itemCode + "]的库位【" + that.fromLocationCode +
								"】与推荐的库位不一致,是否要继续发料?", res => {
									if (res) {
										let locaion = that.createLocationInfo(label, balance, packageInfo);
										item.Locations.push(locaion);
										this.getfocus();
										that.$emit("afterScan");
									}
								})

						} else {
							this.showErrorMessage("扫描物料[" + itemCode + "]的库位【" + that.fromLocationCode +
								"】与推荐的库位不一致,不允许继续发料?")
						}


					}
				} catch (e) {
					this.showErrorMessage(e.stack,
						res => {
							this.getfocus();
						}
					)
				}
			},

			//增加实际扫描的明细
			createLocationInfo(label, balance, packageInfo) {
				let location = {
					fromLocationCode: balance.locationCode,
					qty: balance.qty,
					uom: balance.uom,
					handleQty: 0,
					isNewAdd: true,
					Batchs: []
				}
				let batch = this.createBatchInfo(label, balance, packageInfo);
				batch.detail = balance;
				batch.detail.fromLocationCode = balance.locationCode;
				location.Batchs.push(batch);
				return location;
			},

			createBatchInfo(label, balance, packageInfo) {
				let batch = {
					batch: label.batch,
					qty: 0,
					uom: label.uom,
					handleQty: Number(balance.qty),
					Records: []
				}
				let record = {}
				if (balance != null) {
					record = this.creatRecordByBalance(balance, packageInfo);
					batch.handleQty = Number(label.qty)
				} else {
					record = this.creatRecordByLabel(label, packageInfo);
					batch.handleQty = Number(balance.qty)
				}

				batch.Records.push(record);
				this.issueRecord.unshift(record)
				return batch;
			},

			creatRecordByLabel(label, packageInfo) {
				let record = {
					scaned: true,
					itemCode: label.itemCode,
					packingNumber: label.packingNumber,
					parentPackingNumber: packageInfo.parentNumber,
					batch: label.batch,
					qty: Number(label.qty),
					// qty: Number(label.qty)>Number(balance.qty)?Number(balance.qty):Number(label.qty),
					uom: label.uom,
					inventoryStatus: "OK",
					balance: null,
					toLocationCode: this.toLocationCode,
					supplierCode: label.supplierCode,
					packUnit: packageInfo.packUnit,
					packQty: packageInfo.packQty,
				}
				return record;
			},

			creatRecordByBalance(balance, packageInfo) {
				balance.packQty = packageInfo.packQty
				balance.packUnit = packageInfo.packUnit
				let record = {
					scaned: true,
					itemCode: balance.itemCode,
					packingNumber: packageInfo.number,
					parentPackingNumber: packageInfo.parentNumber,
					batch: packageInfo.batch,
					qty: Number(balance.qty),
					// qty: Number(label.qty)>Number(balance.qty)?Number(balance.qty):Number(label.qty),
					uom: balance.uom,
					inventoryStatus: balance.inventoryStatus,
					balance: balance,
					toLocationCode: this.toLocationCode,
					supplierCode: balance.supplierCode
				}
				return record;
			},

			calcBatchHandleQty(balance) {
			
				this.dataContent.subList.forEach(item => {
					if(item.itemCode == balance.itemCode){
						item.handleQty = balance.qty;
					}
				})
			},

			addRecord(batch, label, balance, packageInfo) {
				let record = {};
				if (balance == null) {
					record = this.creatRecordByLabel(label, packageInfo);
				} else {
					record = this.creatRecordByBalance(balance, packageInfo);
				}

				if (packageInfo.parentNumber) {
					// var checkData = batch.Records.find(r => {
					// 	if (r.packingNumber == packageInfo.parentNumber &&
					// 		r.batch == packageInfo.batch) {
					// 		return r;
					// 	}
					// })
					if (checkData) {
						//提示已经扫描
						this.showErrorMessage("箱码[" + packageInfo.number + "]批次[" + packageInfo.batch +
							"]的父包装已经扫描")
					} else {
						// batch.Records.push(record);
						// this.issueRecord.unshift(record)
						this.calcBatchHandleQty(balance);
						this.getfocus();
					}
				} else {
					//扫描的是父包装
					// var checkData = batch.Records.find(r => {
					// 	if (r.parentPackingNumber == packageInfo.number &&
					// 		r.batch == packageInfo.batch) {
					// 		return r;
					// 	}
					// })
					// if (checkData) {
					// 	//是否移除
					// 	this.$refs.comMessage.showQuestionMessage("扫描箱码[" + checkData.parentPackingNumber + "]" + "批次[" +
					// 		packageInfo
					// 		.batch + "]是父包装,是否移除子包装", res => {
					// 			if (res) {
					// 				batch.Records = []
					// 				batch.Records.push(record);
					// 				this.issueRecord.unshift(record)
					// 				this.calcBatchHandleQty(batch);
					// 				this.getfocus();
					// 			}
					// 		})
					// 	console.log("扫描的是父包装,是否移除子包装")
					// } else {
						// batch.Records.push(record);
						// this.issueRecord.unshift(record)
						this.calcBatchHandleQty(balance);
						this.getfocus();
					// }

				}
			},

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

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

			expands() {
				this.expand = !this.expand;
				this.expendIcon = this.expand == true ? "arrow-down" : "arrow-up"
			},

			swipeClick(e, item, index) {
				if (e.content.text == "详情") {
					this.detail(item)
				} else if (e.content.text == "编辑") {
					this.edit(item)
				} else if (e.content.text == "移除") {
					this.remove(item, index)
				}
			},
			edit(item) {
				this.editItem = item;
				// item.balance.balanceQty = item.balance.qty;
				item.balance.balanceQty = item.balance.qty;
				this.$refs.balanceQtyEdit.openEditPopup(item.balance, item.qty);
			},

			detail(item) {
				this.showItem = item;
				this.$refs.receiptHint.openScanPopup()
			},
			remove(item, index) {
				this.showQuestionMessage("确定移除扫描信息?",
					res => {
						if (res) {
							item.handleQty = 0;
							item.scaned = false ;
							this.$emit('updateData', record);
						}
					});
			},

			packGetFocus() {
				if (this.$refs.comscan) {
					this.$refs.comscan.getfocus();
				}

			},
			packLoseFocus() {
				if (this.$refs.comscan) {
					this.$refs.comscan.losefocus();
				}

			},
			showMessage(message, callback) {
				setTimeout(r => {
					this.packLoseFocus();
					this.$refs.comMessage.showMessage(message, callback);
				})
			},
			showErrorMessage(message, callback) {
				setTimeout(r => {
					this.packLoseFocus();
					this.$refs.comMessage.showErrorMessage(message, callback);

				})
			},
			showQuestionMessage(message, callback) {
				setTimeout(r => {
					this.packLoseFocus();
					this.$refs.comMessage.showQuestionMessage(message, callback);
				})
			},
			confirm(val) {
				this.editItem.qty = Number(val);
				this.$emit('updateData', this.editItem)
			},
			cancle() {
				this.closeScanPopup()
			}
		}
	}
</script>

<style lang="scss">
	button {
		border: none;
	}

	button::after {
		border: none
	}

	.scroll-view {
		overflow-y: scroll;
		height: auto;
		max-height: 300rpx;
		padding: 10rpx;
	}
</style>