<template>
	<view class="page-wraper">
		<view class="">
			<com-blank-view @goScan='showFromLocationPopup' v-if="detailSource.length==0"></com-blank-view>
		</view>
		<view class="page-wraper" v-if="detailSource.length>0">
			<u-line />
			<view class="page-main">
				<scroll-view scroll-y="true" class="page-main-scroll">
					<view class="detail-list" v-for="(item, index) in detailSource" :key="item.id">
						<view class="">
							<com-move-record :dataContent="item" :index="index" @removeData="removeData"
								:isShowStatus="isShowStatus" @updateData="updateData" @removePack='removePack'>
							</com-move-record>
						</view>
						<u-line />
					</view>
				</scroll-view>
			</view>
			
			<view class="page-footer">
				<view class="uni-flex u-col-center space-between padding_10"
					style="background-color:ghostwhite; width: 100%; ">
					<view class="">
						<requiredLocation title="目标库位" :locationCode="toLocationCode" @getLocation='getToLocationCode'
							:locationTypeList="toLocationTypeArray"></requiredLocation>
					</view>
					<view class=" uni-flex uni-row">
						<button class="btn_single_commit" hover-class="btn_commit_after" @click="commit">提交</button>
					</view>
				</view>
			</view>
			<win-scan-button @goScan='openScanPopup'></win-scan-button>
		</view>
		<win-scan-pack-and-location ref="scanPopup" @getResult='getScanResult' :title="'箱码'"></win-scan-pack-and-location>
		<win-scan-location ref="scanFromLocationCode" title="来源库位" @getLocation='getLocation'
			:locationTypeList="fromLocationTypeArray"></win-scan-location>
		<com-message ref="comMessage"></com-message>
	</view>
</template>

