<template>
	<view>
		<uni-collapse>
			<view class="cu-card article ">
				<view class="cu-item shadow borderBottom">
					<view class="content">
						<view class="desc">
							<view class="text-content" style="font-size: 15px;">
								<view><strong>物料编码</strong> : {{singleInfo.materialCode}}</view>
								<view><strong>物料名称</strong> : {{singleInfo.materialName}}</view>
								<view><strong>物料批号</strong> : {{singleInfo.materialBatchNo}}</view>
								<view><strong>上架数量</strong> : {{singleInfo.secondNumber}}</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<uni-row>
				<uni-col :span="12">
					<span style="display: block;text-align: center;">每份数量<view style="margin-left: 15%;"><u-number-box
								v-model="eachNumber" integer min="0" @change="eachNumberClear" /></view></span>
				</uni-col>
				<uni-col :span="12">
					<span style="display: block;text-align: center;">拆分数量<view style="margin-left: 15%;"><u-number-box
								v-model="splitNumber" integer min="0" @change="splitNumberClear" /></view></span>
				</uni-col>
			</uni-row>
			<uni-row style="margin-top: 5px;" :gutter="10">
				<uni-col :span="12">
					<u-button type="primary" icon="cut" :disabled="isSecondOpen" @click="multiSplit" :plain="true"
						text="拆分"></u-button>
				</uni-col>
				<uni-col :span="12">
					<u-button type="success" icon="close-circle" @click="singleSplit" :disabled="isSecondOpen"
						:plain="true" text="不拆分"></u-button>
				</uni-col>
			</uni-row>
			<uni-collapse-item :open="true">
				<uni-forms ref="form" :modelValue="formData">
					<view :key="index" v-for="(item, index) in wmsLotNoList">
						<view>
							<uni-badge :text="index+1" class="uni-badge-left-margin" type="primary"></uni-badge>
						</view>
						<uni-forms-item label="物料箱号" :labelWidth='90' :name="item.lotNo">
							<uni-easyinput type="text" v-model="item.lotNo" />
						</uni-forms-item>
						<uni-forms-item label="推荐库位" :label-width="90" ref="myInput">
							<uni-easyinput disabled type="text" v-model="item.recommend"
								style="width: 70%;float: left;" />
							<u-button
								style="background-color: beige;width: 30%;float: left;font-size: 100%;height: 100%;"
								@click="clickCopy(index)">复制库位</u-button>
						</uni-forms-item>
						<uni-forms-item label="库位条码" :labelWidth='90'
							:name="'wmsLotNoList.'+ index +'.storageLocationBarcode'">
							<uni-easyinput suffixIcon="scan" @iconClick="scanBarstorageLocationBarcode(index)"
								@change="splitStlBarcode(index,$event)" type="text"
								v-model="item.storageLocationBarcode" />
						</uni-forms-item>
						<uni-forms-item label="上架数量" :labelWidth='90'>
							<second-number-change-to-convert :materialCode="item.materialCode"
								:secondNumber.sync="item.secondNumber" :secondUnitId="item.secondUnitId"
								:number.sync="item.number" :unitId="item.unitId"></second-number-change-to-convert>
							<!-- <u-number-box inputWidth="120" button-size="36" v-model="item.secondNumber"
								min="0"></u-number-box> -->
						</uni-forms-item>
						<uni-forms-item label="入库时间" :labelWidth='90' :name="item.storageInTime">
							<view class="example-body">
								<uni-datetime-picker type="datetime" v-model="item.storageInTime" />
							</view>
						</uni-forms-item>
					</view>
				</uni-forms>
			</uni-collapse-item>
		</uni-collapse>
		<u-button type="warning" @click="clickCopy">一键复制</u-button>
		<u-button type="primary" @click="submit">提交</u-button>
	</view>
</template>

