<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-top="scrollTop" scroll-y="true" class="scroll-Y" @scrolltoupper="upper"
			@scrolltolower="lower" @scroll="scroll" style="padding-bottom:150px">
			<view class="detail-list" v-for="(item,index) in itemList">
				<view style="-webkit-flex: 1;flex: 1;">
					<view class="detail-content">
						<uni-swipe-action>
							<uni-swipe-action-item :right-options="options" :auto-close="false"
								@click="swipeClick($event,index)">
								<view class="uni-flex uni-row" style="">
									<view style="margin-left: 10rpx; margin-top: 10rpx;"
										@click="checkeClick(item.packingCode)">
										<checkbox :value="item.packingCode" :checked="item.checked" />
										<text style="writing-mode: vertical-rl; font-size: 35rpx;margin-top: 15rpx;">
											选择此库存</text>
									</view>
									<view class="">
										<com-balance-item :dataContent="item"></com-balance-item>
									</view>
								</view>



							</uni-swipe-action-item>
						</uni-swipe-action>
					</view>
				</view>
			</view>
			<view v-if="itemList.length>0"
				style="background-color: #000; height: 1rpx;margin-top: 15rpx;margin-bottom: 15rpx;">

			</view>

		</scroll-view>

		<div class="new_bot_box" v-show="itemList.length>0">
			<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" @afterClose='afterCloseMessagg'></com-message>
	</view>
	</view>
