<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,'itemCode',index)">
								<com-balance-item :dataContent="item"></com-balance-item>
							</uni-swipe-action-item>
						</uni-swipe-action>
					</view>
				</view>
			</view>
			<view v-if="itemList.length>0" class="uni-flex uni-row uni-center" style="align-items: center;">
				<view class="" style="margin-left: 20rpx; margin-right: 20rpx; font-size: 35rpx; font-weight: bold;">
					拆出箱数 :
				</view>

				<com-number-box :inPutDisabled ="true" ref="comNumberBoxRef" v-model="splitQty" :max="999999" :min="0" style='width: 100px;'
					@change="qtyChanged($event)">
				</com-number-box>
			</view>
			<view v-if="itemList.length>0"
				style="background-color: #000; height: 1rpx;margin-top: 15rpx;margin-bottom: 15rpx;">

			</view>
			<view class="">

				<view class="" v-for="(splitItem,index) in splitList">
					<view style="-webkit-flex: 1;flex: 1;">
						<view class="">
							<uni-swipe-action>
								<uni-swipe-action-item :right-options="options" :auto-close="false"
									@click="swipeClick($event,'split',index)">
									<view class="uni-flex uni-row">
										<view class=""
											style="font-size: 35rpx;font-weight: bold; margin-top: 30rpx; margin-left: 0rpx;">
											({{index+1}})
										</view>
										<view class="detail-list">
											<comSplit :dataContent="splitItem"></comSplit>
										</view>

									</view>


								</uni-swipe-action-item>
							</uni-swipe-action>
						</view>
					</view>
				</view>

			</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,
		splitPackingSubmit
	} from '@/api/index.js';

	import {
		showConfirmMsg,
		goHome,
		getRemoveOption,
		scanSuccessAudio,
		scanFailedAudio,
		timeInMilliseconds,
		secondsToDateTime,
		deepCopyData,
		getInventoryStatusValueList
	} 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
				},
				isClearPackCode: false, //清除箱码
				isClearContainerCode: false, //清除托码
				isClearLot: false, //清除批次,
				locationErpCode: '',
				toLocationErpCode: '',
				locationGotFocus: false,
				splitQty: 0,
				splitList: [],
				labelInfo:{}
			};
		},

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

		},
		
		onLoad() {
			
		},


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

			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 = [];
										that.splitList = [];
										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,5],
					packingCode: packingCode
				};
				getBalancesByFilter(params)
					.then(res => {
						try {
							if (res.totalCount === 0) {
								scanFailedAudio()
								this.showMessage('箱码【' + packingCode + '】在原料库、半成品库、成品库、线边库未查询到库存信息');
							} else if (res.totalCount === 1) {
								this.labelInfo=label
								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) {
				this.clearInfo()
				let item = this.createItem(balanceItem);
				item.label = label
				
				item.statusName=""
				if (this.itemList.length == 0) {
					this.locationErpCode = balanceItem.locationErpCode;
					item.itemNameTemp =item.itemName
					item.itemName =item.itemDesc2
					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.this.labelInfo);
			},

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

			submit() {
				let that = this;
				if (that.itemList.length === 0) {
					this.showMessage('请选择要提交的零件');
					return;
				}
				var isHaveQty=true
				for(var i=0;i<this.splitList.length;i++){
					if( Number(this.splitList[i].qty)==0){
						isHaveQty=false
					}
				}
				
				if(!isHaveQty){
					this.showMessage('数量必须大于0');
					return;
				}
				
				var totalsplitQty = 0;
				this.splitList.forEach(res => {
					totalsplitQty += Number(res.qty)
				})
				if(totalsplitQty==0){
					this.showMessage('请输入拆箱数量');
					return;
				}else {
					if(totalsplitQty>=that.itemList[0].qty){
						this.showMessage('拆箱数量必须小于库存数量');
						return;
					}
				}
				
				
				uni.showLoading({
					title: "提交中....",
					mask: true
				});
				
				var mainLabelItem = this.itemList[0].label;
				var mainItem = this.itemList[0]
				let item = {
					warehouseCode: mainItem.warehouseCode,
					activeDate: mainItem.activeDate,
					remark: mainLabelItem.remark,
					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: mainLabelItem.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_AsnNumber: mainLabelItem.asnNumber,
					purchaseInfo_PoNumber: mainLabelItem.poNumber,
					arrivalNoticNumber: "",
					taskOrderNumber: "",
					receiptRecNumber: "",
					putOnShelfNumber: "",
					supplierName: mainLabelItem.supplierName,
					supplierSimpleName: mainLabelItem.supplierSimpleName,
					supplierItemCode: mainLabelItem.supplierItemCode,
					supplierItemName: mainLabelItem.supplierItemName,
					planArriveDate: mainLabelItem.planArriveDate,
					details: []
				}

				this.splitList.forEach(r => {
					item.details.push(deepCopyData(r));
				})
				item.details.forEach(res => {
					res.produceDate = res.produceDate ? secondsToDateTime(res.produceDate) : res
						.produceDate;
					res.planArriveDate = res.planArriveDate ? secondsToDateTime(res.planArriveDate) :
						"",
						res.expireDate = res.expireDate ? secondsToDateTime(res.expireDate) : "",
						res.activeDate = res.activeDate ? secondsToDateTime(res.activeDate) : "",
						res.creationTime = res.creationTime ? secondsToDateTime(res.creationTime) : "",
						res.lastModificationTime = res.lastModificationTime ? secondsToDateTime(res
							.lastModificationTime) : ""
					res.inventoryStatuses=getInventoryStatusValueList(res.statusName)
				})

				let params = JSON.stringify(item);
				splitPackingSubmit(params)
					.then(res => {
						uni.hideLoading();
						if(res&&res.details.length>0){
							this.navigateToPage(res.details)
							this.clearInfo();
						}else {
							this.showMessage("提交成功未返回数据")
						}
					})
					.catch(err => {
						uni.hideLoading();
						that.showMessage(err.message);
					});
			},
			
			navigateToPage(dataList){
				uni.navigateTo({
					url: './splitPackingResult?data='+encodeURIComponent(JSON.stringify(dataList))
				});
			},

			checkQty(balanceQty) {
				var isPassed = false
				//拆箱的总数不能大于库存数量
				var totalsplitQty = 0;
				this.splitList.forEach(res => {
					totalsplitQty += res.qty
				})

				if (totalsplitQty > balanceQty) {
					isPassed = false
				} else {
					isPassed = true
				}
				return isPassed;

			},

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

			clearInfo() {
				this.itemList = [];
				this.splitList = []
				this.splitQty = 0
			},

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

			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();
			},
			qtyChanged(value) {
				if(value<this.splitList.length){
					this.splitList.splice(0,1)
				}
				
				var size = value - this.splitList.length;
				var labelInfo = this.itemList[0].label
				var itemInfo = this.itemList[0]
				for (var i = 0; i < size; i++) {
					var item = {
						number: "",
						packingCode: "",
						warehouseCode: itemInfo.warehouseCode,
						itemCode: labelInfo.itemCode,
						itemName: labelInfo.itemName,
						itemDesc1: labelInfo.itemDesc1,
						itemDesc2: labelInfo.itemDesc2,
						locationCode: itemInfo.locationCode,
						locationErpCode: itemInfo.locationErpCode,
						recommendLocationCode: itemInfo.recommendLocationCode,
						lot: itemInfo.lot,
						inventoryStatuses: itemInfo.status,
						stdPackQty: labelInfo.stdPackQty,
						uom: labelInfo.uom,
						qty: 0,
						labelType: labelInfo.labelType,
						concurrencyStamp: labelInfo.concurrencyStamp,
						configuration: labelInfo.configuration,
						rpNumber: labelInfo.rpNumber,
						purchaseInfo_AsnNumber: labelInfo.asnNumber,
						purchaseInfo_PoNumber: labelInfo.poNumber,
						arrivalNoticNumber: "",
						receiptRecNumber: "",
						putOnShelfNumber: "",
						taskOrderNumber: "",
						produceDate: labelInfo.produceDate ? timeInMilliseconds(labelInfo.produceDate) : labelInfo
							.produceDate,
						planArriveDate: labelInfo.planArriveDate ? timeInMilliseconds(labelInfo.planArriveDate) : "",
						expireDate: labelInfo.expireDate ? timeInMilliseconds(labelInfo.expireDate) : "",
						supplierCode: labelInfo.supplierCode,
						supplierName: labelInfo.supplierName,
						supplierSimpleName: labelInfo.supplierSimpleName,
						supplierItemCode: labelInfo.supplierItemCode,
						supplierItemName: labelInfo.supplierItemName,
						activeDate: labelInfo.activeDate ? timeInMilliseconds(labelInfo.activeDate) : "",
						creationTime: labelInfo.creationTime ? timeInMilliseconds(labelInfo.creationTime) : "",
						lastModificationTime: labelInfo.lastModificationTime ? timeInMilliseconds(labelInfo
							.lastModificationTime) : "",
						remark: "",
						worker: localStorage.userName_CN == "" ? localStorage.userName : localStorage.userName_CN,
						fullBarcodeString: labelInfo.fullBarcodeString
					}

					this.splitList.push(item)
				}

			}

		}
	};
</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>