<template>
	<view class="page">
		<StickyNavBar>
			<NavBar title="生产退料"></NavBar>
			<view class="headerTitle">
				<view class="">
					<view class="items">退料申请:{{goodsList[0]&&goodsList[0].applyNo}}</view>
					<view class="items">{{goodsList[0]&&goodsList[0].workstationCode}}/{{goodsList[0]&&goodsList[0].workstationName}}</view>
					<view class="items">计划日期:{{goodsList[0]&&goodsList[0].startTime}}</view>
				</view>
				<view class="checkedCase">
					<checkbox-group @change="checkedChange">
						<checkbox value="r1" :checked="checkedBox" />是否结案
					</checkbox-group>
				</view>
			</view>
			<FactorySelect v-model="warehouseCode" />

			<view class="btn">
				<uni-easyinput prefixIcon="search" class="topSearch" v-model="nlpla" focus placeholder="请扫描库位"></uni-easyinput>
				<uni-easyinput
					prefixIcon="search"
					:disabled="isDisabled"
					v-model="wxparams"
					:focus="isFocus"
					placeholder="请扫描产品包装条码/外箱码"
					@input="handleInputPlnr"
				></uni-easyinput>
			</view>
			<view class="total">
				<view class="left">物料明细</view>
				<view class="right">
					物料数量：
					<!-- <text class="blue">{{ totalNum }}</text>
					<text class="line">/</text> -->
					<text class="">{{ goodsList.length }}</text>
				</view>
			</view>
		</StickyNavBar>
		<ContentLoadingMore class="cardbox" :list='goodsList'>
			<view class="cardContent" v-for="(item, index) in goodsList" :key="index">
				<scanningList :item='item' :list='list'/>
			</view>
		</ContentLoadingMore>
		<BottomBtn :btnArr="btnArr" @getBtnHandle="getBtnHandle"></BottomBtn>
	</view>
</template>

