<template>
	<page-meta root-font-size="18px"></page-meta>
	<view class="">
		<win-blank-view @goScan='openScanPopup' v-if="itemList.length==0"></win-blank-view>
		<scroll-view scroll-y="true" class="scroll-Y" 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;'>
									<view class="choose_main common_card">
										<view class="ljh_box">
											<view class="ljh_info">
												<view class="tit_ljh">{{ label.itemCode }}</view>
												<view class="label_xm font_xs fr">{{ label.packingCode }}</view>
											</view>
											<view class="uni-flex space-between desc_card">
												<view class="ljh_left">
													<view class="text_lightblue font_xs">{{label.itemName }}</view>
													<view class="text_lightblue font_xs">{{label.itemDesc1}}</view>
												</view>
												<view class="ljh_right uni-flex">
													<!-- @change="qtyChanged($event,item)" -->
													<com-number-box v-model="label.qty" :max="99999" :min="0"
														style='width: 100px;' @change="qtyChanged($event,item,label)">
													</com-number-box>
													<text class="tunit">{{label.uom}}</text>
												</view>
											</view>
										</view>
										<com-erp-location :erpLocationCode="label.locationErpCode"></com-erp-location>
										<com-item-bottom :dataContent="label"></com-item-bottom>
									</view>
									<view class="choose_marked" style="z-index: 0;">
										<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='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="itemList.length>0"></win-scan-button>
		<win-scan-by-pack ref="scanPopup" @getScanResult='getScanResult'>
		</win-scan-by-pack>
		<com-balance ref="balanceItems" @selectedItem='selectedBalanceItem'></com-balance>
		<com-message ref="comMessage" @afterCloseScanMessage='closeScanMessage' @afterRescanMessage='afterRescan'
			@afterCloseCommitMessage='closeCommitMessage'></com-message>
	</view>
	</view>
</template>

