<template>
	<view class="page">
		<view class="btn">
			<FactorySelect v-model="warehouseCode" @change="warehouseChange" />
			<uni-easyinput v-if="vuex_user_factory !== '1010'" prefixIcon="search" class="topSearch" v-model="nlpla"
				focus placeholder="请扫描仓位" @change="handleInputNlpla"></uni-easyinput>
			<uni-easyinput prefixIcon="search" confirm-type="search" :disabled="isDisabled" v-model="wxparams"
				:focus="isFocus" placeholder="请扫描产品包装条码/外箱码" @confirm="handleConfirm"></uni-easyinput>
			<!-- <view class="checkedCase">
				<checkbox-group @change="checkedChange">
					<checkbox value="r1" :checked="checkedBox" />是否结案
				</checkbox-group>
			</view> -->
		</view>
		<view class="total">
			<view class="left">入库明细</view>
			<view class="right">
				批次数：
				<text class="blue">{{ chargaArr.length }}</text>
				<text class="line">|</text>
				总数量：
				<text class="blue">{{ totalNum }}</text>
			</view>
		</view>
		<ContentLoadingMore class="cardbox" :list='chargaArr'>
			<scroll-view scroll-y="true" style="height: 680rpx;">
				<view class="cardContent" v-for="(item, index) in chargaArr">
					<PutwayItem :item='item' :list='chargaArr' @delGonds="delGonds" />
				</view>
			</scroll-view>
		</ContentLoadingMore>
		<BottomBtn :btnArr="btnArr" @getBtnHandle="getBtnHandle"></BottomBtn>
	</view>
</template>

