<template>
	<page-meta root-font-size="18px"></page-meta>
	<view class="">
		<win-blank-view @goScan='openScanPopup' v-if="fromLocation==null"></win-blank-view>
		<scroll-view scroll-y="true" class="scroll-Y" @scrolltoupper="upper" @scrolltolower="lower" @scroll="scroll"
			style="padding-bottom:150px">
			<view class="top_wrap" v-if="fromLocation!=null">
				<view class="top_card">
					<view class="uni-flex space-between top_lines_info">
						<view class="font_sm">
							来源库位:
							<text class="text_bold">{{fromLocation.code}}</text>
						</view>
						<view><text class="text_bold">{{fromLocationTypeDesc}}</text></view>
					</view>
				</view>
			</view>
			<uni-collapse v-if="fromLocation!=null">
				<view class="pop_list list_info semi_col" v-for="(item, index) in itemList">
					<semi-collapse-item :open="true" :title="item.itemCode" :item="item" :scanCount="item.scanQty"
						style="font-size: 20px; ">
						<view v-for="(label, index) in item.labelList">
							<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>
								</uni-swipe-action-item>
							</uni-swipe-action>
						</view>
					</semi-collapse-item>
				</view>
			</uni-collapse>
		</scroll-view>
		<div class="new_bot_box" v-show="fromLocation!=null">
			<win-collapse-location ref='comToLocation' @getLocationCode='getToLocation' @clear='clearLocation'>
			</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="fromLocation!=null"></win-scan-button>
		<win-scan-by-code ref="scanLocationCodePopup" title="来源库位" @getScanCode='scanLocation'></win-scan-by-code>
		<win-scan-by-pack ref="scanPackPopup" @getScanResult='getScanResult'></win-scan-by-pack>
		<com-balance ref="balanceItems" @selectedItem='selectedBalanceItem'></com-balance>
		<com-message ref="comMessage" @afterRescanMessage='afterRescan' @afterCloseCommitMessage='closeCommitMessage'>
		</com-message>
	</view>
