<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;'>
									<com-balance-item :dataContent="label" style='margin-left: 10px;'>
									</com-balance-item>
									<view class="choose_marked">
										<image src="@/static/image_marked.svg"></image>
									</view>
								</uni-swipe-action-item>
							</uni-swipe-action>
						</view>
					</com-collapse-item>
				</view>
			</uni-collapse>
		</scroll-view>

		<view class="new_bot_box" v-if="itemList.length>0">
			<uni-collapse>
				<uni-collapse-item :show-animation="true" title="扫描客户代码" :open="true">
					<view class="content">
						<uni-easyinput ref='scanInput' v-model="customerCode" @confirm="getCustomerAddressByCode"
							@clear="clearCustomerAddress" style='font-size: 18px;padding: 10rpx 20rpx;'>
						</uni-easyinput>
						<uni-data-picker v-if='customerAddressArray.length>0'
							style="padding: 20rpx; background-color:#fff;" class='uni-data-picker' placeholder="客户地址"
							popup-title="客户地址(客户库位)" v-model="customerAddressCode" :localdata="customerAddressArray"
							@change="customerAddressChanged()">
						</uni-data-picker>
					</view>
				</uni-collapse-item>
			</uni-collapse>
			<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>
		</view>
		<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 {
		locationsAsync,
		getBalancesByFilter,
		rawDeliver,
		getCustomerAddressBycustomerCodeAsync,
	} 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'

	export default {
		name: 'deliverRaw',
		components: {
			winBlankView,
			comBalanceItem,
			comMessage,
			winScanButton,
			winScanByPack,
			comBalance,
			winCollapseLocation,
			comCollapseItem
		},
		data() {
			return {
				options: [],
				itemList: [],
				toLocation: null,
				customerCode: '',
				customerAddress: null,
				customerAddressCode: '',
				customerAddressArray: []
			};
		},
		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 = result.data.code;

				let itemInfo = that.itemList.find(r => {
					return r.itemCode == result.data.itemCode
				})
				if (itemInfo == undefined) {
					that.getBalance(result);
				} else {
					let data = itemInfo.labelList.find(r => {
						return r.packingCode == code
					})
					if (data == undefined) {
						that.getBalance(result);
					} else {
						// showConfirmMsg('箱码【' + code + '】已经存在,是否要重新扫描?', confirm => {
						// 	if (confirm) {
						// 		itemInfo.labelList.forEach((r, i) => {
						// 			if (r.packingCode == code) {
						// 				itemInfo.labelList.splice(i, 1);
						// 				return;
						// 			}
						// 		});
						// 		that.getBalance(result);
						// 	} else {
						// 		this.scanPopupGetFocus();
						// 	}
						// });
					}
				}
			},

			getBalance(result) {
				uni.showLoading({
					title: '加载中',
					mask: true
				})
				let that = this;
				//按照零件号和箱码去查询库存
				let params = {
					pageSize: 100,
					pageIndex: 1,
					locationTypes: [2],
					itemCode: result.data.itemCode,
					packingCode: result.data.packingCode,
					lot: result.data.lot,
				};
				getBalancesByFilter(params)
					.then(res => {
						try {
							if (res.totalCount === 0) {
								this.showScanMessage('箱码【' + result.data.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);
						}

						uni.hideLoading();
					})
					.catch(err => {
						this.showScanMessage(err.message);
						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);
				itemInfo.scanQty += balanceItem.qty;
				this.scanPopupGetFocus();
			},

			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.toContainerCode = this.currentLabel.containerCode;
				label.toPackingCode = this.currentLabel.packingCode;
				label.toLot = this.currentLabel.lot;
				label.toWarehouseCode = localStorage.warehouseCode;
				label.toStatus = balanceItem.status;
				// item.supplierBatch = balanceItem.supplierBatch;
				// item.arriveDate = balanceItem.arriveDate;
				// item.produceDate = balanceItem.produceDate;
				// item.expireDate = balanceItem.expireDate;

				item.labelList.unshift(label)
			},

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

			async getCustomerAddressByCode() {
				uni.showLoading({
					title: '扫描中...',
					mask: true
				})
				let customerAddressRes = await getCustomerAddressBycustomerCodeAsync(this.customerCode)
				if (customerAddressRes.length == 0) {
					this.showMessage('未查找到客户代码为【' + this.customerCode + '】的客户地址');
					this.customerCode = ''
				} else {

					customerAddressRes.forEach(r => {
						r.text = r.code + '(' + r.locationCode + ')';
						r.value = r.code;
					})
					this.customerAddressArray = customerAddressRes;
					this.customerAddress = customerAddressRes[0];
					this.customerAddressCode = customerAddressRes[0].code;
					await this.getToLocation(this.customerAddress.locationCode);
				}

				uni.hideLoading();
			},

			async getToLocation(locationCode) {
				let locationRes = await locationsAsync(locationCode);
				if (locationRes != '' || locationRes != null) {
					this.toLocation = locationRes;
				} else {
					this.toLocation = locationRes;
					this.showMessage('未查找到库位【' + locationCode + '】');
				}
				// if (locationRes.error != undefined) {
				// 	this.showMessage(locationRes.error.message);
				// } else {
				// 	this.toLocation = locationRes;
				// }
			},

			async customerAddressChanged(val) {
				let that = this;
				console.log('customerAddressCode', that.customerAddressCode);
				that.customerAddress = that.customerAddressArray.find(r => r.code == that.customerAddressCode);
				if (that.customerAddress != undefined) {
					let locationCode = that.customerAddress.locationCode;
					console.log('locationCode', locationCode);
					await that.getToLocation(that.customerAddress.locationCode);
				}
			},
			clearCustomerAddress() {
				this.customerAddressArray = [];
				this.toLocation = null;
				this.customerAddress = null;
				this.customerAddressCode = ''
			},

			submit() {
				let that = this;
				if (that.itemList.length === 0) {
					this.showMessage('请扫描要发料的零件');
					return;
				}

				if (that.customerAddress == null && that.toLocation == null) {
					this.showMessage('请扫描客户地址代码');
					return;
				}

				uni.showLoading({
					title: "提交中....",
					mask: true
				});
				let item = {
					customerCode: that.customerAddress.customerCode,
					customerAddressCode: that.customerAddress.customerAddressCode,
					deliverTime: getISODateTime(),
					deliverRequestType: 3,
					toLocationCode: that.toLocation.code,
					toLocationArea: that.toLocation.areaCode,
					toLocationGroup: that.toLocation.locationGroupCode,
					toLocationErpCode: that.toLocation.erpLocationCode,
					jobNumber: '',
					deliverPlanNumber: '',
					deliverRequestNumber: '',
					worker: localStorage.userName,
					warehouseCode: localStorage.warehouseCode,
					company: localStorage.company,
					details: []
				}

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

				let params = JSON.stringify(item);
				console.log('params', params);
				rawDeliver(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 = [];
				this.customerCode = '';
				that.clearCustomerAddress();
			},
						
			openScanPopup() {
				this.$refs.scanPopup.openScanPopup()
			},
			
			scanPopupGetFocus() {
				this.$refs.scanPopup.getfocus();
			},
			
			showMessage(message) {
				this.$refs.comMessage.showMessage(message);
			},

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

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

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

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

			closeCommitMessage() {
				this.openScanPopup();
			}
		}
	};
</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>