<script>
import StickyNavBar from '@/components/StickyNavBar/index.vue';
import ContentLoadingMore from '@/components/ContentLoadingMore/index.vue';
import BottomBtn from '@/components/BottomBtn/index.vue';
import scanningList from "./scanningList.vue"
export default {
	components: {
		StickyNavBar,
		ContentLoadingMore,
		BottomBtn,
		scanningList
	},
	data() {
		return {
			checkedBox: false,
			r1:'',
			// totalNum: 0,
			number: 0,
			show: true,
			nlpla: '',
			wxparams: '',
			warehouseCode: '',
			btnArr: [
				{
					style: '',
					type: 'warning',
					text: '返回',
					way: 'goBack'
				},
				{
					style: '',
					type: 'primary',
					text: '提交',
					way: 'goSubmit'
				}
			],
			goodsList: [],
			isFocus: true,
			isDisabled: false,
			OrderNum: '',
			list: []
		};
	},
	computed:{
		totalNum(){
			let num = 0 
			let i=null,j=null
			const data = JSON.parse(JSON.stringify(this.list))
			const result = data.filter((item, index, self) => {
				return self.findIndex(t => t.itemCode === item.itemCode) === index;
			});
			for(i = 0; i < this.goodsList.length; i++){
				if(this.goodsList[i].itemCode === result[i].itemCode && result[i].quantityIssued){
					num++
				}
			}
			return num || 0
		},
	},
	onLoad(option) {
		if(option && option.order){
			this.OrderNum = option.order
			this.getOrder(option.order)
		}
	},
	watch: {
	  
	},
	created() {
	},
	methods: {
		reset(){
			setTimeout(() => {
				this.wxparams = '';
				this.isFocus = true;
				this.isDisabled = false;
			}, 1000);
		},
		getOrder(applyNo) {
			this.$u.api.mesApi
				.pdaMaterialReturn({
					pageNum:1,
					pageSize:10,
					applyNo
				})
				.then((res) => {
					if (res && res.code - 200 === 0) {
						this.list = res.rows
						const data = res.rows
						const result = data.filter((item, index, self) => {
						    return self.findIndex(t => t.sapItemCode === item.sapItemCode) === index;
						});
						this.goodsList = [...result]
					} else {
						this.$u.toast(res.msg);
					}
					this.loading = false;
				});
		},
		checkedChange(){
			this.checkedBox = !this.checkedBox
		},
		getBtnHandle(row) {
			this[row.way]();
		},
		goBack() {
			console.log('进来')
			uni.navigateBack();
		},
		goSubmit() {
			if (this.list.length === 0) {
				return;
			}
			let arr = this.list.filter(ele=>ele.quantityIssued)
			// "windCase": null,是否结案   Y是  N否
			arr.forEach((ele,index) => {
				ele.windCase = this.checkedBox ? 'Y': 'N'
				ele.AUFNR = ele.workorderCode
				ele.ERFMG = ele.quantityIssued
				ele.MTSNR = ele.applyNo
				ele.ZEILE = index+1
				ele.RSNUM = ele.requirementNumber || '10'
				ele.RSPOS = ele.requirementProjectNumber || '2'
				// 添加仓库别
				ele.UMLGO = this.warehouseCode
			})
			const params = {
				'zencode': 'A009',
				'item': arr
			}
			this.$u.api.sapApi
				.sapProiss(params)
				.then((res) => {
					this.loading = false;
					if(!Array.isArray(res)){
						return
					}
					if (res.every((item) => item.TYPE === 'S')) {
						// this.$u.toast('提交成功');
						this.handleMes(arr,res[0].MESSAGE_V1)
					}
					const foundObject = res.find(item => item.TYPE === 'E');
					if(foundObject && foundObject.MESSAGE){
						this.$u.toast(foundObject.MESSAGE);
					}
				});
		},
		handleMes(arr,num){
			arr.forEach(ele => {
				ele.batchCode = ele.CHARG
				ele.backNum = ele.quantityIssued
				ele.issueCode = num
				ele.issueType = ele.materialType
			});
			this.$u.api.mesApi
				.pdaMaterialReturnNum(arr)
				.then((res) => {
					this.loading = false;
					console.log(res);
					if(res && res.code == 200){
						this.$u.toast('提交成功');
						setTimeout(() => {
							this.goBack()
						}, 1000);
					}else{
						this.$u.toast(res.msg);
					}
				});
		},
		handleInputPlnr(e) {
			e && this.getPlnr(e);
		},
		getPlnr(plnr) {
			this.isDisabled = true;
			this.isFocus = false
			if(!this.nlpla){
				this.$u.toast('请先扫描仓位');
				this.reset()
				return
			}
			this.$u.api.sapApi
				.sapBlpl({
					plnr,
					ztype: '003'
				})
				.then((res) => {
					if (res && res.MSG[0].TYPE === 'S') {
						if (this.list.some((item) => item.PLNR === plnr)) {
							this.reset()
							this.$u.toast('已经存在当前条码');
							return
						}
						this.factorial(res,plnr,0)
						this.reset()
					} else {
						this.$u.toast(res.MSG[0].MESSAGE);
						this.reset()
					}
					this.loading = false;
				});
		},
		factorial(res,plnr,idx,num=0) {
			// 找出符合条件的数组长度
			this.list.forEach(ele => {
				console.log(`output->`,ele.sapItemCode,res.BLPL[0].MATNR)
				console.log(`output->thi`,this.list.filter(item => item.sapItemCode == res.BLPL[0].MATNR))
			});
			const count = this.list.filter(item => item.sapItemCode == res.BLPL[0].MATNR).length
			if(!count){
				this.$u.toast('没有匹配到对应物料');
				return
			}
			for (let m = 0; m < this.list.length; m++) {
				if(this.list[m].sapItemCode == res.BLPL[0].MATNR){
					// 递归的方法
					if(idx){
						if(this.list[idx]){
							if(num > this.list[idx].applyNum){
								this.$set(this.list,idx,{...this.list[idx],quantityIssued : this.list[idx].applyNum,charg: res.BLPL[0].CHARG,... res.BLPL[0],NLPLA: this.nlpla})
								this.factorial(res,plnr,idx+1,num-this.list[idx].applyNum)
							}else{
								this.$set(this.list,idx,{...this.list[idx],quantityIssued : num,charg: res.BLPL[0].CHARG,... res.BLPL[0],NLPLA: this.nlpla})
								this.factorial(res,plnr,idx+1,0)
							}
						}
						return
					}
					// if(this.list[m].grantNum){
						// 发过多少货
					// }else{
						// 没有填入数据的
						if(!this.list[m].quantityIssued){
							// 上一位的数据是否满足
							if(this.list[m-1] && this.list[m-1].quantityIssued < this.list[m-1].applyNum){
								const newCard = {
									...this.list[m-1],
									quantityIssued : this.list[m-1].applyNum - this.list[m-1].quantityIssued,
									add: '1',
									charg: res.BLPL[0].CHARG,
									... res.BLPL[0],
									NLPLA: this.nlpla
								}
								this.list.splice(m, 0, newCard);
								if( res.BLPL[0].PACMG > (this.list[m-1].applyNum - this.list[m-1].quantityIssued)){
									this.factorial(res,plnr, m+1, res.BLPL[0].PACMG - (this.list[m-1].applyNum - this.list[m-1].quantityIssued))
								}
								return
							}
							// 只有一个
							if(count === 1){
								this.$set(this.list,m,{...this.list[m],quantityIssued : res.BLPL[0].PACMG,charg: res.BLPL[0].CHARG,... res.BLPL[0],NLPLA: this.nlpla})
							}else{
								if( res.BLPL[0].PACMG > this.list[m].applyNum){
									if(count === m){
										this.$set(this.list,m,{...this.list[m],quantityIssued : res.BLPL[0].PACMG,charg: res.BLPL[0].CHARG,... res.BLPL[0],NLPLA: this.nlpla})
										return
									}
									this.list[m].quantityIssued = this.list[m].applyNum
									this.$set(this.list,m,{...this.list[m],quantityIssued : this.list[m].applyNum,charg: res.BLPL[0].CHARG,... res.BLPL[0],NLPLA: this.nlpla})
									this.factorial(res,plnr,m+1,res.BLPL[0].PACMG-this.list[m].applyNum)
									return;
								}else{
									this.$set(this.list,m,{...this.list[m],quantityIssued : res.BLPL[0].PACMG,charg: res.BLPL[0].CHARG,... res.BLPL[0],NLPLA: this.nlpla})
								}
							}
						}else{
							if(this.list[m].quantityIssued < this.list[m].applyNum){
								// if(count === m || count === 1){
									const newCard = {
										...this.list[m],
										quantityIssued : res.BLPL[0].PACMG ,
										add: '1',
										charg: res.BLPL[0].CHARG,
										... res.BLPL[0],
										NLPLA: this.nlpla
									}
									this.list.splice(m+1, 0, newCard);
									return
								// }
							}else{
								this.$u.toast('暂无剩余物料');
							}
						}
					// }
				}
			}
		}
	}
};
</script>