</template>

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

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

	import winBlankView from '@/mycomponents/wincom/winBlankView.vue'
	import comBaseItem from '@/mycomponents/comItem/comBaseItem.vue'
	import winScanButton from '@/mycomponents/wincom/winScanButton.vue'
	import winScanByPack from '@/mycomponents/wincom/winScanByPack.vue'
	import winScanByCode from '@/mycomponents/wincom/winScanByCode.vue'
	import comScanSemiPutaway from '@/mycomponents/scan/comScanSemiPutaway.vue'
	import comMessage from '@/mycomponents/common/comMessage.vue'
	import comBalance from '@/mycomponents/common/comBalance.vue'
	import winCollapseLocation from '@/mycomponents/wincom/winCollapseLocation.vue'
	import SemiCollapseItem from '@/mycomponents/common/SemiCollapseItem.vue'

	export default {
		name: 'semiPutaway',
		components: {
			winBlankView,
			comBaseItem,
			comMessage,
			winScanButton,
			winScanByPack,
			winScanByCode,
			comScanSemiPutaway,
			comBalance,
			winCollapseLocation,
			SemiCollapseItem
		},
		data() {
			return {
				options: [],
				itemList: [],
				fromLocation: null,
				fromLocationTypeDesc: '',
				toLocation: null,
				currentLabel: null
			};
		},
		props: {
			// locationTypes: {
			// 	type: [Array, String, Number],
			// 	value: ''
			// },
		},

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

		methods: {
			openScanPopup() {
				if (this.fromLocation == null) { //扫描来源库位
					this.$refs.scanLocationCodePopup.openScanPopup()
				} else { //扫描箱标签
					this.openPackLabel();
				}
			},

			openPackLabel() {
				this.$refs.scanPackPopup.openScanPopup()
			},

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

			//扫描源库位
			scanLocation(code) {
				let that = this;
				if (code == '') return;
				uni.showLoading({
					title: '扫描中...',
					mask: true
				});
				locations(code).then(res => {
					if (res != null) {
						if (res.type == 5 || res.type == 3 || res.type == 4) {
							that.fromLocation = res;
							that.fromLocationTypeDesc = getLocationTypeDesc(res.type);
							this.openPackLabel();
							this.closeScanPopup();
						} else {
							that.showMessage('来源库位的库位类型必须是【线边库位】【半成品库位】【成品库位】');
						}
					} else {
						that.showMessage('未查询到库位' + '【' + code + '】');
					}
					uni.hideLoading();
				}).catch(err => {
					uni.hideLoading();
					that.showMessage(err.message);
				});
			},

			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.code;
				if (code) {
					let datas = [];
					//判断是否重复扫描
					that.itemList.forEach(l => {
						l.labelList.filter(r => {
							if (r.packingCode == code) {
								datas.push(r);
								return;
							}
						})
					})
					if (datas.length > 0) {
						this.showScanMessage('箱码【' + code + '】已经存在,是否要重新扫描?');
						// showConfirmMsg('箱码【' + code + '】已经存在,是否要重新扫描?', confirm => {
						// 	if (confirm) {
						// 		that.itemList.forEach(l => {
						// 			l.labelList.forEach((r, i) => {
						// 				if (r.packingCode == code) {
						// 					l.labelList.splice(i, 1);
						// 					return;
						// 				}
						// 			});
						// 		})
						// 		that.getLabel(result);
						// 	}
						// });
					} else {
						that.getLabel();
					}

				} else {
					this.showScanMessage('请先扫描箱标签');
					return;
				}
			},

			//重新扫描
			afterRescan(confirm) {
				let that = this;
				if (confirm) {
					that.itemList.forEach(l => {
						l.labelList.forEach((r, i) => {
							if (r.packingCode == that.currentLabel.packingCode) {
								l.labelList.splice(i, 1);
								return;
							}
						});
					})
					that.getLabel();
				} else {
					this.scanPopupGetFocus();
				}
			},

			async getLabel() {
				let that = this;
				uni.showLoading({
					title: '扫描中...',
					mask: true
				})

				//查询箱码是否有库存
				let balanceParams = {
					pageSize: 100,
					pageIndex: 1,
					packingCode: that.currentLabel.code
				};
				let res = await getBalancesByFilterAsync(balanceParams);
				if (res.totalCount > 0) {
					let locationCode = res.items[0].locationCode;
					this.showScanMessage('箱码【' + that.currentLabel.code + '】在【' + locationCode +
						'】库位已经有库存信息,请重新扫描箱码');
				} else {
					let itemInfo = that.itemList.find(r => {
						return r.itemCode == that.currentLabel.itemCode
					})
					if (itemInfo == undefined) {
						let params = {
							locationCode: that.fromLocation.code,
							itemCode: that.currentLabel.itemCode
						};

						let balanceRes = await getWipListAsync(params);
						if (balanceRes.totalCount == 0) {
							that.showScanMessage('按零件号和库位【' + that.fromLocation.code + ',' + that.currentLabel
								.itemCode +
								'】未查找到缴库信息');
						} else {
							let balanceItem = balanceRes.items[0];
							let item = {
								itemCode: that.currentLabel.itemCode,
								totalQty: balanceItem.qty,
								uom: balanceItem.uom,
								scanQty: 0,
								status: balanceItem.status,
								balanceItem: balanceItem,
								labelList: []
							};
							this.addLabel(item);
						}
					} else {
						this.addLabel(itemInfo);
					}
				}
				uni.hideLoading();
			},

			addLabel(item) {
				//没有标签
				if (item.labelList.length == 0) {
					if (this.currentLabel.qty > item.totalQty) {
						this.showScanMessage('标签数量【' + this.currentLabel.qty +
							'】大于零件的库存数量【' + item.totalQty + '】,不可以上架')
					} else {
						let data = this.itemList.find(r => r.itemCode == item.itemCode)
						if (data == undefined) {
							this.itemList.push(item)
						}
						this.calcScanQty(item, 0)
						item.labelList.unshift(this.currentLabel);
						this.scanPopupGetFocus();
					}
				} else {
					let scanQty = 0;
					item.labelList.forEach(r => {
						scanQty += Number(r.qty)
					})
					if (scanQty + this.currentLabel.qty > item.totalQty) {
						this.showScanMessage('已扫描数量【' + scanQty + '】加标签数量【' + this.currentLabel.qty +
							'】大于零件的库存数量【' + item.totalQty + '】,不可以上架')
					} else {
						this.calcScanQty(item, scanQty)
						item.labelList.unshift(this.currentLabel);
						this.scanPopupGetFocus();
					}
				}
			},

			calcScanQty(item, scanQty) {
				item.scanQty = scanQty + this.currentLabel.qty;

				//标签赋默认值
				this.currentLabel.locationCode = this.fromLocation.code;
				this.currentLabel.status = 2;

			},

			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 + '】不存在');
						that.$refs.comToLocation.clearLocation();
					} else {
						if (res.type != 3) {
							this.showMessage('目标库位必须是【半成品库】')
						} else {
							this.toLocation = res;
						}
					}
					uni.hideLoading();
				}).catch(err => {
					that.toLocationCode = ''
					that.showMessage(err.message);
					uni.hideLoading();
				})
			},

			clearLocation() {
				this.toLocation = null;
			},

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

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

				let item = {
					number: "",
					worker: localStorage.userName,
					jobNumber: "",
					putawayType: 2,

					details: []
				}
				that.itemList.forEach(i => {
					i.labelList.forEach(r => {
						r.fromLot = '',
							r.arriveDate = r.arriveDate,
							r.fromLocationCode = this.fromLocation.code,
							r.fromLocationErpCode = this.fromLocation.erpLocationCode,
							r.fromLocationGroup = this.fromLocation.locationGroupCode,
							r.fromLocationArea = this.fromLocation.areaCode,
							r.fromPackingCode = "",
							r.fromStatus = i.status,
							r.fromWarehouseCode = i.balanceItem.warehouseCode,
							// r.fromStatus = r.status,
							r.toLot = r.lot,
							r.toPackingCode = r.packingCode,
							r.toLocationCode = this.toLocation.code,
							r.toLocationErpCode = this.toLocation.erpLocationCode,
							r.toLocationArea = this.toLocation.areaCode,
							r.toLocationGroup = this.toLocation.locationGroupCode,
							r.toStatus = i.status,
							r.toWarehouseCode = i.balanceItem.warehouseCode,
							// ========================================

							r.recommendContainerCode = i.balanceItem.containerCode,
							r.recommendPackingCode = r.packingCode,
							r.recommendSupplierBatch = i.balanceItem.supplierBatch,
							r.recommendArriveDate = r.arriveDate,
							r.recommendProduceDate = i.balanceItem.produceDate,
							r.recommendExpireDate = i.balanceItem.expireDate;
							r.recommendLot = r.lot,
							r.recommendToLocationCode = this.toLocation.code,
							r.recommendToLocationArea = this.toLocation.areaCode,
							r.recommendToLocationGroup = this.toLocation.locationGroupCode,
							r.recommendToLocationErpCode = this.toLocation.erpLocationCode,
							r.recommendToWarehouseCode = i.balanceItem.warehouseCode,
							r.recommendQty = r.qty,
						    r.handledContainerCode = i.balanceItem.containerCode,
							r.handledPackingCode = r.packingCode,
							r.handledSupplierBatch = i.balanceItem.supplierBatch,
							r.handledArriveDate = r.arriveDate,
							r.handledProduceDate = i.balanceItem.produceDate,
							r.handledExpireDate = i.balanceItem.expireDate;
							r.handledLot = r.lot,
							r.handledToLocationCode = this.toLocation.code,
							r.handledToLocationArea = this.toLocation.areaCode,
							r.handledToLocationGroup = this.toLocation.locationGroupCode,
							r.handledToLocationErpCode = this.toLocation.erpLocationCode,
							r.handledToWarehouseCode = i.balanceItem.warehouseCode,
							r.handledQty = r.qty,

							item.details.push(r);
					})
				})

				let params = JSON.stringify(item);
				semiPutaway(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.fromLocation = null;
				that.toLocation = null;
			},

			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);
			},
			showCommitSuccess() {
				this.$refs.comMessage.showCommitSuccess();
			},
			showScanMessage(message) {
				this.$refs.comMessage.showScanMessage(message);
			},
			closeScanMessage() {
				this.$refs.scanPackPopup.getfocus();
			},
			getfocus() {
				this.$refs.scanLocationCodePopup.getfocus();
			},

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

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

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

		}
	};
</script>

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