<script>
	import {
		getBalancesExpectByFilter,
		issueDirect,
		locations
	} from '@/api/index.js';

	import {
		getInventoryStatusArray
	} from '@/common/array.js'

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

	import winBlankView from '@/mycomponents/wincom/winBlankView.vue'
	import comBalanceItem from '@/mycomponents/comItem/comBalanceItem.vue'
	import winScanButton from '@/mycomponents/wincom/winScanButton.vue'
	import winScanByPack from '@/mycomponents/wincom/winScanByPack.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'
	import comErpLocation from '@/mycomponents/comItem/comErpLocation.vue'
	import comItemBottom from '@/mycomponents/comItem/comItemBottom.vue'
	import comNumberBox from '@/mycomponents/common/comNumberBox.vue';

	export default {
		name: 'deliverRaw',
		components: {
			winBlankView,
			comBalanceItem,
			comMessage,
			winScanButton,
			winScanByPack,
			comBalance,
			winCollapseLocation,
			comCollapseItem,
			comErpLocation,
			comItemBottom,
			comNumberBox
		},
		data() {
			return {
				options: [],
				itemList: [],
				toLocation: null,
				currentLabel: null,
				reScanItem: null, //重复的箱码
			};
		},
		props: {

		},

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

		methods: {

			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 = that.currentLabel.packingCode;
				let itemInfo = that.itemList.find(r => {
					return r.itemCode == that.currentLabel.itemCode
				})
				if (itemInfo == undefined) {
					that.getBalance();
				} else {
					let data = itemInfo.labelList.find(r => {
						return r.packingCode == code
					})
					if (data == undefined) {
						that.getBalance();
					} else {
						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(confirm) {
				let that = this;
				if (confirm) {
					that.reScanItem.labelList.forEach((r, i) => {
						if (r.packingCode == that.currentLabel.packingCode) {
							that.reScanItem.labelList.splice(i, 1);
							return;
						}
					});
					that.getBalance();
				} else {
					this.scanPopupGetFocus();
				}
			},

			getBalance() {
				uni.showLoading({
					title: '加载中',
					mask: true
				})
				let that = this;
				//按照零件号和箱码去查询库存
				let params = {
					pageSize: 100,
					pageIndex: 1,
					locationTypes: [2, 3],
					itemCode: that.currentLabel.itemCode,
					packingCode: that.currentLabel.packingCode,
					lot: that.currentLabel.lot,
				};
				getBalancesExpectByFilter(params)
					.then(res => {
						try {
							if (res.totalCount === 0) {
								this.showScanMessage('箱码【' + that.currentLabel.packingCode + '】在【原料库】【半成品库】未查询到库存信息');
							} else if (res.totalCount === 1) {
								let balanceItem = res.items[0];
								this.createItem(balanceItem);
							} else {
								this.$refs.balanceItems.openPopup(res.items);
							}
						} catch (e) {
							this.showScanMessage(e.message);
						}
						this.scanPopupGetFocus();
						uni.hideLoading();
					})
					.catch(err => {
						this.showScanMessage(err.message);
						this.scanPopupGetFocus();
						uni.hideLoading();
					});
			},

			createItem(balanceItem) {
				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.unshift(itemInfo);
				}
				this.addLabel(itemInfo, balanceItem);
				this.calcScanCount(itemInfo);
			},

			addLabel(item, balanceItem) {
				let label = this.currentLabel;
				label.qty = balanceItem.qty;
				label.uom = balanceItem.uom;
				label.locationCode = balanceItem.locationCode;
				label.locationGroup = balanceItem.locationGroup;
				label.locationArea = balanceItem.locationArea;
				label.locationErpCode = balanceItem.locationErpCode;
				label.warehouseCode = balanceItem.warehouseCode;
				label.status = balanceItem.status;

				label.fromPackingCode = balanceItem.packingCode;
				label.fromContainerCode = balanceItem.containerCode;
				label.fromLot = balanceItem.lot;

				label.fromLocationCode = balanceItem.locationCode;
				label.fromLocationGroup = balanceItem.locationGroup;
				label.fromLocationArea = balanceItem.locationArea;
				label.fromLocationErpCode = balanceItem.locationErpCode;
				label.fromWarehouseCode = balanceItem.warehouseCode;
				label.fromStatus = balanceItem.status;

				// label.toPackingCode = this.currentLabel.packingCode;
				// label.toContainerCode = this.currentLabel.containerCode;
				label.toPackingCode = '';
				label.toContainerCode = '';
				label.toLot = '';
				label.toWarehouseCode = localStorage.warehouseCode;
				label.toStatus = balanceItem.status;
				// item.supplierBatch = balanceItem.supplierBatch;
				// item.arriveDate = balanceItem.arriveDate;
				// item.produceDate = balanceItem.produceDate;
				// item.expireDate = balanceItem.expireDate;
				
				// ====================================
				
				
			  label.recommendContainerCode=balanceItem.containerCode;
			  label.recommendPackingCode=balanceItem.packingCode;
			  label.recommendSupplierBatch=balanceItem.supplierBatch;;
			  label.recommendArriveDate=balanceItem.arriveDate;
			  label.recommendProduceDate=balanceItem.produceDate;
			  label.recommendExpireDate= balanceItem.expireDate;
		
			  label.recommendLot= balanceItem.lot;;
			  label.recommendFromLocationCode=balanceItem.locationCode;
			  label.recommendFromLocationArea=balanceItem.locationArea;
			  label.recommendFromLocationGroup=balanceItem.locationGroup;
			  label.recommendFromLocationErpCode=balanceItem.locationErpCode;
			  label.recommendFromWarehouseCode=localStorage.warehouseCode;;
			  label.recommendQty= balanceItem.qty;
			  label.handledContainerCode=balanceItem.containerCode;
			  label.handledPackingCode=balanceItem.packingCode;;
			  label.handledSupplierBatch= balanceItem.supplierBatch;
			  label.handledArriveDate=balanceItem.arriveDate;
			  label.handledProduceDate=balanceItem.produceDate;
			  label.handledExpireDate=balanceItem.expireDate;
			
			  label.handledLot = balanceItem.lot;
			  label.handledToLocationCode = balanceItem.locationCode;
			  label.handledToLocationArea = balanceItem.locationArea;
			  label.handledToLocationGroup =  balanceItem.locationGroup;
			  label.handledToLocationErpCode = balanceItem.locationErpCode;
			  label.handledToWarehouseCode = balanceItem.warehouseCode;
			  label.handledQty = balanceItem.qty;
			  item.labelList.unshift(label)
			},

			calcScanCount(item) {
				let scanQty = 0;
				item.labelList.forEach(r => scanQty += r.qty)
				item.scanQty = scanQty;
			},

			selectedBalanceItem(balanceItem) {
				this.createItem(balanceItem);
			},

			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 != 5) {
							this.showMessage('目标库位必须是【线边库】')
						} else {
							this.toLocation = res;
						}
					}
					uni.hideLoading();
				}).catch(err => {
					that.toLocationCode = ''
					that.showMessage(err.message);
					uni.hideLoading();
				})
			},

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

			clearCustomerAddress() {
				this.customerAddressArray = [];
				this.toLocation = null;
				this.customerAddress = null;
				this.customerAddressCode = ''
			},

			submit() {
				let that = this;
				if (that.itemList.length === 0) {
					that.showMessage('请扫描要提交的零件');
					return;
				}
				if (that.toLocation == null) {
					that.showMessage('请扫描目标库位');
					return;
				}
				let message = '';
				that.itemList.forEach(r => {
					r.labelList.forEach(l => {
						if (l.qty <= 0) {
							message += l.packingCode + ','
						}
					})
				})

				if (message != '') {
					this.showMessage('箱码【' + message + '】数量为0不允许发料');
					return;
				} else {
					uni.showLoading({
						title: "提交中....",
						mask: true
					});

					let item = {
						company: localStorage.company,
						number: "",
						worker: localStorage.userName,
						warehouseCode: localStorage.warehouseCode,
						jobNumber: "abc",
						useOnTheWayLocation: false,
						details: []
					}

					that.itemList.forEach(i => {
						i.labelList.forEach(r => {
							r.toLocationCode = this.toLocation.code,
								r.toLocationErpCode = this.toLocation.erpLocationCode,
								r.toLocationArea = this.toLocation.areaCode,
								r.toLocationGroup = this.toLocation.locationGroupCode,
								item.details.push(r);
						})
					})

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

			qtyChanged(value, item, label) {
				if (value <= 0) {
					// label.qty = 1;
					// this.showMessage('发料数量不能小于或等于0')
					// this.$forceUpdate();
				}
				this.calcScanCount(item);
			},

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

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

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

			showCommitSuccess() {
				this.$refs.comMessage.showCommitSuccess();
			},

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

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

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

			closeScanMessage() {
				this.scanPopupGetFocus();
			}
		}
	};
</script>

<style scoped lang="scss">
	/deep/ .uni-numbox__value {
		width: 40px;
	}

	// /deep/ .input-value {
	// 	font-size: 16px;
	// }

	// /deep/ .uni-collapse-item__title-text {
	// 	font-size: 16px;
	// }

	// /deep/ .uni-collapse-item--border {
	// 	border-bottom-width: 0px;
	// 	border-bottom-color: #ebeef5;
	// }

	// /deep/ .uni-collapse-item--border {
	// 	border-bottom-width: 1px;
	// 	border-bottom-color: #ebeef5;
	// }
</style>
