<template>
	<page-meta root-font-size="18px"></page-meta>
	<view class="">
		<win-blank-view @goScan='openScanPopup' v-if="fromLocationCode==''"></win-blank-view>
			<view class="" style="  background-color: #5A7CF3; color: #fff; border-radius: 10rpx; margin: 15rpx;" v-if="fromLocationCode!=''">
				<view class="" style="">
					<view class="uni-flex  top_lines_info" style="flex-direction: column;">
						<view class="" style="padding: 20rpx;">
							来源库位:
							<text class="text_bold" >{{fromLocationCode}}</text>
						</view>
						<!-- <view class=""  style="padding: 10rpx;">
							扫描数量:
							<text class="text_bold"> {{allCount}}</text>
						</view> -->
					</view>
				</view>
			</view>
		<scroll-view scroll-y class="scroll-detail" style="margin-top: 10rpx;padding-bottom:100px"  >
			<view class="detail-list " v-for="(item, index) in showList" :key="index">
				<view class="detail-content">
					<view class="" style="">
						<view class="uni-flex uni-row u-col-center">
							<view class="" style="margin-top: 20rpx; margin-left: 10rpx; font-weight: bold;">
								({{index+1}}).
							</view>
							<comItemCode :itemData="item"></comItemCode>
						</view>

						<uni-table border stripe style="">
							<!-- <uni-tr>
								<uni-td align="center">物品代码</uni-td>
								<uni-td>{{item.itemCode}}</uni-td>
							</uni-tr> -->
							<uni-tr>
								<uni-td align="center">单位</uni-td>
								<uni-td>{{item.uom}}</uni-td>
							</uni-tr>
							<uni-tr>
								<uni-td align="center">标包数</uni-td>
								<uni-td>{{item.stdPackQty}}</uni-td>
							</uni-tr>

							<uni-tr>
								<uni-td align="center">数量</uni-td>
								<uni-td>
									<view class="uni-flex uni-row">
										<view class="uni-flex uni-row space-between" style="width: 100%;">
											<view class="">
												<com-number-box :ref="'comNumberBox_'+index" v-model="item.qty"
													:max="99999" :min="0" @change="qtyChanged($event,item,index)">
												</com-number-box>
											</view>

											<view class="">
												<button type="primary" size="mini" style="margin-left: 30rpx;"
													@click="remove(item,index)">移除</button>
											</view>

										</view>
									</view>
								</uni-td>
							</uni-tr>
						</uni-table>
					</view>
				</view>
			</view>

		</scroll-view>
		<uni-load-more :status="loadingType" v-if="showList.length>0" />
		<div class="new_bot_box" v-show="showList.length>0">
			<win-collapse-location scanTitle='扫描目标库位' ref='comCollapseLocation' @getLocationCode='getDefaultToLocation'
				@clear='clearDefaultLocation'>
			</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="fromLocationCode!=''"></win-scan-button>
		<winScanByProductCode ref="scanPackPopup" title="单件码" @getScanResult='getScanResult'></winScanByProductCode>
		<win-scan-by-code ref="scanFromLocationPopup" title="来源库位" @getScanCode='scanFromLocation'></win-scan-by-code>
		<com-message ref="comMessage" @afterCloseScanMessage='closeScanMessage' @afterRescanMessage='afterRescan'
			@afterCloseCommitMessage='closeCommitMessage'>
		</com-message>
	</view>
</template>

