<template>
	<page-meta root-font-size="18px"></page-meta>
	<view class="">
		<win-blank-view @goScan='openScanPopup' v-if="itemList.length==0"></win-blank-view>
		<view class="top_wrap" v-if="itemList.length>0">
			<view class="top_card">
				<view class="uni-flex space-between top_lines_info">
					<view class="font_sm">
						指定ERP储位:
						<text class="text_bold">{{recommendErpLocationCode}}</text>
					</view>
				</view>
			</view>
		</view>

		<scroll-view scroll-y="true" class="scroll-Y" @scrolltoupper="upper" @scrolltolower="lower" @scroll="scroll"
			style="padding-bottom:150px">
			<uni-collapse v-if="itemList.length>0">
				<view class="pop_list list_info semi_col" v-for="(item, index) in itemList" :key="item.id">
					<com-collapse-item :open="true" :title="item.itemCode" :item="item" :scanCount="item.scanQty"
						style="font-size: 20px; ">
						<view v-for="(label, index) in item.labelList" :key="item.id">
							<uni-swipe-action>
								<uni-swipe-action-item :right-options="options" :auto-close="false"
									@click="swipeClick($event,item,index)" style='background-color: #ffffff;'>
									<com-base-item :dataContent="label" style='margin-left: 10px;'></com-base-item>
									<view class="choose_marked">
										<image src="@/static/image_marked.svg"></image>
									</view>
								</uni-swipe-action-item>
							</uni-swipe-action>
						</view>
					</com-collapse-item>
				</view>
			</uni-collapse>
		</scroll-view>

		<div class="new_bot_box" v-show="itemList.length>0">
			<win-collapse-location ref='comCollapseLocation' @getLocationCode='getToLocation' @clear='clear'>
			</win-collapse-location>
			<view class="new_btn_bot bot_pos uni-flex">
				<button class="new_clear_btn btn_double" @click="cancel()">清空</button>
				<button class="new_save_btn btn_double" @click="submit()">提交</button>
			</view>
		</div>

		<win-scan-button @goScan='openScanPopup' v-if="itemList.length>0"></win-scan-button>
		<win-scan-pack ref="scanPopup" @getScanResult='getScanResult'></win-scan-pack><com-balance ref="balanceItems" @selectedItem='selectedBalanceItem'></com-balance>
		<com-message ref="comMessage" @afterCloseScanMessage='closeScanMessage' @afterRescanMessage='afterRescan'
			@afterCloseCommitMessage='closeCommitMessage'>
		</com-message>
	</view>
</template>