<script>
	import StickyNavBar from '@/components/StickyNavBar/index.vue';
	import FactorySelect from '@/components/FactorySelect/FactorySelect.vue'
	import ContentLoadingMore from '@/components/ContentLoadingMore/index.vue';
	import PutwayItem from './putwayItem.vue';
	import BottomBtn from '@/components/BottomBtn/index.vue';
	import {
		parseTime
	} from "@/utils/ruoyi";
	export default {
		components: {
			StickyNavBar,
			FactorySelect,
			ContentLoadingMore,
			PutwayItem,
			BottomBtn,
		},
		data() {
			return {
				r1: '',
				checkedBox: true,
				number: 0,
				totalNum: 0,
				show: true,
				nlpla: '',
				wxparams: '',
				warehouseCode: '',
				applyNo: '',
				btnArr: [{
						style: '',
						type: 'warning',
						text: '返回',
						way: 'goBack'
					},
					{
						style: '',
						type: 'primary',
						text: '提交',
						way: 'goSubmit'
					}
				],
				list: [],
				goodsList: [],
				isFocus: false,
				isDisabled: false,
				chargaArr: []
			};
		},
		created() {
			const pages = getCurrentPages(); // 获取页面栈
			const currentPage = pages[pages.length - 1]; // 获取当前页面的对象
			const options = currentPage.options; // 如果是通过路由带参数的话，参数会在这里
			console.log('当前页面参数:', options);
			if (currentPage.options.complete == "N") {
				this.applyNo = currentPage.options.order;
				this.getOrder(currentPage.options.order);
			}
		},
		methods: {
			getOrder(applyNo) {
				this.$u.api.mesApi
					.pdaMaterialReturn({
						pageNum: 1,
						pageSize: 10,
						applyNo
					})
					.then((res) => {
						if (res && res.code - 200 === 0) {
							const data = res.rows
							const arr = [];
							const result = data.filter((item, index, self) => {
								if (!arr.includes((item.sapItemCode))) {
									arr.push(item.sapItemCode)
								}
							});
							this.list = arr
						} else {
							this.$u.toast(res.msg);
						}
						this.loading = false;
					});
			},
			warehouseChange(e) {
				console.log(this.warehouseCode, '----');
			},
			// checkedChange() {
			// 	this.checkedBox = !this.checkedBox
			// },
			delGonds(detail) {
				this.goodsList.forEach((ele, idx) => {
					if (detail.PLNR === ele.PLNR) {
						this.goodsList.splice(idx, 1);
					}
				});
				this.totalNum = 0;
				this.goodsList.forEach((ele) => {
					this.totalNum += ele.TOMNG - 0
					ele.cardNum = 0
				});
				this.handleData()
			},
			getBtnHandle(row) {
				this[row.way]();
			},
			goBack() {
				uni.navigateBack();
			},
			goSubmit() {
				// 根据不同工厂，不同选择
				if (this.goodsList.length === 0) {
					return;
				}
				const data = JSON.parse(JSON.stringify(this.goodsList))
				data.forEach(ele => {
					ele.applyNo = this.applyNo
					ele.windCase = this.checkedBox ? 'Y' : 'N'
					ele.ERFMG = ele.TOMNG
					ele.ERFME = ele.MEINS
					// 添加仓库别
					ele.UMLGO = this.warehouseCode
				});
				this.$u.api.sapApi
					.sapRrm([{
						BLDAT: parseTime(new Date(), '{y}{m}{d}'),
						BUDAT: parseTime(new Date(), '{y}{m}{d}'),
						ZENCODE: 'A014',
						TYPE: 'CG',
						ITEM: data
					}], 300)
					.then((res) => {
						this.loading = false;
						if (!Array.isArray(res)) {
							return
						}
						if (res && res.every((item) => item.TYPE === 'S')) {
							if (this.checkedBox) {
								this.handleMes(data)
							}
							this.goodsList = [];
							this.chargaArr = []
							this.totalNum = 0;
							this.nlpla = '';
							this.wxparams = '';
							this.$u.toast('提交成功');
						}
						const foundObject = res.find(item => item.TYPE === 'E');
						if (foundObject && foundObject.MESSAGE) {
							this.$u.toast(foundObject.MESSAGE);
						}
					});
			},
			handleMes(arr) {
				arr.forEach(ele => {
					ele.batchCode = ele.CHARG
					ele.returnNum = 0
				});
				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);
						}
					});
			},
			handleConfirm(e) {
				this.isFocus = false;
				e && this.getPlnr(e);
			},
			handleInputNlpla(e) {
				if (e) {}
			},
			getPlnr(plnr) {
				this.isDisabled = true;
				if (!this.nlpla && this.vuex_user_factory !== '1010') {
					this.$u.toast('请先扫描仓位');
					setTimeout(() => {
						this.wxparams = '';
						this.isFocus = true;
						this.isDisabled = false;
					}, 1000);
					return
				}
				this.$u.api.sapApi
					.sapPlnr({
						plnr,
						zType: '001'
					}, 300)
					.then((res) => {
						console.log(this.list);
						if (res && res.RESULT.TYPE === 'S') {
							if (this.goodsList.some((item) => item.PLNR === plnr)) {
								setTimeout(() => {
									this.isFocus = true;
									this.isDisabled = false;
									this.wxparams = '';
								}, 1000);
								this.$u.toast('已经存在当前条码');
								return
							}
							// console.log(this.list);
							// console.log(res.DATA[0]["MATNR"]);
							console.log(this.list.includes(res.DATA[0]["MATNR"]));
							if (!this.list.includes(res.DATA[0]["MATNR"])) {
								setTimeout(() => {
									this.wxparams = '';
									this.isFocus = true;
									this.isDisabled = false;
								}, 1000);
								return this.$u.toast('当前条码物料编号不匹配');
							}
							const arr = [{
								...res.DATA[0],
								NLPLA: this.nlpla
							}]
							this.goodsList = this.goodsList.concat(arr);
							this.totalNum = 0;
							this.goodsList.forEach((ele) => {
								this.totalNum += ele.TOMNG - 0
								ele.cardNum = 0
							});
							this.handleData()
							setTimeout(() => {
								this.wxparams = '';
								this.isFocus = true;
								this.isDisabled = false;
							}, 1000);
						} else {
							setTimeout(() => {
								this.isFocus = true;
								this.isDisabled = false;
								this.wxparams = '';
							}, 1000);
							this.$u.toast(res.RESULT.MESSAGE);
						}
						this.loading = false;
					});
			},
			handleData() {
				this.chargaArr = this.goodsList.filter((item, index, self) => {
					return self.findIndex(t => t.CHARG === item.CHARG) === index;
				});
				this.chargaArr.forEach((ele, idx) => {
					this.goodsList.forEach(item => {
						if (ele.CHARG === item.CHARG) {
							ele.cardNum += (item.TOMNG - 0)
							this.$set(this.chargaArr, idx, {
								...ele
							})
						}
					});
				});
			},
		}
	};
</script>

<style lang="scss" scoped>
	.btn {
		padding: 20rpx;
		background: #fff;

		.factoryBox {
			padding: 0;
			margin-bottom: 10px;
		}

		.topSearch {
			margin-bottom: 20rpx;
		}

		.checkedCase {
			margin-top: 10rpx;
		}
	}

	.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 - 540rpx);
		padding: 0rpx 20rpx;
		margin-top: 20rpx;
	}

	.cardContent {
		border-radius: 8px;
		background: #fff;
		margin-bottom: 20rpx;
	}

	/deep/ .u-sticky {
		top: 0 !important;
		background: #fff;
	}
</style>