<script>
	import {
		locations,
		getBalancesByFilterAsync,
		getWipListAsync,
		thirdLocationRequest,
	} from '@/api/index.js';

	import {
		showConfirmMsg,
		goHome,
		getRemoveOption,
		getISODateTime
	} from '@/common/basic.js';

	import winBlankView from '@/mycomponents/wincom/winBlankView.vue'
	import comBaseItem from '@/mycomponents/comItem/comBaseItem.vue'
	import winScanButton from '@/mycomponents/wincom/winScanButton.vue'
	import winScanByPack from '@/mycomponents/wincom/winScanByPack.vue'
	import winScanByProductCode from '@/mycomponents/wincom/winScanByProductCode.vue'

	import winScanByCode from '@/mycomponents/wincom/winScanByCode.vue'
	import comScanSemiPutaway from '@/mycomponents/scan/comScanSemiPutaway.vue'
	import comMessage from '@/mycomponents/common/comMessage.vue'
	import winCollapseLocation from '@/mycomponents/wincom/winCollapseLocation.vue'
	import SemiCollapseItem from '@/mycomponents/common/SemiCollapseItem.vue'
	import comItemCode from '@/mycomponents/comItem/comItemCode.vue'
	import comNumberBox from '@/mycomponents/common/comNumberBox.vue';


	export default {
		name: 'thirdLocationRequest',
		components: {
			winBlankView,
			comBaseItem,
			comMessage,
			winScanButton,
			winScanByPack,
			winScanByCode,
			comScanSemiPutaway,
			winCollapseLocation,
			SemiCollapseItem,
			winScanByProductCode,
			comItemCode,
			comNumberBox
		},
		data() {
			return {
				options: [],
				currentItem: {},
				showList: [],
				toLocationCode: "",
				toLocationArea:"",
				fromLocationCode: "",
				fromLocationArea:"",
				allCount: 0,
				allDataList: [],
				loadingType: "",
				pageNo: 0,
				pageSize: 5,
				scrollTop: 60,
				old: {
					scrollTop: 0
				},
			};
		},
		onLoad() {
			this.updateTitle()
		},
		onPullDownRefresh() {
			this.pageNo = 1;
			this.showList=[]
			this.loadingType = "";
			this.showList = this.getDataPage(this.pageNo, this.pageSize)
			uni.stopPullDownRefresh()
		},
		onReachBottom() {
			console.log("底部")
			if (this.loadingType == 'nomore') {
				console.log("没有更多了")
				return;
			}
			this.pageNo++;
			var list = this.getDataPage(this.pageNo, this.pageSize)
			if (list.length > 0) {
				console.log("加载更多了")
				this.showList = this.showList.concat(list)
			} else {
				//没有更多了
				this.loadingType = "nomore";
			}
		},


		onNavigationBarButtonTap(e) {
			if (e.index === 0) {
				goHome();
			} else if (e.index === 1) {
				window.location.reload();
			}
		},
		mounted: function() {
			this.openScanPopup();
		},

		methods: {
			
			//扫描源库位
			scanFromLocation(code) {
				let that = this;
				if (code == '') return;
				uni.showLoading({
					title: '扫描中...',
					mask: true
				});
				locations(code).then(res => {
					uni.hideLoading();
					if(res){
						if(res.type == 3||res.type == 4){
							this.fromLocationCode = res.code;
							this.fromLocationArea = res.areaCode;
							this.openPackLabel();
							this.closeScanFromLocationPopup();
						}else {
							this.showMessage('扫描的库位【' + code + '】不是【半成品库】或【成品库位】');
						}
					}else {
						this.showMessage('未查询到库位【' + code + '】');
					}
					
				}).catch(err => {
					this.fromLocationCode = "";
					this.fromLocationArea = "";
					uni.hideLoading();
					that.showMessage(err.message);
				});
			},
			
			getDataPage(pageNo, pageSize) {
				//计算总页数
				var totalPages = Math.ceil(this.allCount / pageSize);
				//当前页起始索引
				const start = (pageNo - 1) * pageSize;
				const end = start + pageSize; //当前页结束索引
				return this.allDataList.slice(start, end)

			},
			qtyChanged(value, item, index) {
				if (value <= 0) {
					this.showMessage('退货数量必须大于0')
					item.handledQty = item.qty
					this.$refs['comNumberBox_' + index][0].setValue(item.handledQty);
				}
			},
			remove(item, index) {
				showConfirmMsg("是否移除当前" + item.itemCode, res => {
					if (res) {
						this.allDataList.splice(index, 1);
						this.allCount = this.allDataList.length;
						this.updateTitle()
						this.$forceUpdate()
					}
				})
			},

			async getScanResult(result) {
				var balanceParam={
					pageIndex: 1,
					pageSize: 100,
					itemCode:result.itemCode,
					locationCode:this.fromLocationCode
					
				}
				let balanceRes = await getBalancesByFilterAsync(balanceParam);
				
				if(balanceRes.totalCount==0){
					this.showMessage("单件码【" + result.itemCode + "】在库位【"+this.fromLocationCode+"】没有库存")
					return;
				}
				
				var filterItem = this.allDataList.filter(res => {
					if (res.itemCode == result.itemCode) {
						return res;
					}
				})
				if (filterItem.length > 0) {
					this.showMessage("单件码【" + filterItem[0].itemCode + "】已经扫描")
					return;
				}

				var item = {
					itemCode: result.itemCode,
					itemName: result.itemName,
					itemDesc1: result.itemDesc1,
					stdPackQty: result.stdPackQty,
					uom: result.uom,
					qty: result.stdPackQty

				}
				this.allDataList.unshift(item)
				this.allCount = this.allDataList.length;
				this.pageNo = 1;
				this.showList = []
				this.loadingType = "";
				this.showList = this.getDataPage(this.pageNo, this.pageSize)
				this.updateTitle()
				this.$forceUpdate();
			},


			//扫描默认目标库位
			getDefaultToLocation(locationCode) {
				uni.showLoading({
					title: "扫描中",
					mask: true
				});
				locations(locationCode).then(res => {
					uni.hideLoading();
					if (res) {
						this.toLocationCode = res.code
						this.toLocationArea =res.areaCode;
					} else {
						this.showMessage('目标库位【' + locationCode + '】不存在');
					}

				}).catch(err => {
					uni.hideLoading();
					this.toLocationCode = ""
					this.toLocationArea =""
					this.showMessage(err.message);

				})
			},

			clearDefaultLocation() {
				this.toLocationCode = ""
				this.toLocationArea =""
			},

			submit() {
				if (this.allDataList.length === 0) {
					this.showMessage('请扫描单件码');
					return;
				}

				if (this.toLocationCode == "") {
					this.showMessage('请扫描目标库位');
					return;
				}
				var checkQtyItem =this.checkQty()
				if(checkQtyItem!=undefined){
					this.showMessage("【"+checkQtyItem.itemCode+'】数量为0,退货数量必须大于0');
					return;
				}

				uni.showLoading({
					title: "提交中....",
					mask: true
				});

				let params = this.setSubmitParam();
				console.log("提交"+JSON.stringify(params)  )
				thirdLocationRequest(params)
					.then(res => {
						uni.hideLoading();
						this.showCommitSuccess();
						this.clearInfo();
						
					})
					.catch(err => {
						uni.hideLoading();
						this.showMessage(err.message);
						
					});
			},
			
			checkQty(){
				var isCheck =true;
				var result =undefined
				for (let item of this.allDataList) {
					if(item.qty==0){
						result =item
						break
					}
				}
				return result;
			},

			setSubmitParam() {
				let item = {
					worker: localStorage.userName_CN == "" ? localStorage.userName : localStorage.userName_CN,
					activeDate:getISODateTime(),
					 useOnTheWayLocation: true,
					type: "Transfer_Warehouse",
					details: []
				}
				this.allDataList.forEach(res => {
					var detail = {
						itemCode: res.itemCode,
						itemName: res.itemName,
						itemDesc1: res.itemDesc1,
						uom: res.uom,
						qty: res.qty,
						stdPackQty: res.stdPackQty,
						toLocationCode:this.toLocationCode,
						toLocationArea:this.toLocationArea,
						fromLocationCode:this.fromLocationCode,
						fromLocationArea:this.fromLocationArea,
						 useOnTheWayLocation: true
					}
					item.details.push(detail)
				})
				
				return item;

			},


			getSubmitParam() {
				let that = this;
				let item = {
					number: "",
					worker: localStorage.userName_CN == "" ? localStorage.userName : localStorage.userName_CN,
					putawayType: 2,
					details: []
				}

				that.showList.forEach(i => {
					let balanceItem = i.balanceItem;
					i.labelList.forEach(l => {
						let detail = {};
						detail.itemCode = balanceItem.itemCode;
						detail.itemName = balanceItem.itemName;
						detail.itemDesc1 = balanceItem.itemDesc1;
						detail.itemDesc2 = balanceItem.itemDesc2;
						detail.uom = l.uom;
						detail.qty = l.qty;
						detail.stdPackQty = balanceItem.stdPackQty;

						detail.fromPackingCode = balanceItem.packingCode;
						detail.toPackingCode = l.packingCode;
						detail.fromLot = balanceItem.lot;
						detail.toLot = l.lot;


						detail.toLocationCode = l.toLocationCode ?? that.defaultToLocation.code;
						detail.toLocationGroup = l.toLocationGroup ?? that.defaultToLocation
							.locationGroupCode;
						detail.toLocationArea = l.toLocationArea ?? that.defaultToLocation.areaCode;
						detail.toLocationErpCode = l.toLocationErpCode ?? that.defaultToLocation
							.erpLocationCode;

						detail.fromStatus = balanceItem.status;
						detail.toStatus = l.status;

						detail.fromWarehouseCode = localStorage.warehouseCode;
						detail.toWarehouseCode = localStorage.warehouseCode;

						detail.supplierBatch = balanceItem.supplierBatch;
						detail.arriveDate = balanceItem.arriveDate;
						detail.produceDate = balanceItem.produceDate;
						detail.expireDate = balanceItem.expireDate;
						//===========================================
						detail.recommendPackingCode = balanceItem.packingCode;
						detail.recommendSupplierBatch = l.supplierBatch;
						detail.recommendArriveDate = l.arriveDate;
						detail.recommendProduceDate = l.produceDate;
						detail.recommendExpireDate = l.expireDate;
						detail.recommendLot = balanceItem.lot;;
						detail.recommendToLocationCode = l.toLocationCode ?? that.defaultToLocation.code;
						detail.recommendToLocationArea = l.toLocationArea ?? that.defaultToLocation
							.areaCode;
						detail.recommendToLocationGroup = l.toLocationGroup ?? that.defaultToLocation
							.locationGroupCode;
						detail.recommendToLocationErpCode = l.toLocationErpCode ?? that.defaultToLocation
							.erpLocationCode;
						detail.recommendToWarehouseCode = localStorage.warehouseCode;
						detail.recommendQty = balanceItem.qty;


						detail.handledContainerCode = l.containerCode;
						detail.handledPackingCode = l.packingCode;
						detail.handledSupplierBatch = l.supplierBatch;
						detail.handledArriveDate = l.arriveDate;
						detail.handledProduceDate = l.produceDate;
						detail.handledExpireDate = l.expireDate;
						detail.handledLot = l.lot;
						detail.handledToLocationCode = l.toLocationCode ?? that.defaultToLocation.code;
						detail.handledToLocationArea = l.toLocationArea ?? that.defaultToLocation.areaCode;
						detail.handledToLocationGroup = l.toLocationGroup ?? that.defaultToLocation
							.locationGroupCode;
						detail.handledToLocationErpCode = l.toLocationErpCode ?? that.defaultToLocation
							.erpLocationCode;
						detail.handledToWarehouseCode = localStorage.warehouseCode;
						detail.handledQty = l.qty;
						item.details.push(detail);
					});
				})
				return item;
			},

			cancel() {
				let that = this;
				showConfirmMsg('是否要清空已扫描信息?', confirm => {
					if (confirm) {
						that.clearInfo();
					}
				})
			},

			clearInfo() {
				this.allDataList = [];
				this.showList = [];
				this.toLocationCode = "";
				this.toLocationCodeArea = "";
				this.fromLocationCode= ""
				this.fromLocationCodeArea= ""
				this.allCount = 0;
				this.loadingType = ""
				this.pageNo = 0
				this.updateTitle()
				this.$refs.comCollapseLocation.clearLocation();
				
			},
			updateTitle(){
				if(this.allCount == 0){
					uni.setNavigationBarTitle({
						title: "三方库发货"
					})
				}else {
					uni.setNavigationBarTitle({
						title: "三方库发货"+"("+this.allCount+")"
					})
				}
				
			},

			openScanPopup() {
				this.scanPackPopup();
			},

			scanPopupGetFocus() {
				this.$refs.scanPackPopup.getfocus();
			},
			showMessage(message) {
				this.$refs.comMessage.showMessage(message);
			},
			showCommitSuccess() {
				this.$refs.comMessage.showCommitSuccess();
			},
			showScanMessage(message) {
				this.$refs.comMessage.showScanMessage(message);
			},
			closeCommitMessage() {
				// this.openScanPopup();
			},
			closeScanMessage() {
				this.scanPopupGetFocus();
			},

			openPackLabel() {
				this.$refs.scanPackPopup.openScanPopup()
			},
			openScanFromLocationPopup() {
				this.$refs.scanFromLocationPopup.openScanPopup()
			},
			
			closeScanFromLocationPopup() {
				this.$refs.scanFromLocationPopup.closeScanPopup();
			},
			scanPackPopup(){
				if (this.fromLocationCode == "") { //扫描来源库位
					this.openScanFromLocationPopup();
				} else { //扫描箱标签
					this.openPackLabel();
				}
			}

		}
	};
</script>

<style scoped lang="scss">
</style>