<template>
	<view class="page-wraper">
		<view class="">
			<com-blank-view @goScan='getBusinessType' v-if="recommendList.length==0"></com-blank-view>
		</view>
		<view class="page-wraper" v-if="recommendList.length>0">
			<view class="page-header">
				<view class="header_item" style="font-size:35rpx; padding: 10rpx;">
					<uni-collapse ref="collapse">
						<uni-collapse-item :open="true">
							<template v-slot:title>
								<view class="card_itemName" style="padding: 3px 5px; font-size: 28rpx;">
									先进先出推荐信息
								</view>
							</template>
							<view class="detail-list" v-for="(recommend, index) in recommendList" :key="recommend.id">
								<view class="card_view">
									<text class="card_item_code ">物料代码</text>
									<text class="card_content ">{{recommend.itemCode}}</text>
								</view>
								<balance :dataContent='recommend' :isShowStatus='false'></balance>
							</view>
						</uni-collapse-item>
					</uni-collapse>
				</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="">
							<record-com-detail-card :dataContent="item" :index="index" :settingParam="dataContent"
								:isShowFromLocation="true" @removeItem="removeItem(index,item)"
								:isShowToLocation="false" @updateData="updateData" @removePack="removePack">
							</record-com-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="">
						<requiredLocation v-if="showToLoaction" title="目标库位" :locationCode="toLocationCode"
							@getLocation='getToLocationCode' :locationAreaTypeList="toLocationAreaTypeList">
						</requiredLocation>
					</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>
		</view>
		<winComScanBalance ref="scanPopup" @getBalance='getScanResult' :bussinessCode="businessTypeCode">
		</winComScanBalance>
		<comMessage ref="comMessage"></comMessage>
	</view>
</template>