<script>
	import comEmptyView from '@/mycomponents/common/comEmptyView.vue'
	import winScanButton from '@/mycomponents/scan/winScanButton.vue'
	import requiredLocation from '@/mycomponents/location/requiredLocation.vue'
	import comMoveRecord from '@/pages/inventoryMove/coms/comMoveRecord.vue'
	import comBlankView from '@/mycomponents/common/comBlankView.vue'
	import winScanLocation from "@/mycomponents/scan/winScanLocation.vue"
	import winScanPackAndLocation from "@/mycomponents/scan/winScanPackAndLocation.vue"
	import comMessage from '@/mycomponents/common/comMessage.vue'
	import {
		getBalanceByUniquecode,
	} from '@/api/request.js';

	import {
		getDirectoryItemArray
	} from '@/common/directory.js';
	
	import {
		getBusinessType,
		createItemInfo,
		createDetailInfo,
		calcHandleQty
	} from '@/common/record.js';

	export default {
		components: {
			comEmptyView,
			winScanButton,
			requiredLocation,
			comMoveRecord,
			comBlankView,
			winScanLocation,
			winScanPackAndLocation,
			comMessage
		},
		props: {
			// fromInventoryStatus: {
			// 	type: String,
			// 	default: ""
			// },
			// toInventoryStatus: {
			// 	type: String,
			// 	default: ""
			// },
			isShowStatus: {
				type: Boolean,
				default: false
			},
			businessTypeCode: {
				type: String,
				default: "Move"
			} //业务类型
		},
		data() {
			return {
				fromLocationCode: "",
				fromLocationInfo: {},
				fromLocationTypeArray: [],
				toLocationCode: "",
				toLocationInfo: {},
				toLocationTypeArray: [],
				toInventoryStatus: "",
				businessType: {}, //业务类型
				detailSource: [], //绑定在页面上的数据源
			}
		},

		mounted() {
			getBusinessType(this.businessTypeCode, res => {
				if (res.success) {
					this.businessType = res.businessType;
					this.fromlocationTypeList = res.fromlocationTypeList;
					this.tolocationTypeList = res.tolocationTypeList;
					this.showFromLocationPopup();
				} else {
					this.$refs.comMessage.showBreakMessage(res.message );
				}
			});
			this.updateTitle();
		},

		onLoad() {

		},

		methods: {
			updateTitle() {
				var name =""
				if(this.businessTypeCode=="Move"){
					name = "库存转移记录";
				}else if(this.businessTypeCode=="HoldToOkRecord"){
					name = "隔离转合格记录";
					this.toInventoryStatus  = "OK"
				}else if(this.businessTypeCode=="HoldToScrapRecord"){
					name = "隔离转报废记录";
					this.toInventoryStatus  = "SCRAP"
				}else if(this.businessTypeCode=="OkToHoldRecord"){
					name = "合格转隔离记录";
					this.toInventoryStatus  ="HOLD"
				}else if(this.businessTypeCode=="OktoScrapRecord"){
					name = "合格转报废记录";
					this.toInventoryStatus  ="SCRAP"
				}else if(this.businessTypeCode=="ScrapToHoldRecord"){
					name = "报废转隔离记录";
					this.toInventoryStatus  ="HOLD"
				}
				uni.setNavigationBarTitle({
					title: name
				})
			},
			openScanPopup() {
				if (this.fromLocationCode == "") {
					this.showFromLocationPopup();
					return
				}
				this.$refs.scanPopup.openScanPopupForType(this.fromLocationCode, this.businessType);
			},
			showFromLocationPopup() {
				this.$nextTick(() => {
					this.$refs.scanFromLocationCode.openScanPopup();
				})

			},
			getLocation(location) {
				this.getfromLocationCode(location)
			},
			getfromLocationCode(location) {
				this.fromLocationInfo = location;
				this.fromLocationCode = location.code;
				this.openScanPopup();
			},
			getToLocationCode(location, code) {
				this.toLocationCode = code;
			},
			getScanResult(result) {
				this.getDataSource(result)
			},

			getDataSource(result) {
				var balance = result.balance;
				var pack = result.package;
				var item = this.detailSource.find(res => {
					if (res.itemCode == balance.itemCode) {
						return res
					}
				})
				if (item == undefined) {
					var itemp = createItemInfo(balance,pack);
					let newDetail = createDetailInfo(balance, pack); //
					itemp.subList.push(newDetail);
					this.detailSource.push(itemp)
				} else {
					var detail = item.subList.find(r => {
						if (r.packingNumber == balance.packingNumber &&
							r.batch == balance.batch &&
							r.locationCode == balance.locationCode &&
							r.inventoryStatus == balance.inventoryStatus &&
							r.scaned == true) {
							return r;
						}
					})

					if (detail == undefined) {
						let newDetail = createDetailInfo(balance, pack);
						item.subList.push(newDetail);
					} else {
						this.showErrorMessage(balance.packingNumber + "已经在列表中")
					}
				}
				calcHandleQty(this.detailSource);

			},

			createItemInfo(balance, pack) {
				let item = {
					itemCode: pack.itemCode,
					itemName: pack.itemName,
					stdPackQty: pack.stdPackQty,
					stdPackUnit: pack.stdPackUnit,
					qty: balance.qty,
					handleQty: 0,
					uom: pack.uom,
					subList: []
				}
				return item;
			},

			createDetailInfo(data, pack) {
				data.scaned = true;
				data.toInventoryStatus = this.toInventoryStatus == "" ? data.inventoryStatus : this.toInventoryStatus;
				let detail = {};
				Object.assign(detail, data)
				detail.balanceQty = detail.qty
				detail.package = pack
				return detail;
			},

			calcHandleQty() {
				for (let item of this.detailSource) {
					item.qty = 0;
					for (let detail of item.subList) {
						if (detail != undefined) {
							item.qty += detail.qty
						}
					}
				}
				this.$forceUpdate();
			},

			showErrorMessage(message) {
				this.$refs.comMessage.showErrorMessage(message, res => {
					if (res) {

					}
				});
			},
			updateData() {
				calcHandleQty(this.detailSource);
				for (var i = 0; i < this.detailSource.length; i++) {
					let item = this.detailSource[i];
					if (item.qty == 0) {
						this.detailSource.splice(i, 1)
					}
				}
			},

			removePack() {
				for (var i = 0; i < this.detailSource.length; i++) {
					var item = this.detailSource[i];
					if (item.subList.length == 0) {
						this.detailSource.splice(i, 1)
					}
				}
				this.updateData();
			},


			removeData(item) {
				for (let i = 0; i < this.detailSource.length; i++) {
					if (this.detailSource[i].itemCode == item.itemCode) {
						this.detailSource.splice(i, 1)
					}
				}
			},
			commit() {
				uni.showLoading({
					title: "提交中....",
					mask: true
				});
			
				if (this.detailSource.length > 0 && this.detailSource[0].subList.length > 0) {
					console.log("提交参数", JSON.stringify(params));
			
					//直接创建记录
					//采购退货直接出库，不用查询管理模式
					var params = this.setRecordParams(true)
					console.log("提交参数", JSON.stringify(params));
			
					purchaseReturnRecordSubmit(params).then(res => {
						uni.hideLoading()
						if (res.data) {
							this.showCommitSuccessMessage("提交成功<br>生成采购退货记录" + res.data)
						} else {
							this.showErrorMessage("提交失败" + res.msg)
						}
					}).catch(error => {
						uni.hideLoading()
						this.showErrorMessage(error)
					})
				} else {
					this.showErrorMessage("没有要提交的数据")
				}
			},
		}
	}
</script>

<style>
</style>
