<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)">
								<com-balance-item :dataContent="item"></com-balance-item>
							</uni-swipe-action-item>
						</uni-swipe-action>
					</view>
				</view>
			</view>
		</scroll-view>

		<div class="new_bot_box" v-show="itemList.length>0">
			<win-collapse-location ref="location" @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-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,
		inventoryTransfer
	} from '@/api/index.js';

	import {
		showConfirmMsg,
		goHome,
		getRemoveOption
	} 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'

	export default {
		name: 'comtransfer',
		components: {
			winBlankView,
			comBalanceItem,
			comMessage,
			winScanButton,
			winScanByPack,
			comBalance,
			winCollapseLocation
		},
		data() {
			return {
				options: [],
				itemList: [],
				fromLocationCode: '',
				toLocationCode: '',
				scrollTop: 0,
				old: {
					scrollTop: 0
				},
				inventoryStatus: -1,
				inventoryStatusArray: [],
				isClearPackCode: false, //清除箱码
				isClearContainerCode: false, //清除托码
				isClearLot: false, //清除批次,
				locationErpCode: '',
				toLocationErpCode: '',
				locationGotFocus: false
			};
		},
		props: {
			// locationTypes: {
			// 	type: [Array, String, Number],
			// 	value: ''
			// },
			byLocation: {
				type: Boolean,
				value: false
			},
			transferType: {
				type: String,
				value: 'Transfer_Inside' //Transfer_Inside:储位内 Transfer_Area:储位间
			}
		},

		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 datas = that.itemList.filter(r => {
					return r.packingCode == code
				})

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

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

			pushItem(balanceItem) {
				let item = this.createItem(balanceItem);
				if (this.itemList.length == 0) {
					this.locationErpCode = balanceItem.locationErpCode;
					this.itemList.unshift(item);
				} else {
					if (this.transferType == 'Transfer_Inside') //储位内移库
					{
						if (this.locationErpCode != balanceItem.locationErpCode) {
							this.showMessage('箱码【' + balanceItem.packingCode + '】的ERP储位【' + balanceItem.locationErpCode +
								'】与默认的ERP储位[' + this
								.locationErpCode +
								'】不是同一ERP储位,不可以进行储位内移库');
						} else {
							this.itemList.unshift(item);
						}
					} else if (this.transferType == 'Transfer_Area') //储位调拨
					{
						this.itemList.unshift(item);
					}
				}
			},

			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.toLocationCode = 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);
			},

			qtyInput(value, item) {
				if (value == '') {
					setTimeout(() => {
						item.qty = 0;
					}, 10)
				} else {
					let qtyValue = Number(value);
					if (qtyValue < 0) {
						this.showMessage('数量不能小于0');
						setTimeout(() => {
							item.qty = 0;
						}, 10)
					} else if (value > item.defaultQty) {
						this.showMessage('数量不能大于【' + item.defaultQty + '】');
						setTimeout(() => {
							item.qty = item.defaultQty;
						}, 10)
					}
				}
			},

			getToLocation(code) {
				if (code == '') {
					this.showMessage('目标库位不能为空');
					return;
				}
				uni.showLoading({
					title: "扫描中",
					mask: true
				});
				let that = this;
				locations(code).then(res => {
					if (res == null) {
						that.toLocationCode = ''
						that.showMessage('目标库位【' + code + '】不存在');
						this.$refs.location.clearLocation()
						this.locationGotFocus = true;
					} else {
						if (that.transferType == 'Transfer_Inside') //储位内调拨
						{
							if (that.locationErpCode != res.erpLocationCode) {
								that.showMessage('目标库位的ERP储位【' + res.erpLocationCode + '】与【' + this
									.locationErpCode +
									'】不是同一ERP储位,请重新扫描目标库位');
								that.toLocationCode = ''
								that.$refs.location.clearLocation();
								this.locationGotFocus = true;
							} else {
								that.toLocationCode = code;
								that.toLocationErpCode = res.erpLocationCode;
							}

						} else //储位调拨
						{
							let items = that.itemList.filter(r => {
								return r.fromLocationErpCode == res.erpLocationCode;
							})
							if (items.length > 0) {
								let msg = '';
								for (var i = 0; i < items.length; i++) {
									let r = items[i];
									msg += (i == 0 ? '' : ',') + r.fromPackingCode
								}
								that.showMessage('【' + msg + '】所在ERP储位与目标库位的ERP储位【' + res
									.erpLocationCode + '】相同,请重新扫描目标库位');
								that.toLocationCode = ''
								that.$refs.location.clearLocation();
								this.locationGotFocus = true;
							} else {
								that.toLocationCode = res.code;
								that.toLocationErpCode = res.erpLocationCode;
							}
						}
					}
					uni.hideLoading();
				}).catch(err => {
					that.toLocationCode = ''
					this.locationGotFocus = true;
					that.showMessage(err.message);
					uni.hideLoading();
				})
			},

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

			submit() {
				let that = this;
				if (that.itemList.length === 0) {
					this.showMessage('请选择要提交的零件');
					return;
				}
				if (that.toLocationCode === '') {
					this.showMessage('请扫描目标库位');
					return;
				}
				uni.showLoading({
					title: "提交中....",
					mask: true
				});
				let item = {
					worker: localStorage.userName_CN ==""?localStorage.userName:localStorage.userName_CN,
					warehouseCode: localStorage.warehouseCode,
					jobNumber: "",
					supplierCode: "",
					company: localStorage.company,
					number: "",
					type: this.transferType,
					details: []
				}

				that.itemList.forEach(r => {
					r.toLocationCode = that.toLocationCode;
					r.toLocationErpCode = this.toLocationErpCode

					r.worker = localStorage.userName_CN ==""?localStorage.userName:localStorage.userName_CN
					item.details.push(r);
				})


				let params = JSON.stringify(item);
				console.log('params', params);
				inventoryTransfer(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.toLocationCode = '';
				that.inventoryStatus = -1;
			},

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