<style lang="scss" scoped>
page {
	background: #f8f8f8;
}
.headerTitle{
	padding: 20rpx;
	font-weight: 600;
	.items{
		line-height: 40rpx;
	}
}
.btn {
	padding: 20rpx;
	background: #fff;
	.topSearch {
		margin-bottom: 20rpx;
	}
}
.bottomBtn {
	position: sticky;
	padding: 20rpx;
	display: flex;
	justify-content: space-between;
	background: #fff;
	bottom: 0rpx;
	margin-top: 20rpx;
	.u-btn {
		width: 300rpx;
	}
}
.blue {
	color: #3f9dcc;
}
.total {
	background: #fff;
	color: #000;
	padding: 0rpx 40rpx;
	display: flex;
	justify-content: space-between;
	font-size: 32rpx;
	.line {
		margin: 0px 10rpx;
	}
}
.cardbox {
	min-height: calc(100vh - 480rpx);
	padding: 0rpx 20rpx;
	margin-top: 20rpx;
}
.cardContent {
	border-radius: 8px;
	background: #fff;
	margin-bottom: 20rpx;
}
.listItemTitle {
	display: flex;
	justify-content: space-between;
	padding: 20rpx;
	border-bottom: 2px solid #f8f8f8;
	.u-btn {
		width: 150rpx;
		margin: 0px;
		margin-top: 10rpx;
	}
	.item {
		line-height: 50rpx;
		color: #333;
		font-size: 28rpx;
		font-weight: 500;
		word-break: break-all;
		font-weight: 600;
	}
}
.listBottom {
	.bottomTitle {
		height: 80rpx;
		position: relative;
		.desc {
			color: #bbb;
			font-size: 24rpx;
			line-height: 80rpx;
			padding-left: 20rpx;
		}
		.topIcons {
			position: absolute;
			left: 50%;
			top: 50%;
			transform: translate(-50%, -50%);
			color: #aaa;
		}
	}
	.bottomBox {
		padding: 20rpx;
		.bottomItem {
			background: #f8f8f8;
			padding: 20rpx;
			margin-bottom: 20rpx;
			.items {
				color: #333;
				font-size: 24rpx;
				height: 40rpx;
				line-height: 40rpx;
			}
		}
	}
}
/deep/ .u-sticky {
	top: 0 !important;
	background: #fff;
}
.checkedCase{
	margin-top: 10rpx;
}
</style>