<script>
	import {
		repleinshRecordSubmit,
		validateItemAndLocation,
		getBalanceByFilter,
		getBalanceByBatchOffShelf
	} from '@/api/request2.js';

	import {
		goHome,
		updateTitle,
		getCurrDateTime,
		getPackingNumberAndBatchByList,
		deepCopyData
	} from '@/common/basic.js';

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

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

	import {
		getBusinessType,
		createItemInfo,
		createDetailInfo,
		calcHandleQty
	} from '@/common/record.js';

	import {
		getManagementPrecisions,
		getPrecisionStrategyList,
		getPrecisionStrategyParams
	} from '@/common/balance.js';

	import winScanButton from '@/mycomponents/scan/winScanButton.vue'
	import winScanPack from '@/mycomponents/scan/winScanPack.vue'
	import requiredLocation from '@/mycomponents/location/requiredLocation.vue'
	import comBlankView from '@/mycomponents/common/comBlankView.vue'
	import winScanLocation from "@/mycomponents/scan/winScanLocation.vue"
	import winScanPackAndLocation from "@/mycomponents/scan/winScanPackAndLocation.vue"
	import recordComDetailCard from '@/mycomponents/record/recordComDetailCard.vue'
	import winComScanBalance from '@/mycomponents/scan/winComScanBalance.vue'
	import balance from '@/mycomponents/balance/balance.vue'

	export default {
		components: {
			winScanButton,
			winScanPack,
			requiredLocation,
			comBlankView,
			winScanLocation,
			winScanPackAndLocation,
			recordComDetailCard,
			winComScanBalance,
			balance
		},
		data() {
			return {
				id: '',
				dataContent: {}, //内容
				detailSource: [], //绑定在页面上的数据源
				fromLocationCode: "",
				fromLocationAreaTypeList: [],
				toLocationAreaTypeList: [],
				inInventoryStatus: "", //目标入库库存状态
				outInventoryStatus: "", //来源出库库存状态
				businessType: {},
				showToLoaction: true,
				recommendLocationList: [], //推荐库位列表
				fromWarehouseCode: '', //来源仓库
				businessTypeCode: "Repleinment",
				toLocationCode: "",
				resultData: {},
				itemCode: "",
				recommendList: []
			};
		},
		onLoad(option) {
			uni.setNavigationBarTitle({
				title: option.title
			})
			this.clear();
			this.getBusinessType()
		},
		//返回首页
		onNavigationBarButtonTap(e) {
			if (e.index === 0) {
				goHome();
			}
		},
		//拦截返回按钮事件
		onBackPress(e) {},

		onPullDownRefresh() {},

		mounted() {},

		methods: {
			getBusinessType() {
				getBusinessType(this.businessTypeCode, res => {
					if (res.success) {
						this.businessType = res.businessType;
						this.fromInventoryStatuses = getDirectoryItemArray(res.fromInventoryStatuses);
						this.fromLocationAreaTypeList = res.fromLocationAreaTypeList
						this.openScanPopup();
					} else {
						this.showErrorMessage(res.message)
					}
				});
			},
			getBalance(label, packageInfo, callback) {
				var filters = []

				if (packageInfo.parentNumber) {
					var packingNumber = packageInfo.parentNumber + "," + label.packingNumber;
					filters.push({
						column: "packingNumber",
						action: "in",
						value: packingNumber
					})
				} else {
					filters.push({
						column: "packingNumber",
						action: "==",
						value: label.packingNumber
					})
				}

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

				if (this.fromInventoryStatuses != null && this.fromInventoryStatuses != "") {
					filters.push({
						column: "inventoryStatus",
						action: "in",
						value: this.fromInventoryStatuses
					})
				}

				var params = {
					filters: filters,
					pageNo: 1,
					pageSize: 100,
				}
				getBalanceByFilter(params).then(res => {
					callback(res.data)
				}).catch(err => {
					this.showErrorMessage(err.message);
				})
			},

			getScanResult(result) {
				let that = this;
				let pack = result.package;
				if (that.recommendList.length > 0) {
					let recommend = that.recommendList.filter(r => r.itemCode == pack.itemCode);
					if (recommend.length == 0) {
						this.showErrorMessage('物料代码【' + pack.itemCode + '】不在推荐列表中');
					} else {
						let batch = recommend.find(r => r.batch == pack.batch);
						if (batch == undefined) {
							that.showErrorMessage('扫描的批次【' + pack.batch + '】,不是系统推荐的批次,不满足系统的先进先出规则,请重新扫描物料');
						} else {
							this.setData(result);
						}
					}
				} else {
					this.getRecommendInfo(result);
				}
			},

			getRecommendInfo(result) {
				let that = this;
				uni.showLoading({
					title: '加载中...',
					mask: true
				})
				let item = {
					itemCode: result.package.itemCode,
					qty: result.package.qty,
				}
				getBalanceByBatchOffShelf(item.itemCode, item.qty, "Repleinment").then(res => {
					if (res.data == null) {
						that.showErrorMessage('未获取到推荐信息');
					} else {
						if (res.data.length > 0) {
							that.recommendList = res.data;
							that.recommendList.forEach(r => r.locationCode = r.fromLocationCode)
							let recommendInfo = res.data[0];
							if (recommendInfo.batch != result.package.batch) {
								that.showErrorMessage('扫描的批次【' + result.package.batch + '】,不是系统推荐的批次【' +
									recommendInfo.batch + '】,不满足系统的先进先出规则,请重新扫描');
							} else {
								this.setData(result);
							}
						} else {
							that.showErrorMessage('未查找到物料的推荐信息');
						}
						uni.hideLoading();
					}
				}).catch(error => {
					uni.hideLoading()
					that.showErrorMessage(error)
				})
			},

			setData(result) {
				let balance = result.balance;
				let label = result.label;
				let pack = result.package;
				if (this.fromLocationCode && this.fromLocationCode != balance.locationCode) {
					this.showErrorMessage("箱码[" + balance.packingNumber + "批次[" + balance.batch + "]在库位[" + this
						.fromLocationCode + "]没有库存余额")
					return;
				}

				var item = this.detailSource.find(res => {
					if (res.itemCode == balance.itemCode) {
						return res
					}
				})
				if (item == undefined) {
					if (this.itemCode != "" && this.itemCode != balance.itemCode) {
						this.showErrorMessage("请扫描物料为【" + this.itemCode + "】的箱码")
						return;
					}
					if (this.fromWarehouseCode == '') {
						this.fromWarehouseCode = balance.warehouseCode;
					}
					var itemp = createItemInfo(balance, pack);
					let newDetail = createDetailInfo(balance, pack); //
					newDetail.parentNumber = pack.parentNumber;
					newDetail.packingNumber = pack.number
					newDetail.packUnit = pack.packUnit;
					newDetail.packQty = pack.packQty;
					if (balance.lableQty) {
						newDetail.handleQty = balance.lableQty
					}
					itemp.subList.push(newDetail);
					this.detailSource.push(itemp)
					this.itemCode = balance.itemCode;
					this.fromLocationCode = balance.locationCode
					this.scanPopupGetFocus()
				} else {
					var detail = item.subList.find(r => {
						if (r.packingNumber == pack.number &&
							r.batch == balance.batch &&
							r.locationCode == balance.locationCode &&
							r.inventoryStatus == balance.inventoryStatus) {
							return r;
						}
					})
					if (detail == undefined) {
						let newDetail = createDetailInfo(balance, pack);
						newDetail.parentNumber = pack.parentNumber;
						newDetail.packingNumber = pack.number
						newDetail.packUnit = pack.packUnit;
						newDetail.packQty = pack.packQty;
						if (balance.lableQty) {
							newDetail.handleQty = balance.lableQty
						}
						item.subList.push(newDetail);
						this.scanPopupGetFocus()
					} else {
						if (detail.scaned == true) {
							this.showErrorMessage("箱码[" + detail.packingNumber + "批次[" + balance.batch + "]已经在列表中")
						}
					}
				}
				calcHandleQty(this.detailSource);
			},



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


			updateData() {
				calcHandleQty(this.detailSource);
				for (var i = 0; i < this.detailSource.length; i++) {
					let item = this.detailSource[i];
					if (item.qty == 0) {
						this.detailSource.splice(i, 1)
					}
				}
				this.$forceUpdate();

			},

			removeItem(index, item) {
				this.detailSource.splice(index, 1)
				this.updateData();
			},

			removePack() {
				for (var i = 0; i < this.detailSource.length; i++) {
					var item = this.detailSource[i];
					if (item.subList.length == 0) {
						this.detailSource.splice(i, 1)
					}
				}
				this.updateData();
			},

			openScanPopup() {
				if (this.businessType) {
					this.$refs.scanPopup.openScanPopup(this.businessType);
				} else {
					this.getBusinessType()
				}
			},


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

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

			scanLocationCode(location, code) {
				this.toLocationCode = code
			},

			commit() {
				if (this.toLocationCode == "") {
					this.showMessage("请输入目标库位")
					return;
				}


				if (this.detailSource.length == 0) {
					this.showMessage("请扫描要发货的物料")
					return;
				}


				this.detailSource.forEach(item => {
					item.subList.forEach(detail => {
						detail.toLocationCode = this.toLocationCode
						detail.fromLocation = this.fromLocationCode
					})
				})

				uni.showLoading({
					title: "提交中....",
					mask: true
				});

				//记录有目标库位，需要查询管理模式
				let precisionStrategyParams = getPrecisionStrategyParams(this.detailSource);
				//2:获取管理模式，封装参数
				getPrecisionStrategyList(precisionStrategyParams, res => {
					if (res.success) {
						this.managementList = res.list;
						var params = this.setRecordParams()
						console.log("提交参数", JSON.stringify(params));

						repleinshRecordSubmit(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);
					}
				});
			},


			setRecordParams() {
				var subList = []
				var creator = this.$store.state.user.id
				this.detailSource.forEach(item => {
					item.subList.forEach(detail => {
						if (detail.scaned) {
							var info = getPackingNumberAndBatchByList(this.managementList, detail.itemCode,
								detail.packingNumber, detail.toLocationCode, detail.batch);
							var submitItem = deepCopyData(detail)
							submitItem.toPackingNumber = info.packingNumber;
							submitItem.toBatch = info.batch;
							submitItem.toContainerNumber = detail.containerNumber;

							submitItem.fromPackingNumber = info.packingNumber;
							submitItem.fromBatch = info.batch;
							submitItem.fromContainerNumber = detail.containerNumber;

							submitItem.fromLocationCode = detail.locationCode;
							submitItem.toLocationCode = detail.toLocationCode;

							// detail.toInventoryStatus = detail.inventoryStatus
							// detail.toLocationCode = detail.toLocationCode
							submitItem.qty = detail.handleQty;
							submitItem.package = "";
							submitItem.recordList = [{
								toInventoryStatus: detail.inventoryStatus,
								fromPackingNumber: info.packingNumber,
								fromParentPackingNumber: detail.parentNumber,
								fromBatch: info.batch,

								toPackingNumber: info.packingNumber,

								toBatch: info.batch,
								fromLocationCode: detail.locationCode,
								toLocationCode: detail.toLocationCode,
								handleQty: detail.handleQty,
								fromPackUnit: detail.packUnit,
								toPackUnit: detail.packUnit,
								fromPackQty: detail.packQty,
								toPackQty: detail.packQty
							}]
							subList.push(submitItem)
						}
					})
				})
				if (subList.length > 0) {
					this.dataContent.toWarehouseCode = subList[0].toWarehouseCode;
				}
				this.dataContent.subList = subList
				this.dataContent.creator = creator;
				this.dataContent.fromWarehouseCode = this.fromWarehouseCode;
				return this.dataContent;
			},

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

			showScanMessage(message) {
				this.$refs.comMessage.showScanMessage(message);
			},

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

			closeScanMessage() {
				this.scanPopupGetFocus();
			},
			getToLocationCode(location, code) {
				if (this.fromLocationCode == code) {
					uni.showToast({
						title: "来源库位[" + this.fromLocationCode + "]不能与目标库位[" + code + "]一致",
						duration: 2000
					})
					return
				}
				this.toLocationCode = code;
			},

			showCommitSuccessMessage(hint) {
				this.$refs.comMessage.showSuccessMessage(hint, res => {
					this.clear();
				})
			},

			clear() {
				this.fromLocationCode = '';
				this.fromWarehouseCode = '';
				this.toWarehouseCode = '';
				this.detailSource = [];
				this.toLocationCode = "";
				this.itemCode = ""
			}
		}
	}
</script>

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