</template>

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

	import {
		showConfirmMsg,
		goHome,
		getRemoveOption,
		scanSuccessAudio,
		scanFailedAudio,
		deepCopyData
	} 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 comNumberBox from '@/mycomponents/common/comNumberBox.vue';
	import comSplit from '@/mycomponents/coms/inventory/comSplit.vue';


	export default {
		name: 'comtransfer',
		components: {
			winBlankView,
			comBalanceItem,
			comMessage,
			winScanButton,
			winScanByPack,
			comBalance,
			winCollapseLocation,
			comNumberBox,
			comSplit
		},
		data() {
			return {
				options: [],
				itemList: [],
				fromLocationCode: '',
				scrollTop: 0,
				old: {
					scrollTop: 0
				},
				locationErpCode: '',
				toLocationErpCode: '',
				locationGotFocus: false,
				labelInfo: {}
			};
		},

		watch: {},
		mounted: function() {
			this.openScanPopup();
			this.options = getRemoveOption();
		},

		methods: {
			openScanPopup() {
				this.$refs.scanPopup.openScanPopup()
			},
			//提示是否移除选择的行?
			swipeClick(e, index) {
				let {
					content
				} = e;
				if (content.text === '移除') {
					uni.showModal({
						title: '提示',
						content: '是否移除选择的行?',
						success: res => {
							if (res.confirm) {
								this.itemList.splice(index, 1);
							}
						}
					});
				}
			},

			getScanResult(result) {
				let that = this;
				let code = result.data.code;
				let label = result.data
				let datas = that.itemList.filter(r => {
					return r.packingCode == code
				})

				if (datas.length > 0) {
					scanFailedAudio()
					setTimeout(res => {
						showConfirmMsg('箱码【' + code + '】已经存在,是否要重新扫描?', confirm => {
							if (confirm) {
								that.itemList.forEach((r, i) => {
									if (r.packingCode == code) {
										that.itemList = [];
										return;
									}
								});
								that.getBalance(code, label);
							}
						});
					}, 100)

				} else {
					that.getBalance(code, label);
				}
			},

			getBalance(packingCode, label) {
				uni.showLoading({
					title: '加载中',
					mask: true
				})
				let that = this;
				//按照ERP料号和箱码去查询库存
				let params = {
					pageSize: 100,
					pageIndex: 1,
					// locationTypes: [2, 3, 4],
					packingCode: packingCode
				};

				getBalancesByFilter(params)
					.then(res => {
						try {
							if (res.totalCount === 0) {
								scanFailedAudio()
								this.showMessage('箱码【' + packingCode + '】未查询到库存信息');
							} else if (res.totalCount === 1) {
								this.pushItem(res.items[0], label);
								this.$refs.scanPopup.closeScanPopup()
							} else {
								scanSuccessAudio()
								this.$refs.scanPopup.closeScanPopup()
								this.$refs.balanceItems.openPopup(res.items);

							}
						} catch (e) {
							scanFailedAudio()
							this.showMessage(e.message);
						}
						uni.hideLoading();
					})
					.catch(err => {
						scanFailedAudio()
						this.showMessage(err.message);
						uni.hideLoading();
					});
			},

			pushItem(balanceItem, label) {
				//校验物料号
				if (this.itemList.length > 0) {
					var itemInfo = this.itemList[0]
					if (itemInfo.itemCode != balanceItem.itemCode) {
						this.showMessage("扫描ERP料号[" + balanceItem.itemCode + "]与合箱ERP料号[" + itemInfo.itemCode +
							"]不一致,不允许合箱")
						return;
					}
				}
				let item = this.createItem(balanceItem);
				item.itemNameTemp =item.itemName
				item.itemName =item.itemDesc2
				item.checked = false
				item.label = label
				this.locationErpCode = balanceItem.locationErpCode;
				this.itemList.unshift(item);
				scanSuccessAudio()
			},

			createItem(item) {
				item.checked = true;
				item.fromLot = item.lot;
				item.toLot = item.lot;

				item.fromPackingCode = item.packingCode;
				item.toPackingCode = item.packingCode;

				item.fromContainerCode = item.containerCode;
				item.toContainerCode = item.containerCode;

				item.fromLocationCode = item.locationCode;

				item.fromWarehouseCode = localStorage.warehouseCode;
				item.toWarehouseCode = localStorage.warehouseCode;

				item.fromStatus = item.status;
				item.toStatus = item.status;

				item.fromLocationErpCode = item.locationErpCode;
				// item.fromLocationErpCode = item.locationErpCode;

				item.defaultQty = item.qty
				item.defaultUom = item.uom

				return item;
			},

			selectedBalanceItem(balanceItem) {
				this.pushItem(balanceItem,this.labelInfo);
			},

			clear() {
				this.itemList = [];
				this.splitList = []
			},

			submit() {
				let that = this;
				if (that.itemList.length < 2) {
					this.showMessage('合箱箱码必须大于等于2');
					return;
				}

				if (!this.checkData()) {
					this.showMessage('请先选择合箱的箱码');
					return;
				}

				uni.showLoading({
					title: "提交中....",
					mask: true
				});
				var params = this.setParams()
				mergePackingSubmit(params)
					.then(res => {
						uni.hideLoading();
						if(res&&res.details.length>0){
							this.navigateToPage(res.details)
							this.clearInfo();
						}else {
							this.showMessage("提交成功未返回数据")
						}
					})
					.catch(err => {
						that.showMessage(err.message);
						uni.hideLoading();
					});
			},

			checkData() {
				var isCheck = this.itemList.find(r => r.checked == true)
				if (isCheck) {
					return true
				} else {
					return false
				}
			},

			setParams() {
				var checked = []
				var noChecked = []

				this.itemList.forEach(res => {
					if (res.checked) {
						checked.push(res)
					} else {
						noChecked.push(res)
					}
				})
				var mainLabelItem = checked[0].label;
				var mainItem = checked[0]

				let item = {
					tenantId: mainLabelItem.tenantId,
					activeDate: mainItem.activeDate,
					warehouseCode: mainItem.warehouseCode,
					remark: mainLabelItem.remark,
					extraProperties: {},
					worker: localStorage.userName_CN == "" ? localStorage.userName : localStorage.userName_CN,
					activeDate: mainItem.activeDate,
					number: "",
					itemCode: mainLabelItem.itemCode,
					itemName: mainItem.itemNameTemp,
					itemDesc1: mainLabelItem.itemDesc1,
					itemDesc2: mainLabelItem.itemDesc2,
					configuration: mainItem.configuration,
					packingCode: mainItem.packingCode,
					locationCode: mainItem.locationCode,
					containerCode: mainLabelItem.containerCode,
					lot: mainItem.lot,
					inventoryStatuses: mainItem.status,
					stdPackQty: mainLabelItem.stdPackQty,
					uom: mainLabelItem.uom,
					qty: mainItem.qty,
					labelType: mainLabelItem.labelType,
					fullBarcodeString: mainLabelItem.fullBarcodeString,
					supplierBatch: mainLabelItem.supplierBatch,
					arriveDate: mainLabelItem.arriveDate,
					produceDate: mainLabelItem.produceDate,
					expireDate: mainLabelItem.expireDate,
					recommendLocationCode: mainLabelItem.recommendLocationCode,
					locationErpCode: mainLabelItem.locationErpCode,
					supplierCode: mainLabelItem.supplierCode,
					rpNumber: mainLabelItem.rpNumber,
					purchaseInfo_PoNumber: mainLabelItem.poNumber,
					purchaseInfo_AsnNumber: mainLabelItem.asnNumber,
					arrivalNoticNumber: "",
					taskOrderNumber: "",
					receiptRecNumber: "",
					putOnShelfNumber: "",
					supplierName: mainLabelItem.supplierName,
					supplierSimpleName: mainLabelItem.supplierSimpleName,
					supplierItemCode: mainLabelItem.supplierItemCode,
					supplierItemName: mainLabelItem.supplierItemName,
					planArriveDate: mainLabelItem.planArriveDate,
					details: []
				}

				noChecked.forEach(r => {
					var submitItem = deepCopyData(r.label)
					submitItem.packingCode = r.packingCode
					submitItem.locationCode = r.locationCode
					submitItem.inventoryStatuses = r.status
					submitItem.stdPackQty = r.stdPackQty
					submitItem.qty=r.qty
					submitItem.lot=r.lot
					submitItem.recommendLocationCode = r.recommendLocationCode
					submitItem.locationErpCode = r.locationErpCode
					submitItem.purchaseInfo_PoNumber = submitItem.poNumber
					submitItem.purchaseInfo_AsnNumber = submitItem.asnNumber
					submitItem.arrivalNoticNumber = ""
					submitItem.taskOrderNumber = ""
					submitItem.receiptRecNumber = ""
					submitItem.putOnShelfNumber = ""
					submitItem.supplierName = ""
					submitItem.itemName=mainItem.itemNameTemp,
					item.details.push(submitItem);
				})

				return item;

			},
			
			navigateToPage(dataList){
				uni.navigateTo({
					url: './mergePackingResult?data='+encodeURIComponent(JSON.stringify(dataList))
				});
			},


			cancel() {
				let that = this;
				showConfirmMsg('是否要清空合箱数据?', confirm => {
					if (confirm) {
						that.clearInfo();
					}
				})
			},

			clearInfo() {
				this.itemList = [];
				this.labelInfo={}
			},

			afterCloseMessagg() {
				if (this.locationGotFocus) {
					this.$refs.location.gotFocus();
				}
			},

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

			checkeClick(value) {
				for (let i = 0; i < this.itemList.length; i++) {
					this.itemList[i].checked = false
				}

				for (let i = 0; i < this.itemList.length; i++) {
					if (this.itemList[i].packingCode == value) {
						if (this.itemList[i].checked == true) {
							this.itemList[i].checked = false
						} else {
							this.itemList[i].checked = true
						}
					}
				}
				this.$forceUpdate()
			},

		}
	};
</script>

<style scoped lang="scss">
	/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>