<template>
	<view class="page-wraper">
		<view class="page-header">
			<view class="header-view">
				<view class="header_job_top">
					<job-top :dataContent="jobContent" :isShowPlanNumber='true'></job-top>
				</view>
				<work-station :workshopCode="jobContent.workShopCode"
					:productionLineCode="jobContent.detailProductionLineCode"
					:workStationCode="jobContent.detailWorkStationCode"
					:rawLocationCode="jobContent.detailToLocationCode"
					:itemGroup="jobContent.itemGroup" :isShowItemGroup='false'>
				</work-station>
			</view>
		</view>
		<view class="page-main">
			<scroll-view scroll-y="true" class="page-main-scroll">
				<view v-for="(toLocation, index) in detailSource.subList">
					<comIssueDetailCardBatch ref='comIssueDetailCardBatch' :dataContent="toLocation" :settingParam="jobContent"
						@updateData='updateData'
						>
					</comIssueDetailCardBatch>
					<view class="split_line"></view>
				</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="">
				</view>
				<view class=" uni-flex uni-row">
					<button class="btn_single_commit" hover-class="btn_commit_after" @click="submit()">提交</button>
				</view>
			</view>
		</view>

		<win-scan-button @goScan='openScanPopup'></win-scan-button>
		<winScanPackAndLocationNoShow :balanceFromInventoryStatuses="false" :toLocationCode="jobToLocationCode"
			ref="scanPopup" @getResult='getScanResult' :noShowBalanceMessage="false" :title="'补给品标签'" headerType="HEQ"></winScanPackAndLocationNoShow>
		<balance-select ref="balanceSelect" ></balance-select>
		<comMessage ref="comMessage"></comMessage>
	</view>
</template>

