<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.materialLotNo}}</view>
								<view><strong>上架数量</strong> : {{singleInfo.number}}</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-swipe-action> -->

				<uni-forms ref="form" :modelValue="formData" :rules="rules">
					<view :key="index" v-for="(item, index) in wmsLotNoList">
						<!-- 						<uni-swipe-action-item :key="index" v-for="(item, index) in wmsLotNoList"
							@click="(data) => clickDetail(index,data)" @change="swipChange"> -->
						<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="库位条码" :labelWidth='90' name="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'>
							<u-number-box inputWidth="120" button-size="36" v-model="item.number"
								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-swipe-action-item> -->
				</uni-forms>
				<!-- </uni-swipe-action> -->
			</uni-collapse-item>
		</uni-collapse>
		<u-button type="primary" @click="submit">提交</u-button>
	</view>
</template>

<script>
	import {
		addInDetail,
		addLotInfo,
	} from "@/api/wms/purchase.js";

	import {
		updateInDetail,
		getConnectLoc
	} from "@/api/wms/pdcIn.js";
	export default {
		onLoad: function(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;
			console.log(option);
			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.eachNumber = option.eachNumber;
			this.splitNumber = option.splitNumber;
			this.index = option.index
		},
		data() {
			return {
				//入库时间
				rkTime: null,
				//是否已分批
				isSecondOpen: false,
				selectedRow: {},
				singleInfo: {},
				wmsLotNoList: [],
				eachNumber: null,
				splitNumber: null,
				index: null,
				checkStorageLocationBarcode: true,
				// storageLocationBarcode: ''
				formData: {},
				rules: {
					storageLocationBarcode: {
						rules: [{
							required: true,
							errorMessage: '请输入库位条码!'
						}]
					}
				},
			}
		},
		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 = [];
				console.log(this.singleInfo)

				let materialCode = this.singleInfo.materialCode;
				let batchNo = this.singleInfo.materialBatchNo;
				let unit = this.singleInfo.unit;
				let purchaseInCode = this.singleInfo.purchaseInCode;
				let type = this.singleInfo.type;
				let unitId = this.singleInfo.unitId;
				let secondNumber = this.singleInfo.secondNumber;
				let secondUnitId = this.singleInfo.secondUnitId;
				let productionVersion = this.singleInfo.productionVersion;
				let materialName = this.singleInfo.materialName;
				let specification = this.singleInfo.specification;
				let unitName = this.singleInfo.unit;
				let storageInBillCode = this.singleInfo.storageInBillCode;
				let storageInBillDetailCode = this.singleInfo.storageInBillDetailCode;
				let erpDocLineKey1 = this.singleInfo.erpDocLineKey1;

				if (this.eachNumber != 0 && this.eachNumber != null) {
					console.log(this.eachNumber)
					this.splitNumber = 0;
					let t;
					let k;
					t = parseInt(this.singleInfo.number / this.eachNumber);
					k = this.singleInfo.number % this.eachNumber;
					if (k != 0) {
						t++;
					}
					for (let i = 0; i < t; i++) {
						let obj = {};
						obj.materialCode = materialCode;
						obj.batchNo = batchNo;
						obj.number = this.eachNumber;
						obj.secondNumber = this.eachNumber;
						obj.unit = unit;
						obj.secondUnitId = secondUnitId;
						obj.type = type;
						obj.storageInBillDetailCode = storageInBillDetailCode;
						obj.storageInBillCode = storageInBillCode;
						obj.materialName = materialName;
						obj.specification = specification;
						obj.productionVersion = productionVersion;
						obj.storageInTime = this.rkTime;
						if (i == t - 1) {
							if (k != 0) {
								obj.number = k;
							}
						}
						// obj.lotNo = i + 1;
						this.wmsLotNoList.push(obj);
					}
				}
				if (this.splitNumber != 0 && this.splitNumber != null) {
					console.log(2)
					this.eachNumber = 0;
					let k;
					let j;
					k = parseInt(this.singleInfo.number / this.splitNumber);
					j = this.singleInfo.number - (this.splitNumber - 1) * k;

					for (let i = 0; i < this.splitNumber; i++) {
						let obj = {};
						obj.materialCode = materialCode;
						obj.batchNo = batchNo;
						obj.number = k;
						obj.secondNumber = k;
						obj.secondUnitId = secondUnitId;

						obj.unit = unit;
						obj.type = type;
						obj.storageInBillDetailCode = storageInBillDetailCode;
						obj.storageInBillCode = storageInBillCode;
						obj.materialName = materialName;
						obj.specification = specification;
						obj.productionVersion = productionVersion;
						obj.storageInTime = this.rkTime;
						// obj.lotNo = i + 1;
						if (i == this.splitNumber - 1) {
							obj.number = j;
							obj.secondNumber = j;
						}
						this.wmsLotNoList.push(obj);
					}
				}
			},
			//不拆分批次
			singleSplit() {
				this.wmsLotNoList = [];
				this.splitNumber = 1;
				this.eachNumber = 0;
				let obj = {};
				obj.materialCode = this.singleInfo.materialCode;
				obj.batchNo = this.singleInfo.materialBatchNo;
				obj.number = this.singleInfo.number;
				obj.unit = this.singleInfo.unit;
				obj.secondNumber = this.singleInfo.secondNumber;
				obj.secondUnitId = this.singleInfo.secondUnitId;
				obj.type = this.singleInfo.type;
				obj.storageInBillDetailCode = this.singleInfo.storageInBillDetailCode;
				obj.storageInBillCode = this.singleInfo.storageInBillCode;
				obj.materialName = this.singleInfo.materialName;
				obj.specification = this.singleInfo.specification;
				obj.productionVersion = this.singleInfo.productionVersion;
				obj.storageInTime = this.rkTime;

				// obj.lotNo = 1;
				this.wmsLotNoList.push(obj);
			},
			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.wmsLotNoList[i].storageLocationBarcode = res.result;
						_this.splitStlBarcode(i);
					}
				});
			},
			//提交分批入库详情
			submit() {
				//数量防错
				let allNum = 0;
				for (var i in this.wmsLotNoList) {
					allNum += this.wmsLotNoList[i].number;
				}
				console.log(allNum)
				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.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 {
							console.log(this.wmsLotNoList);
							var flag =
								this.wmsLotNoList.filter((obj) => obj.whCode == null).length == 0 ?
								1 :
								0;
							console.log(flag);
							if (flag == 0) {
								console.log("入库库位必填！", flag);
								this.$modal.msgError("入库库位必填！");
							} else {
								let obj = {};
								obj = this.singleInfo;
								obj.batchNo = this.singleInfo.materialBatchNo;
								obj.eachNumber = this.eachNumber;
								// obj.eachSecondNumber = this.eachSecondNumber;
								obj.splitNumber = this.splitNumber;

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

						}
					}



					// let obj = {};
					// obj = this.singleInfo;
					// obj.batchNo = this.singleInfo.materialBatchNo;
					// obj.lotNo = this.singleInfo.materialLotNo;
					// obj.eachNumber = this.eachNumber;
					// // obj.eachSecondNumber = this.eachSecondNumber;
					// obj.splitNumber = this.splitNumber;
					// addLotInfo(obj); //拆箱详情
					// addInDetail(this.wmsLotNoList, 1) //对库存操作
					// 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 {
					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>