<script>
	import {
		addInDetail,
		addLotInfo,
		uploadU9
	} from "@/api/wms/purchase.js";
	import SecondNumberChangeToConvert from "@/components/SecondNumberChangeToConvert/index.vue";

	import {
		updateInDetail,
		getConnectLoc
	} from "@/api/wms/pdcIn.js";
	import {
		listStock
	} from "@/api/wms/stock.js"
	// import { set } from "lodash";
	export default {
		onLoad: async function(option) {
			console.log(option);
			// 获取当前时间
			var currentDate = new Date();
			// 格式化为字符串（YYYY-MM-DD HH:mm:ss）
			var year = currentDate.getFullYear();
			var month = ("0" + (currentDate.getMonth() + 1)).slice(-2);
			var day = ("0" + currentDate.getDate()).slice(-2);
			var hours = ("0" + currentDate.getHours()).slice(-2);
			var minutes = ("0" + currentDate.getMinutes()).slice(-2);
			var seconds = ("0" + currentDate.getSeconds()).slice(-2);
			var formattedDate = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
			// 将当前时间赋值给 formData.endTime
			this.rkTime = formattedDate;
			this.isSecondOpen = option.isSecondOpen == 'false' ? false : true;
			this.selectedRow = JSON.parse(decodeURIComponent(option.selectedRow));
			this.singleInfo = JSON.parse(decodeURIComponent(option.singleInfo));
			this.wmsLotNoList = JSON.parse(decodeURIComponent(option.wmsLotNoList));
			this.wmsLotNoList.map(item => {
				item.storageInTime = formattedDate;
				item.storageLocationBarcode = item.whCode ? (item.areaCode ? (
						item.shelvesCode ? (item.storageLocationCode ? (item
							.whCode + '-' + item.areaCode + '-' + item
							.shelvesCode +
							'-' + item.storageLocationCode) : (item.whCode +
							'-' + item.areaCode + '-' + item
							.shelvesCode
						)) : (item.whCode + '-' + item.areaCode)) : item
					.whCode) : ''
				return item
			})
			console.log(this.wmsLotNoList);
			this.recommend = await fnListStock(this.singleInfo)
			this.eachNumber = option.eachNumber;
			this.splitNumber = option.splitNumber;
			this.index = option.index

			/**
			 * 通过明细编码去获取库位
			 * @param {Object} list 明细信息
			 */
			async function fnListStock(list) {
				const set = new Set()
				await listStock({
					materialCode: list.materialCode
				}).then(res => {
					const rows = res.rows;
					for (let i in rows) {
						if (rows[i].whCode != null && rows[i].areaCode != null && rows[i]
							.storageLocationCode && rows[i].shelvesCode) {
							set.add(rows[i].whCode + '-' + rows[i].areaCode + '-' + rows[i].shelvesCode +
								'-' + rows[i].storageLocationCode)
						}
					}
				})
				return [...set].toString()
			}
		},
		data() {
			return {
				recommend: null,
				number: 1111,
				//入库时间
				rkTime: null,
				//是否已分批
				isSecondOpen: false,
				selectedRow: {},
				singleInfo: {},
				wmsLotNoList: [],
				eachNumber: null,
				splitNumber: null,
				index: null,
				checkStorageLocationBarcode: true,
				// storageLocationBarcode: ''
				formData: {},
				rules: {
					// storageLocationBarcode: {
					// 	rules: [{
					// 		required: true,
					// 		errorMessage: '请输入库位条码!'
					// 	}]
					// }
					storageLocationBarcode: [{

						required: true,
						errorMessage: '请输入库位条码!'

					}]
				},
			}
		},
		components: {
			SecondNumberChangeToConvert
		},
		methods: {
			eachNumberClear() {
				this.eachSecondNumber = null;
				this.splitNumber = null;
			},
			eachSecondNumberClear() {
				this.eachNumber = null;
				this.splitNumber = null;
			},
			splitNumberClear() {
				this.eachNumber = null;
				this.eachSecondNumber = null;
			},
			//选择条件拆分批次
			multiSplit() {
				this.wmsLotNoList = [];
				let materialCode = this.singleInfo.materialCode;
				let batchNo = this.singleInfo.materialBatchNo;
				let unit = this.singleInfo.unit;
				let unitId = this.singleInfo.unitId;
				let secondUnitId = this.singleInfo.secondUnitId;
				let purchaseInCode = this.singleInfo.purchaseInCode;
				let materialName = this.singleInfo.materialName;
				let specification = this.singleInfo.specification;
				let unitName = this.singleInfo.unitName;
				let u9StorageCode = this.singleInfo.u9StorageCode;
				let storageInBillDetailCode = this.singleInfo.storageInBillDetailCode;
				let u9LineId = this.singleInfo.u9LineId;
				let connectedLocation = "";
				let storageInTime = this.rkTime;
				if (this.singleInfo.whCode != null) {
					connectedLocation = this.singleInfo.whCode;
					if (this.singleInfo.areaCode != null) {
						connectedLocation = connectedLocation + '-' + this.singleInfo.areaCode;
						if (this.singleInfo.shelvesCode != null) {
							connectedLocation = connectedLocation + '-' + this.singleInfo.shelvesCode;
							if (this.singleInfo.storageLocationCode != null) {
								connectedLocation = connectedLocation + '-' + this.singleInfo.storageLocationCode;
							}
						}
					}
				}
				let locCascade = [
					this.singleInfo.whCode,
					this.singleInfo.areaCode,
					this.singleInfo.shelvesCode,
					this.singleInfo.storageLocationCode,
				];
				if (this.eachNumber != null) {
					let t;
					let k;
					t = parseInt(this.singleInfo.number / this.eachNumber);
					k = this.singleInfo.number % this.eachNumber;
					let rate;
					let secondK;
					let secondT;
					rate = this.singleInfo.number / this.singleInfo.secondNumber;
					secondT = parseInt(this.singleInfo.secondNumber / this.eachNumber);
					secondK = this.singleInfo.secondNumber % this.eachNumber;
					// if (k != 0) { t++; }
					if (secondK != 0) {
						secondT++;
					}
					for (let i = 0; i < secondT; i++) {
						console.log(i)
						let obj = {};
						obj.recommend = this.recommend;
						obj.materialCode = materialCode;
						obj.batchNo = batchNo;
						obj.number = this.eachNumber * rate;
						obj.secondNumber = this.eachNumber;
						obj.unit = unit;
						obj.unitId = unitId;
						obj.secondUnitId = secondUnitId;
						obj.storageInBillCode = purchaseInCode;
						obj.materialName = materialName;
						obj.specification = specification;
						obj.unitName = unitName;
						obj.locCascade = locCascade;
						obj.connectedLocation = connectedLocation;
						obj.u9StorageCode = u9StorageCode;
						obj.storageInBillDetailCode = storageInBillDetailCode;
						obj.u9LineId = u9LineId;
						obj.storageInTime = storageInTime;
						// this.selectLoc(locCascade, obj);
						if (i == secondT - 1) {
							if (secondK != 0) {
								obj.number = secondK * rate;
								obj.secondNumber = secondK;
							}
						}
						// obj.lotNo = i + 1;
						console.log(obj);
						this.wmsLotNoList.push(obj);
					}
				} else if (this.splitNumber != null) {
					let k;
					let j;
					const data = this.singleInfo[0] === undefined ? this.singleInfo : this.singleInfo[0]
					k = parseInt(data.number / this.splitNumber);
					j = data.number - (this.splitNumber - 1) * k;
					let secondK;
					let secondJ;
					secondK = parseInt(data.secondNumber / this.splitNumber);
					secondJ = data.secondNumber - (this.splitNumber - 1) * secondK;
					for (let i = 0; i < this.splitNumber; i++) {
						let obj = {};
						obj.recommend = this.recommend;
						obj.materialCode = materialCode;
						obj.batchNo = batchNo;
						obj.number = k;
						obj.unit = unit;
						obj.secondNumber = secondK;
						obj.unitId = unitId;
						obj.secondUnitId = secondUnitId;
						obj.storageInBillCode = purchaseInCode;
						obj.materialName = materialName;
						obj.unitName = unitName;
						obj.specification = specification;
						obj.locCascade = locCascade;
						// this.selectLoc(locCascade, obj);
						obj.connectedLocation = connectedLocation;
						obj.u9StorageCode = u9StorageCode;
						obj.storageInBillDetailCode = storageInBillDetailCode;
						obj.u9LineId = u9LineId;
						obj.storageInTime = storageInTime;
						// obj.lotNo = i + 1;
						if (i == this.splitNumber - 1) {
							obj.number = j;
							obj.secondNumber = secondJ;
						}
						this.wmsLotNoList.push(obj);
					}
				} else if (this.eachSecondNumber != 0) {
					let t;
					let k;
					t = parseInt(this.singleInfo.secondNumber / this.eachSecondNumber);
					k = this.singleInfo.secondNumber % this.eachSecondNumber;
					if (k != 0) {
						t++;
					}
					for (let i = 0; i < t; i++) {
						let obj = {};
						obj.recommend = this.recommend;
						obj.materialCode = materialCode;
						obj.batchNo = batchNo;
						obj.secondNumber = this.eachSecondNumber;
						obj.secondUnit = secondUnit;
						obj.storageInBillCode = purchaseInCode;
						obj.materialName = materialName;
						obj.unitName = unitName;
						obj.secondNumber = this.eachSecondNumber;
						obj.unitId = unitId;
						obj.secondUnitId = secondUnitId;
						obj.specification = specification;
						obj.locCascade = locCascade;
						obj.connectedLocation = connectedLocation;
						obj.u9StorageCode = u9StorageCode;
						obj.storageInBillDetailCode = storageInBillDetailCode;
						obj.u9LineId = u9LineId;
						obj.storageInTime = storageInTime;
						// this.selectLoc(locCascade, obj);
						if (i == t - 1) {
							if (k != 0) {
								obj.secondNumber = k;
							}
						}
						// obj.lotNo = i + 1;
						console.log(obj);
						this.wmsLotNoList.push(obj);
					}
				}
			},
			/**
			 * 复制
			 */
			clickCopy(index) {
				const data = this.wmsLotNoList
				if (index != undefined) {
					data[index].storageLocationBarcode = data[index].recommend
				} else {
					for (let i in data) {
						data[i].storageLocationBarcode = data[i].recommend
					}
				}
				this.wmsLotNoList = Object.assign({});
				this.wmsLotNoList = data
			},
			//不拆分批次
			async singleSplit() {
				const set = new Set()
				await listStock({
					materialCode: this.singleInfo.materialCode
				}).then(res => {
					const rows = res.rows;
					for (let i in rows) {
						if (rows[i].whCode != null && rows[i].areaCode != null && rows[i]
							.storageLocationCode && rows[i].shelvesCode) {
							set.add(rows[i].whCode + '-' + rows[i].areaCode + '-' + rows[i]
								.storageLocationCode + '-' + rows[i].shelvesCode)
						}
					}
				})
				const array = [...set].toString()
				this.wmsLotNoList = [];
				this.splitNumber = 1;
				let obj = {};
				obj.areaCode = array;
				obj.recommend = this.recommend;
				obj.materialCode = this.singleInfo.materialCode;
				obj.batchNo = this.singleInfo.materialBatchNo;
				obj.secondNumber = this.singleInfo.secondNumber;
				obj.secondUnit = this.singleInfo.secondUnit;
				obj.storageInBillCode = this.singleInfo.purchaseInCode;
				obj.number = this.singleInfo.number;
				obj.unitId = this.singleInfo.unitId;
				obj.secondUnitId = this.singleInfo.secondUnitId;
				obj.unit = this.singleInfo.unit;
				obj.unitName = this.singleInfo.unitName;
				obj.materialName = this.singleInfo.materialName;
				obj.specification = this.singleInfo.specification;
				obj.u9StorageCode = this.singleInfo.u9StorageCode;
				obj.storageInBillDetailCode = this.singleInfo.storageInBillDetailCode;
				obj.u9LineId = this.singleInfo.u9LineId;
				obj.storageInTime = this.rkTime;
				if (this.singleInfo.whCode != null) {
					obj.connectedLocation = this.singleInfo.whCode;
					if (this.singleInfo.areaCode != null) {
						obj.connectedLocation = obj.connectedLocation + '-' + this.singleInfo.areaCode;
						if (this.singleInfo.shelvesCode != null) {
							obj.connectedLocation = obj.connectedLocation + '-' + this.singleInfo.shelvesCode;
							if (this.singleInfo.storageLocationCode != null) {
								obj.connectedLocation = obj.connectedLocation + '-' + this.singleInfo
									.storageLocationCode;
							}
						}
					}
				}
				obj.locCascade = [
					this.singleInfo.whCode,
					this.singleInfo.areaCode,
					this.singleInfo.shelvesCode,
					this.singleInfo.storageLocationCode,
				];
				// this.selectLoc(obj.locCascade, obj);
				// obj.lotNo = 1;
				this.wmsLotNoList.push(obj);
				console.log(this.wmsLotNoList);
			},
			async splitStlBarcode(i, event) {
				const _this = this;
				const detail = _this.wmsLotNoList[i];

				detail.whCode = null;
				detail.areaCode = null;
				detail.shelvesCode = null;
				detail.storageLocationCode = null;

				let barcode = detail.storageLocationBarcode;
				if (!barcode) {
					return; // 如果没有条码，不做任何处理
				}

				let [whCode, areaCode, shelvesCode, storageLocationCode, extra] = barcode.split('-');

				const data = await getConnectLoc({
					connectLoc: event
				})
				if (!data.data) return this.$modal.msg("库位条码校验错误，请重新输入！")

				_this.checkStorageLocationBarcode = true;
				detail.whCode = whCode || null;
				detail.areaCode = areaCode || null;
				detail.shelvesCode = shelvesCode || null;
				detail.storageLocationCode = extra ? `${storageLocationCode}-${extra}` : storageLocationCode || null;
				console.log(this.wmsLotNoList[i]);
			},
			scanBarstorageLocationBarcode(i) {
				const _this = this;
				uni.scanCode({
					scanType: ['barCode', 'qrCode'],
					success: function(res) {
						_this.$set(_this.wmsLotNoList[i], "storageLocationBarcode", res
							.result);
						_this.splitStlBarcode(i);
					}
				});
			},
			//提交分批入库详情
			async submit() {
				// const valid = await this.$refs.form.validate();
				// if (valid) {
				// this.$refs.form.validate().then(res => {
				let isStorageLocationBarcode = true;
				for (var i in this.wmsLotNoList) {
					if (this.wmsLotNoList[i].storageLocationBarcode == null || this.wmsLotNoList[i]
						.storageLocationBarcode == '') isStorageLocationBarcode = false
				}
				if (isStorageLocationBarcode) {
					//数量防错
					let allNum = 0;
					for (var i in this.wmsLotNoList) {
						allNum += this.wmsLotNoList[i].number;
					}
					console.log(allNum, this.singleInfo.number)
					if (this.wmsLotNoList.length > 0) {
						if (this.wmsLotNoList[0].id != null) {
							console.log(this.wmsLotNoList[0].id);
							for (let i = 0; i < this.wmsLotNoList.length; i++) {
								// if (this.wmsu9whMode == "true") {
								// 	console.log(this.wmsu9whMode);
								// 	updateU9Stock(this.wmsLotNoList[i]);
								// } else {
								// 	updateStock(this.wmsLotNoList[i]);
								// }
								if (this.wmsLotNoList && this.wmsLotNoList.length >
									0) {
									this.selectedRow.status = "1";
								} else {
									this.selectedRow.status = "0";
								}
							}
							this.$modal.msgSuccess("编辑成功！");
							setTimeout(() => {
								uni.$emit('backWithParam', {
									status: this.selectedRow.status,
									index: this.index
								});
								this.$tab.navigateBack();
							}, 500);
						} else {
							let obj = {};
							obj = this.singleInfo;
							obj.batchNo = this.singleInfo.materialBatchNo;
							obj.eachNumber = this.eachNumber;
							obj.splitNumber = this.splitNumber;

							if (this.wmsLotNoList && this.wmsLotNoList.length >
								0) {
								this.selectedRow.status = "1";
							} else {
								this.selectedRow.status = "0";
							}
							if (!this.checkStorageLocationBarcode) {
								this.$modal.msg("库位条码校验错误，请重新输入！")
								return;
							}
							this.$modal.loading('提交中')
							addLotInfo(obj).then(res => {
								addInDetail(this.wmsLotNoList, 1).then(res => {
									uploadU9(this.wmsLotNoList)
									this.$modal.closeLoading();
									this.$modal.msgSuccess("编辑成功！");
									// setTimeout(() => {
									uni.$emit(
										'backWithParam', {
											status: this
												.selectedRow
												.status,
											index: this
												.index
										});
									this.$tab.navigateBack();
									// }, 500);
								})
							});
						}
					}

					// if (allNum == this.singleInfo.number) {
					// 	if (this.wmsLotNoList.length > 0) {
					// 		if (this.wmsLotNoList[0].id != null) {
					// 			console.log(this.wmsLotNoList[0].id);
					// 			for (let i = 0; i < this.wmsLotNoList.length; i++) {
					// 				// if (this.wmsu9whMode == "true") {
					// 				// 	console.log(this.wmsu9whMode);
					// 				// 	updateU9Stock(this.wmsLotNoList[i]);
					// 				// } else {
					// 				// 	updateStock(this.wmsLotNoList[i]);
					// 				// }
					// 				if (this.wmsLotNoList && this.wmsLotNoList.length >
					// 					0) {
					// 					this.selectedRow.status = "1";
					// 				} else {
					// 					this.selectedRow.status = "0";
					// 				}
					// 			}
					// 			this.$modal.msgSuccess("编辑成功！");
					// 			setTimeout(() => {
					// 				uni.$emit('backWithParam', {
					// 					status: this.selectedRow.status,
					// 					index: this.index
					// 				});
					// 				this.$tab.navigateBack();
					// 			}, 500);
					// 		} else {
					// 			let obj = {};
					// 			obj = this.singleInfo;
					// 			obj.batchNo = this.singleInfo.materialBatchNo;
					// 			obj.eachNumber = this.eachNumber;
					// 			obj.splitNumber = this.splitNumber;

					// 			if (this.wmsLotNoList && this.wmsLotNoList.length >
					// 				0) {
					// 				this.selectedRow.status = "1";
					// 			} else {
					// 				this.selectedRow.status = "0";
					// 			}
					// 			if (!this.checkStorageLocationBarcode) {
					// 				this.$modal.msg("库位条码校验错误，请重新输入！")
					// 				return;
					// 			}
					// 			this.$modal.loading('提交中')
					// 			addLotInfo(obj).then(res => {
					// 				addInDetail(this.wmsLotNoList, 1).then(res => {
					// 					uploadU9(this.wmsLotNoList)
					// 					this.$modal.closeLoading();
					// 					this.$modal.msgSuccess("编辑成功！");
					// 					// setTimeout(() => {
					// 					uni.$emit(
					// 						'backWithParam', {
					// 							status: this
					// 								.selectedRow
					// 								.status,
					// 							index: this
					// 								.index
					// 						});
					// 					this.$tab.navigateBack();
					// 					// }, 500);
					// 				})
					// 			});
					// 		}
					// 	}

					// } else {
					// 	this.$modal.msg("批号分批入库明细数量不符合！");
					// }
				} else {
					this.$modal.msg("库位条码必填！");
				}
				// })
			}
		},

	}
</script>

<style>
	.cu-card.article>.cu-item .content .text-content {
		height: 100% !important;
	}

	.cu-card.article>.cu-item {
		padding-bottom: 0;
	}

	.cu-card>.cu-item {
		margin: 0;
	}

	.uni-swipe {
		overflow: inherit;
	}
</style>