<script>
	import {
		takeIssueJob,
		cancleTakeIssueJob,
		getIssueJobDetail,
		issueJobEopSubmit,
		issueCheck,
		getBalanceByFilter
	} from '@/api/request2.js';

	import {
		goHome,
		navigateBack,
		getRemoveOption,
		getCurrDateTime,
		getDirectoryItemArray,
		getPackingNumberAndBatch,
		deepCopyData,
		compareAsc,
	} from '@/common/basic.js';

	import {
		getManagementPrecisions
	} from '@/common/balance.js';
	import {
		calc
	} from '@/common/calc.js';
	
	
	import {
		getDataSource,
		getTreeDataSource,
		calcTreeHandleQty,
		getScanCount,
		getThreeDataSource
	} from '@/common/detail.js';
	
	import {
		calcHandleQtyAdd
	} from '@/common/record.js';
	
	
	import {
		getBusinessType
	} from '@/common/record.js';

	import jobDetailPopup from '@/mycomponents/job/jobDetailPopup.vue'
	import comIssueDetailCardBatch from '@/pages/issueSupplies/coms/comIssueDetailCardBatch.vue'
	import winScanButton from '@/mycomponents/scan/winScanButton.vue'
	import jobTop from '@/mycomponents/job/jobTop.vue'
	import workStation from '@/mycomponents/workStation/workStation.vue'
	import balanceSelect from '@/mycomponents/balance/balanceSelect.vue'
	import winScanPackAndLocationNoShow from "@/mycomponents/scan/winScanPackAndLocationNoShow.vue"

	export default {
		name: 'issueSuppliesDetail',
		components: {
			jobDetailPopup,
			winScanButton,
			jobTop,
			workStation,
			balanceSelect,
			comIssueDetailCardBatch,
			winScanPackAndLocationNoShow
		},
		data() {
			return {
				id: '',
				jobContent: {}, //任务内容
				subList: [], //接口返回的任务subList
				detailSource:{}, //绑定在页面上的数据源
				detailOptions: [],
				scanOptions: [],
				jobStatus: "",
				scanMessage: '',
				managementList: [],
				managementType: "",
				fromLocationCode:'',
				str1:''
			};
		},

		props: {

		},

		onLoad(option) {
			uni.setNavigationBarTitle({
				title: option.title + '详情'
			});
			this.id = option.id;
			this.scanMessage = option.scanMessage || '';
			if (this.id != undefined) {
				//新建的任务自动接收
				if (option.status == "1") {
					this.receive((callback => {
						this.getDetail();
					}));
				} else {
					this.getDetail();
				}
			}
		},

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

		//拦截返回按钮事件
		onBackPress(e) {
			//已经接收但是没提交任务
			if (e.from === 'backbutton') {
				if (this.jobStatus == "2") {
					//取消承接任务	
					cancleTakeIssueJob(this.id).then(res => {
						uni.navigateBack();
					}).catch(error => {
						uni.navigateBack();
					})
				} else {
					uni.navigateBack();
				}

				return true;
			}

		},

		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 => {
					uni.hideLoading();
					if (res.data == null) {
						that.showMessage('未获取到详情');
					} else {
						if (res.data.subList.length > 0) {
							// res.data.allowModifyLocation = 'FALSE'
							that.jobContent = res.data;
							that.jobStatus = res.data.status
							that.subList = res.data.subList;
							that.detailSource = res.data
							that.jobContent.detailToLocationCode = res.data.subList[0].toLocationCode
							that.toLocationCode= res.data.subList[0].toLocationCode
							that.fromLocationCode = that.subList[0].fromLocationCode
						} else {
							that.showMessage('列表数据为0');
						}
					}
				}).catch(error => {
					uni.hideLoading()
					this.showErrorMessage(error)
				})
			},

			closeScan() {
			},
			
			getScanResult(result) {
				console.log(333,result)
				let label = result.label;
				var qty = label.qty;
				var itemCode = label.itemCode;
				var fromLocationCode = label.location;
				console.log( this.detailSource)
				console.log( fromLocationCode)
			
				var detail = this.detailSource.subList.find(r => r.itemCode == itemCode &&r.fromLocationCode ==  fromLocationCode);
				if (detail == undefined) {
					this.showErrorMessage("物料【" + itemCode + "】来源库位【" + fromLocationCode + "】不在列表中")
				} else {
					if(detail.scaned == true){
						this.showErrorMessage("物料【" + itemCode + "】已经扫描")
						return
					}
					if(detail.qty>result.balance.qty){
						this.showErrorMessage("物料【" + itemCode + "】库存不足")
						return
					}
					detail.scaned = true
				}
				this.continueScan()
			},
			
			//继续扫描
			continueScan() {
				this.scanCount = getScanCount(this.subList);
				if (this.scanCount == this.subList.length) {
					this.closeScanPopup();
				} else {
					this.scanPopupGetFocus();
				}
			},
			scanPopupGetFocus (){
				if (this.$refs.scanPopup ) {
					this.$refs.scanPopup.packGetFocus();
				}
			},

			submitJob() {
				uni.showLoading({
					title: "提交中....",
					mask: true
				});
				// var params = this.setParams()
				issueJobEopSubmit(this.detailSource).then(res => {
					uni.hideLoading()
					if (res.data) {
						this.showCommitSuccessMessage("提交成功\n生成发料记录\n" + res.data)
					} else {
						this.showErrorMessage("提交失败[" + res.msg + "]")
					}
				}).catch(error => {
					uni.hideLoading()
					this.showErrorMessage(error)
				})
			},

			setParams() {
				var subList = []
				var creator = this.$store.state.user.id
				this.detailSource.forEach(toLocationCode => {
					let arr = []
					toLocationCode.subList.forEach(record=>{
						if(record.scaned){
							let obj = {...toLocationCode,...record}
								obj.recordList = []
								delete obj.balance
								delete obj.subList
								let obj1 ={}
								obj1.supplierCode = record.supplierCode;
								obj1.batch = record.batch;
								obj1.copyContent =record.copyContent;
								obj1.fromInventoryStatus =record.fromInventoryStatus;
								obj1.fromLocationCode =record.fromLocationCode;
								obj1.handleQty =record.handleQty;
								obj1.inventoryStatus =record.fromInventoryStatus;
								obj1.packQty =record.packQty;
								obj1.packUnit =record.packUnit;
								obj1.packingNumber =record.packingNumber;
								obj1.qty =record.qty;
								obj1.scaned =record.scaned;
								obj1.toLocationCode =record.toLocationCode;
								obj1.fromPackingNumber =record.packingNumber;
								obj1.fromBatch = record.batch;
								obj1.toBatch  = record.batch;
								obj1.toInventoryStatus   = record.inventoryStatus;
								obj1.toPackingNumber  ="";
								obj1.packingNumber  = "";
								
								let single_price = record.balance.singlePrice == null ? 0 : record.balance.singlePrice;
								
								obj1.singlePrice = single_price;
								obj1.amount = single_price *record.qty;
								obj.recordList.push(obj1)
								subList.push(obj)
						}
					})
				})
					
				this.jobContent.subList = subList
				this.jobContent.creator = creator;
				return this.jobContent;
			},

			cancel() {
				let that = this;
				this.$refs.comMessage.showQuestionMessage('是否要清空已扫描的物料和目标库位信息?', res => {
					if (res) {
						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;
										})
									}
								})
							}

						})
					}

				})
			},

			updateData(record) {
				this.detailSource.forEach(item=>{
						item.handleQty = 0
					item.subList.forEach(cur=>{
					item.handleQty = calc.add(cur.handleQty,item.handleQty)
					})
				})
			},

			afterScan() {
				// this.autoCommit()
			},
		submit(){
			//防止重复点击
			this.$throttle(this.autoCommit, 2000, this)()
		},
			async autoCommit(){
				const array = this.detailSource.subList.filter(detail=>detail.scaned)
				if(array.length < this.detailSource.subList.length){
					this.showErrorMessage('任务明细为全部完成，无法提交')
					return
				}
				let index = 0
				await this.recursion(index)
				if(this.str1){
					console.log(this.str1)
				}
				
			},
			async recursion(index){
				let filters = []
				filters.push({
					column: "itemCode",
					action: "==",
					value: this.detailSource.subList[index].itemCode
				})
				filters.push({
					column: "locationCode",
					action: "==",
					value: this.detailSource.subList[index].fromLocationCode
				})
				var params = {
					filters: filters,
					pageNo: 1,
					pageSize: 100,
				}
				await getBalanceByFilter(params).then(res => {
					const balance =  res.data.list[0]
					if(this.detailSource.subList[index].qty>balance.qty){
						this.str1 += "物料【" + itemCode + "】、"
					}
					index++;
					if(index <  this.detailSource.subList.length){
						this.recursion(index)
					}else{
						if(this.str1){
							this.str1 = this.str1.substring(0,this.str1.length - 1)
							this.showErrorMessage(`${str1}库存不足`)
						}else{
							this.submitJob()
						}
					}
				}).catch(err => {
					this.showErrorMessage(err.message);
				})
			},
			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();
			},

			showCommitSuccessMessage(hint) {
				this.$refs.comMessage.showSuccessMessage(hint, res => {
					navigateBack(1)
				})
			},

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

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


			closeScanMessage() {
				this.scanPopupGetFocus();
			},
			confirm(data) {
				this.dataContent = data;
			},
			confirmResult(result) {
				this.dataContent = result;
				this.$forceUpdate();
			},
			openScanPopup() {
				this.$refs.scanPopup.openScanPopupForJob(this.jobContent);
			},

			closeScanPopup() {
				this.$refs.scanPopup.closeScanPopup()
			},
			confirmFromLocation(fromLocationCodeParams){
				this.fromLocationCode = fromLocationCodeParams
			}
		}
	};
</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>