<template>
	<!-- <page-meta root-font-size="18px"></page-meta> -->
	<view class="page-wraper">
		<view class="page-main">
			<scroll-view scroll-y="true" class="">
				<view v-for="(toLocation, index) in detailSource">
					<com-issue-detail-card ref='comIssueDetailCard' :dataContent="toLocation"></com-issue-detail-card>
				</view>
			</scroll-view>
		</view>

		<div class="btn_bottom">
			<view class="" style="display: flex;flex-direction: row;">
				<view class="">
					<button class="btn_commit" hover-class="btn_commit_after" :disabled="disabledConfirm"
						@click="submit()">提交</button>
					<button class="btn_commit" hover-class="btn_commit_after" @click="resizeCollapse()">刷新</button>
				</view>
			</view>
		</div>
		<win-scan-button @goScan='openScanDetailPopup'></win-scan-button>
		<com-scan-issue-pack ref="comScanIssuePack" @closeScan='closeScan'></com-scan-issue-pack>
		<!-- <com-balance ref="balanceItems"></com-balance> -->
		<comMessage ref="comMessage"></comMessage>
	</view>
</template>

<script>
	import {
		takeIssueJob,
		cancelTakeIssueJob,
		getIssueJobDetail,
		getBalanceByUniquecode,
		issueJobSubmit
	} from '@/api/request.js';

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

	import itemQty from '@/mycomponents/item/itemQty.vue'
	import recommend from '@/mycomponents/recommend/recommend.vue'
	import recommendQtyEdit from '@/mycomponents/qty/recommendQtyEdit.vue'
	import jobDetailPopup from '@/mycomponents/job/jobDetailPopup.vue'
	import requiredLocation from '@/mycomponents/location/requiredLocation.vue'
	import comIssueRecommend from '@/pages/issue/coms/comIssueRecommend.vue'
	import winScanButton from '@/mycomponents/scan/winScanButton.vue'
	import comIssueDetailCard from '@/pages/issue/coms/comIssueDetailCard.vue'
	import comScanIssuePack from '@/pages/issue/coms/comScanIssuePack.vue'

	import pack from '@/mycomponents/balance/pack.vue'
	import location from '@/mycomponents/balance/location.vue'
	import batch from '@/mycomponents/balance/batch.vue'
	import recommendQty from '@/mycomponents/qty/recommendQty.vue'
	import compareQty from '@/mycomponents/qty/compareQty.vue'
	import balanceQty from '@/mycomponents/qty/balanceQty.vue'
	import qty from '@/mycomponents/qty/qty.vue'

	export default {
		name: 'issueDetail',
		components: {
			winScanButton,
			comIssueDetailCard,
			comScanIssuePack,
			itemQty,
			recommend,
			recommendQtyEdit,
			jobDetailPopup,
			requiredLocation,
			comIssueRecommend,
			pack,
			location,
			batch,
			recommendQty,
			compareQty,
			balanceQty,
			qty
		},
		data() {
			return {
				itemList: [],
				toLocation: null,
				currentLabel: null,
				reScanItem: null, //重复的箱码
				isFromEdit: false,
				locationDisabled: false,
				disabledConfirm: true,
				currentData: {},
				id: '',
				jobContent: {}, //任务内容
				subList: [], //接口返回的任务subList
				detailSource: [], //绑定在页面上的数据源
				detailOptions: [],
				scanOptions: []
			};
		},

		props: {

		},

		onLoad(option) {
			this.id = option.id;
			if (this.id != undefined) {
				//新建的任务自动接收
				if (option.status == "JOB_PENDING") {
					this.receive((callback => {
						this.received = true;
						this.getDetail();
					}));
				} else {
					this.getDetail();
				}
			}
		},

		onNavigationBarButtonTap(e) {
			if (e.index === 0) {
				goHome();
			}
		},

		//拦截返回按钮事件
		onBackPress(e) {
			//已经接收但是没提交任务
			if (this.received) {
				//取消承接任务	
				cancelTakeIssueJob(this.id).then(res => {}).catch(error => {
					this.showMessage(err);
				})
			}
		},

		watch: {
			locationTypes(newVal) {
				let value = newVal;
			},
		},
		mounted: function() {

		},

		methods: {
			//接收
			receive(callback) {
				if (this.id != null) {
					takeIssueJob(this.id).then(res => {
						callback();
					}).catch(error => {
						this.showErrorMessage(error)
					})
				}
			},

			getDetail() {
				var that = this;
				uni.showLoading({
					title: "加载中....",
					mask: true
				});
				getIssueJobDetail(that.id).then(res => {
					if (res.data[0].subList.length > 0) {
						that.jobContent = res.data[0];
						that.subList = res.data[0].subList;
						that.detailSource = that.getDataSource(that.subList)
						that.resizeCollapse();
						uni.hideLoading();
					} else {
						that.showMessage('列表数据为0');
					}
				}).catch(error => {
					uni.hideLoading()
					this.showErrorMessage(error)
				})
			},

			getDataSource(subList) {
				let list = [];
				let that = this;
				for (var i = 0; i < subList.length; i++) {
					let detail = subList[i];
					var location = list.find(r =>
						r.toLocationCode == detail.toLocationCode)
					if (location == undefined) {
						location = {
							toLocationCode: detail.toLocationCode,
							Items: []
						}
						list.push(location);
					}
					that.createDetailInfo(location, detail);
				}
				return list;
			},

			//树形结构:需求库位 -> 零件Items -> 库位 Locations-> 批次Batchs -> 记录Records
			createDetailInfo(location, detail) {
				let that = this;
				var item = location.Items.find(r =>
					r.itemCode == detail.itemCode)
				if (item == undefined) {
					item = that.createItemInfo(detail);
					location.Items.push(item)
				} else {
					item.qty += detail.qty
					//在零件下查找库位
					let location = item.Locations.find(r => r.fromLocationCode == detail.fromLocationCode);
					if (location == undefined) {
						location = that.createLocationInfo(detail);
						item.Locations.push(location);
					} else {
						//在库位下查找批次
						let batch = location.Batchs.find(r => r.batch == detail.Bacth);
						if (batch == undefined) {
							let batch = that.createBatchInfo(detail);
							location.Batchs.push(batch);
						}
					}
				}
			},

			createItemInfo(detail) {
				let item = {
					itemCode: detail.itemCode,
					itemName: detail.itemName,
					stdPackQty: detail.stdPackQty,
					stdPackUnit: detail.stdPackUnit,
					qty: detail.qty,
					uom: detail.uom,
					handleQty: 0,
					Locations: []
				}
				let location = this.createLocationInfo(detail);
				item.Locations.push(location);
				return item;
			},

			createLocationInfo(detail) {
				let location = {
					fromLocationCode: detail.fromLocationCode,
					qty: detail.qty,
					uom: detail.uom,
					handleQty: 0,
					Batchs: []
				}
				let batch = this.createBatchInfo(detail);
				location.Batchs.push(batch);
				return location;
			},

			createBatchInfo(detail) {
				let batch = {
					batch: detail.batch,
					qty: detail.qty,
					uom: detail.uom,
					handleQty: 0,
					// Records: []
				}
				return batch;
			},

			createRecordInfo(detail) {
				var record = {}
				detail.scaned = true;
				// let record = JSON.parse(JSON.stringify(detail));
				//克隆对象,深度克隆,防止双向绑定同一个变量
				Object.assign(record, detail)
				record.toLocationCode = this.toLocationCode;
				return record;
			},


			closeScan() {
				this.resizeCollapse();
			},

			resizeCollapse() {
				this.$nextTick(r => {
					this.$refs.comIssueDetailCard.forEach(r => {
						r.resizeCollapse();
					})

					// this.$refs.collapse.forEach(r => {
					// 	r.resize();
					// })

					// this.$refs.subCollapse.forEach(r => {
					// 	r.resize();
					// })


					// this.$refs.collapse.forEach(r => {
					// 	r.resize();
					// })

					// this.$refs.subCollapse[0].resize();
					// this.$refs.collapse[0].resize();



				});
			},


			reload() {
				let that = this;
				this.$nextTick(r => {
					that.$refs.collapse[0].resize();
				});
			},

			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, locationCode) {
				let that = this;

				let location = that.dataSource.find(r => r.toLocationCode == locationCode);

				if (locatio == undefined || locatio == null) {
					this.showErrorMessage('需求库位不存在', callback => {

					})
				} else {
					let item = location.Items.find(r => r.itemCode == result.label.itemCode);
					if (item == undefined || item == null) {
						this.showErrorMessage('未查找到零件【' + result.label.itemCode + '】的发料需求', callback => {

						})
					} else {
						let fromLocation = item.Locations.find(r => r.fromLocationCode == locationCode);
						let batch = fromLocation.Batchs.find(r => r.Bacth == result.label.batch)
						if (batch == undefined || batch == null) {
							if (jobContent.AllowModifyBach == 1) {
								//增加批次
								let bacth = this.createBatchInfo(result);
								item.Batchs.push(bacth);
							} else {
								this.showErrorMessage('未查找到零件【' + result.label.itemCode + '】对应的批次【' + result.label.batch +
									'】需求', callback => {

									})
							}

						} else {
							//在批次下增加记录
						}
					}
				}
			},

			afterRescan(confirm) {
				let that = this;
				if (confirm) {
					that.reScanItem.labelList.forEach((r, i) => {
						if (r.packingCode == that.currentLabel.packingCode) {
							that.reScanItem.labelList.splice(i, 1);
							return;
						}
					});
					that.getBalance();
				} else {
					this.scanPopupGetFocus();
				}
			},

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

			getToLocation(code) {
				if (code == '') {
					this.showMessage('目标库位不能为空');
					return;
				}
				uni.showLoading({
					title: "扫描中",
					mask: true
				});
				let that = this;
				locations(code).then(res => {
					if (res == null) {
						that.showMessage('目标库位【' + code + '】不存在');
						that.$refs.comToLocation.clearLocation();
					} else {
						if (res.type != 5) {
							this.showMessage('目标库位必须是【线边库】')
						} else {
							this.toLocation = res;
						}
					}
					uni.hideLoading();
				}).catch(err => {
					that.toLocationCode = ''
					that.showMessage(err.message);
					uni.hideLoading();
				})
			},

			clearLocation() {
				this.toLocation = null;
			},

			clearCustomerAddress() {
				this.customerAddressArray = [];
				this.toLocation = null;
				this.customerAddress = null;
				this.customerAddressCode = ''
			},

			submit() {
				//3.如果是按批次先进先出发料提交时如果扫描的箱码不是先进的批次,则报错
				//:请扫描XXX批次,改批次满足先进先出规则。否则可以直接提交
				var isOutIn = getApp().globalData.feed_configList.filter(
					res => {
						if (res.name == 'feed_isOutIn') {
							return res;
						}
					});

				this.dataContent.itemCodeList.forEach(res => {
					if (res.handleQty > res.recommendQty) {
						this.$refs.modal.showConfirmMessageModal('实际数量大于需求数量,是否提交?', confirm => {
							if (confirm) {
								//提交
								uni.showToast({
									title: "提交"
								})
							}
						})
					} else {
						uni.showToast({
							title: "扫描的数量" + res.handleQty + "]小于推荐数量[" + res.recommendQty + "]"
						})
					}
				})
			},

			updateCommitBtn() {
				var isHandleQtyNoRecommedQty = getApp().globalData.feed_configList.filter(
					res => {
						if (res.name == 'feed_isHandleQtyNoRecommedQty') {
							return res;
						}
					});
				//实际发料数量是否允许与需求量不同
				//允许
				if (isHandleQtyNoRecommedQty[0].value) {
					//实际发料数量与需求量允许不一致

					//有扫描数量可以提交,按钮可点击
					var handleQty = 0;
					this.dataContent.itemCodeList.forEach(res => {
						handleQty = res.handleQty + handleQty;
					})

					if (handleQty > 0) {
						this.disabledConfirm = false;
						//如果实际数量(扫描数量)大于需求数量,提示是否提交

					} else {
						this.disabledConfirm = true;
					}



				} else {
					//实际发料数量与需求量不允许不一致,按钮不可用
					//必须相等才可以用

					this.dataContent.itemCodeList.forEach(res => {
						if (res.handleQty == res.recommendQty) {
							this.disabledConfirm = false;
						} else {
							this.disabledConfirm = true;
						}
					})

					// if(handleQty==recommendQty){
					// 	this.disabledConfirm =false;
					// }else {
					// 	this.disabledConfirm =true;
					// }
					//实际数量大于等于才可以提交,按钮可以点击


				}
			},


			cancel() {
				let that = this;
				showConfirmMsg('是否要清空已扫描的零件和目标库位信息?', confirm => {
					if (confirm) {
						that.clearInfo();
					}
				})
			},

			clearInfo() {
				this.dataContent.itemCodeList.forEach(res => {
					if (res.recommendList != null) {
						res.recommendList.forEach(res1 => {
							if (res1.locationCodeList != null) {
								res1.locationCodeList.forEach(res2 => {
									if (res2.packingCodeList != null) {
										res2.packingCodeList.forEach(res3 => {
											res3.itemCode = "";
											res3.qty = 0;
										})
									}
								})
							}

						})
					}

				})
			},

			qtyChanged(value, item, label) {
				if (value <= 0) {
					// label.qty = 1;
					// this.showMessage('发料数量不能小于或等于0')
					// this.$forceUpdate();
				}
				this.calcScanCount(item);
			},
			openAddScanDetailPopup() {
				this.isFromEdit = false;
				this.locationDisabled = true;
				this.openIssuePopup();
			},

			scanPopupGetFocus() {
				this.$refs.scanPopup.getfocus();
			},


			showMessage(message) {
				this.$refs.comMessage.showMessage(message, res => {
					if (res) {
						this.afterCloseMessage()
					}
				});
			},
			showErrorMessage(message) {
				this.$refs.comMessage.showErrorMessage(message, res => {
					if (res) {
						this.afterCloseMessage()
					}
				});
			},

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

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

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

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

			closeScanMessage() {
				this.scanPopupGetFocus();
			},
			confirm(data) {
				this.dataContent = data;
			},
			issueDetailEdit(data) {
				this.isFromEdit = true;
				// this.dataContent = data;
				this.$forceUpdate();
			},
			confirmResult(result) {
				this.dataContent = result;
				this.$forceUpdate();
			},
			closeScanPopup() {
				this.updateCommitBtn();
			},
			openScanDetailPopup() {
				var datacontent = {}
				//克隆对象,深度克隆,防止双向绑定同一个变量
				// Object.assign(datacontent, this.detailSource);
				this.$refs.comScanIssuePack.openScanPopup(this.detailSource, this.jobContent);
			},
		}
	};
</script>

<style scoped lang="scss">
	.uni-numbox__value {
		width: 40px;
	}

	button[disabled] {
		background-color: #3C9CFF;
		color: #fff;
		opacity: 0.7;
	}


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