<script>
	import {
		locations,
		getBalancesByFilterAsync,
		getPurchaseDetailAsync,
		purchasePutaway,
	} from '@/api/index.js';

	import {
		showConfirmMsg,
		goHome,
		getRemoveOption
	} from '@/common/basic.js';

	import winBlankView from '@/mycomponents/wincom/winBlankView.vue'
	import comBaseItem from '@/mycomponents/comItem/comBaseItem.vue'
	import winScanButton from '@/mycomponents/wincom/scanCom/winScanButton.vue'
	import winScanPack from '@/mycomponents/wincom/scanCom/winScanPack.vue'
	import comMessage from '@/mycomponents/common/comMessage.vue'
	import comBalance from '@/mycomponents/common/comBalance.vue'
	import winCollapseLocation from '@/mycomponents/wincom/winCollapseLocation.vue'
	import comCollapseItem from '@/mycomponents/common/comCollapseItem.vue'

	export default {
		
		name: 'purchasePutaway',
		components: {
			winBlankView,
			comBaseItem,
			comMessage,
			winScanButton,
			winScanPack,
			comBalance,
			winCollapseLocation,
			comCollapseItem
		},
		data() {
			return {
				options: [],
				itemList: [],
				location: null,
				recommendErpLocationCode: '',
				currentLabel: null,
				reScanItem: null, //重复的箱码
			};
		},
		props: {
			// locationTypes: {
			// 	type: [Array, String, Number],
			// 	value: ''
			// },
		},

		onNavigationBarButtonTap(e) {
			if (e.index === 0) {
				goHome();
			}
		},
		mounted: function() {
			this.options = getRemoveOption();
		},

		methods: {
			openScanPopup() {
				this.$refs.scanPopup.openScanPopup()
			},

			swipeClick(e, item, index) {
				let {
					content
				} = e;
				if (content.text === '移除') {
					uni.showModal({
						title: '提示',
						content: '是否移除选择的行?',
						success: res => {
							if (res.confirm) {
								this.removeLabel(item, index)
							}
						}
					});
				}
			},

			removeLabel(item, index) {
				let label = item.labelList[index];
				item.scanQty = item.scanQty - label.qty;
				item.labelList.splice(index, 1);
				if (item.labelList.length == 0) {
					let itemIndex = this.itemList.findIndex(r => {
						return r.itemCode == item.itemCode
					})
					this.itemList.splice(itemIndex, 1)
				}
			},

			getScanResult(result) {
				let that = this;
				that.currentLabel = result.data;
				let code = result.data.packingCode;
				let itemInfo = that.itemList.find(r => {
					return r.itemCode == result.data.itemCode
				})
				if (itemInfo == undefined) {
					that.getBalance();
				} else {
					let data = itemInfo.labelList.find(r => {
						return r.packingCode == code
					})
					if (data == undefined) {
						that.getBalance();
					} else {
						this.reScanItem = itemInfo;
						this.showRescanMessage('箱码【' + code + '】已经存在,是否要重新扫描?');
						// showConfirmMsg('箱码【' + code + '】已经存在,是否要重新扫描?', confirm => {
						// 	if (confirm) {
						// 		itemInfo.labelList.forEach((r, i) => {
						// 			if (r.packingCode == code) {
						// 				itemInfo.labelList.splice(i, 1);
						// 				return;
						// 			}
						// 		});
						// 		that.getBalance();
						// 	} else {
						// 		this.scanPopupGetFocus();
						// 	}
						// });
					}
				}
			},
			//重新扫描
			afterRescan(val) {
				let that = this;
				if (val) {
					that.reScanItem.labelList.forEach((r, i) => {
						if (r.packingCode == that.currentLabel.packingCode) {
							that.reScanItem.labelList.splice(i, 1);
							return;
						}
					});
					that.reScanItem = null;
					that.getBalance();
				} else {
					that.scanPopupGetFocus();
				}
			},

			async getBalance() {
				uni.showLoading({
					title: '加载中...',
					mask: true
				})
				let that = this;
				let packingCode = that.currentLabel.packingCode;
				let params = {
					pageSize: 100,
					pageIndex: 1,
					locationTypes: [1], //待检库
					inventoryStatuses: [2], //合格
					packingCode: packingCode
				};

				let balanceRes = await getBalancesByFilterAsync(params);
				if (balanceRes.totalCount === 0) {
					that.showScanMessage('箱码【' + packingCode + '】在【待检库】未查询到库存状态为【合格】的库存信息');
				} else if (balanceRes.totalCount === 1) {
					let balanceItem = balanceRes.items[0];
					//根据零件号和箱码获取采购信息
					let purchaseDetail = await getPurchaseDetailAsync(balanceItem.itemCode, balanceItem
						.packingCode);
					if (purchaseDetail.error) {
						that.showScanMessage(purchaseDetail.error.message);
					} else {
						that.createBalanceItem(balanceItem, purchaseDetail);
					}
				} else {
					that.$refs.balanceItems.openPopup(balanceRes.items);
				}
				uni.hideLoading()
			},

			createBalanceItem(balanceItem, purchaseDetail) {
				let locationErpCode = purchaseDetail.recommendErpCode;
				if (this.itemList.length == 0) {
					this.recommendErpLocationCode = locationErpCode;
					this.createItem(balanceItem, purchaseDetail);
				} else {
					if (this.recommendErpLocationCode != locationErpCode) {
						this.showScanMessage('当前零件的ERP储位是【' + locationErpCode + '】与【' + this
							.recommendErpLocationCode +
							'】不是同一ERP储位,请重新扫描');
					} else {
						this.createItem(balanceItem, purchaseDetail);
					}
				}
			},

			createItem(balanceItem, purchaseDetail) {
				let that = this;
				let label = that.currentLabel;
				let itemInfo = that.itemList.find(r => {
					return r.itemCode == label.itemCode
				})

				if (itemInfo == undefined) {
					itemInfo = {
						itemCode: label.itemCode,
						totalQty: label.qty,
						uom: label.uom,
						scanQty: 0,
						// status: balanceItem.status,
						// balanceItem: balanceItem,
						labelList: []
					};
					this.itemList.push(itemInfo)
				}
				let newLabel = this.createLabel(balanceItem, purchaseDetail);
				this.addLabel(itemInfo, newLabel);
				this.scanPopupGetFocus();
			},

			createLabel(balanceItem, purchaseDetail) {
				let label = this.currentLabel;
				label.putawayType = 0;
				label.qty = balanceItem.qty;
				label.uom = balanceItem.uom;
				label.status = balanceItem.status;
				label.locationCode = balanceItem.locationCode;
				label.fromContainerCode = balanceItem.containerCode;
				label.fromStatus = balanceItem.status;
				label.fromPackingCode = balanceItem.packingCode;
				label.fromLocationCode = balanceItem.locationCode;
				label.fromLocationGroup = balanceItem.locationGroup;
				label.fromLocationArea = balanceItem.locationArea;
				label.fromLocationErpCode = balanceItem.locationErpCode;
				label.fromWarehouseCode = balanceItem.warehouseCode;
				label.fromLot = balanceItem.lot;

				label.poNumber = purchaseDetail.poNumber;
				label.poLine = purchaseDetail.poLine;
				label.supplierPackUom = purchaseDetail.supplierPackUom;
				label.supplierPackQty = purchaseDetail.supplierPackQty;
				label.stdPackUom = purchaseDetail.stdPackUom;
				label.stdPackQty = purchaseDetail.stdPackQty;

				label.worker = localStorage.userName;
				return label;
			},

			addLabel(item, label) {
				item.labelList.unshift(label);
				item.scanQty += label.qty;
			},

			async selectedBalanceItem(balanceItem) {
				let purchaseDetail = await getPurchaseDetailAsync(balanceItem.itemCode, balanceItem
					.packingCode);
				if (purchaseDetail != null) {
					this.createBalanceItem(purchaseDetail);
				} else {
					this.showScanMessage('未查到零件【' + balanceItem.itemCode + '】的采购信息');
				}
			},

			getToLocation(code) {
				if (code == '') {
					this.showMessage('目标库位不能为空');
					return;
				}
				uni.showLoading({
					title: "扫描中",
					mask: true
				});
				let that = this;
				locations(code).then(res => {
					if (res == null) {
						that.showMessage('目标库位【' + code + '】不存在');
						this.$refs.comCollapseLocation.clearLocation();
					} else {
						if (res.type != 2) {
							this.showMessage('目标库位必须是原材料库')
							this.$refs.comCollapseLocation.clearLocation();
						} else {
							if (that.recommendErpLocationCode != res.erpLocationCode) {
								that.showMessage('目标库位的ERP储位【' + res.erpLocationCode + '】与【' + this
									.recommendErpLocationCode +
									'】不是同一ERP储位,请重新扫描');
								this.$refs.comCollapseLocation.clearLocation();
							} else {
								this.location = res;
							}
						}
					}
					uni.hideLoading();
				}).catch(err => {
					that.location = null;
					that.showMessage(err.message);
					uni.hideLoading();
				})
			},

			clear() {
				this.location = null;
			},

			submit() {
				let that = this;
				if (that.itemList.length === 0) {
					that.showMessage('请扫描要提交的零件');
					return;
				}
				if (that.location === null) {
					that.showMessage('请扫描目标库位');
					return;
				}

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

				let item = {
					company: localStorage.company,
					number: "",
					worker: localStorage.userName,
					warehouseCode: localStorage.warehouseCode,
					jobNumber: "validation errors",
					details: []
				}

				that.itemList.forEach(i => {
					i.labelList.forEach(r => {
						r.toContainerCode = r.fromContainerCode,
							r.toStatus = r.fromStatus,
							r.toPackingCode = r.fromPackingCode,
							r.toWarehouseCode = r.fromWarehouseCode,
							r.toLot = r.fromLot,
							r.toLocationCode = that.location.code,
							r.toLocationGroup = that.location.locationGroupCode,
							r.toLocationArea = that.location.areaCode,
							r.toLocationErpCode = that.location.erpLocationCode,

							r.worker = localStorage.userName,
							item.details.push(r);
					})
				})
				let params = JSON.stringify(item);
				purchasePutaway(params)
					.then(res => {
						that.showCommitSuccess();
						that.clearInfo();
						uni.hideLoading();
					})
					.catch(err => {
						that.showMessage(err.message);
						uni.hideLoading();
					});
			},

			cancel() {
				let that = this;
				showConfirmMsg('是否要清空已扫描的零件和目标库位信息?', confirm => {
					if (confirm) {
						that.clearInfo();
					}
				})
			},

			clearInfo() {
				let that = this;
				that.itemList = [];
				that.location = null;
				that.recommendErpLocationCode = '';
			},

			clearPackCode() {
				this.isClearPackCode = !this.isClearPackCode;
			},

			clearContainerCode() {
				this.isClearContainerCode = !this.isClearContainerCode;
			},

			clearLot() {
				this.isClearLot = !this.isClearLot;
			},

			upper: function(e) {
				// console.log(e)
			},
			lower: function(e) {
				// console.log(e)
			},
			scroll: function(e) {
				// console.log(e)
				this.old.scrollTop = e.detail.scrollTop;
			},

			showMessage(message) {
				this.$refs.comMessage.showMessage(message);
			},
			showConfirmMessage(message) {
				this.$refs.comMessage.showConfirmMessage(message);
			},
			showCommitSuccess() {
				this.$refs.comMessage.showCommitSuccess();
			},
			showScanMessage(message) {
				this.$refs.comMessage.showScanMessage(message);
			},
			showRescanMessage(message) {
				this.$refs.comMessage.showRescanMessage(message);
			},

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

			closeCommitMessage() {
				this.openScanPopup();
			},

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

			scanPopupLoseFocus(message) {
				this.$refs.scanPopup.losefocus();
			},
		}
	};
</script>

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