<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)" 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
	} 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 = [];
				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;
					let materialCode = this.singleInfo.materialCode;
					let batchNo = this.singleInfo.materialBatchNo;
					let unit = this.singleInfo.unit;
					let productInCode = this.singleInfo.productInCode;
					let unitId = this.singleInfo.unitId;
					let secondUnitId = this.singleInfo.secondUnitId;
					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.unitId = unitId;
						obj.secondUnitId = secondUnitId;
						obj.unit = unit;
						obj.storageInBillCode = productInCode;
						obj.storageInBillDetailCode = this.singleInfo.storageInBillDetailCode;
						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;

					let materialCode = this.singleInfo.materialCode;
					let batchNo = this.singleInfo.materialBatchNo;
					let unit = this.singleInfo.unit;
					let productInCode = this.singleInfo.productInCode;
					let unitId = this.singleInfo.unitId;
					let secondUnitId = this.singleInfo.secondUnitId;
					for (let i = 0; i < this.splitNumber; i++) {
						let obj = {};
						obj.materialCode = materialCode;
						obj.batchNo = batchNo;
						obj.number = k;
						obj.secondNumber = k;
						obj.unit = unit;
						obj.unitId = unitId;
						obj.secondUnitId = secondUnitId;
						obj.storageInBillCode = productInCode;
						obj.storageInBillDetailCode = this.singleInfo.storageInBillDetailCode;
						obj.storageInTime = this.rkTime;
						// obj.lotNo = i + 1;
						if (i == this.splitNumber - 1) {
							obj.number = 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.secondNumber = this.singleInfo.secondNumber;
				obj.secondUnit = this.singleInfo.secondUnit;
				obj.secondUnitId = this.singleInfo.secondUnitId;
				obj.storageInBillCode = this.singleInfo.productInCode;
				obj.storageInBillDetailCode = this.singleInfo.storageInBillDetailCode;
				obj.number = this.singleInfo.number;
				obj.unit = this.singleInfo.unit;
				obj.storageInTime = this.rkTime;
				// obj.lotNo = 1;
				this.wmsLotNoList.push(obj);
			},
			splitStlBarcode(i) {
				console.log(this.wmsLotNoList[i]);

				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('-');
				console.log(_this.$store.getters)
				if (whCode) {
					let warehouseObj = _this.$store.getters.warehouseOptions.find(item => item.warehouseCode == whCode);
					if (!warehouseObj) {
						_this.checkStorageLocationBarcode = false;
						_this.$modal.msg("仓库不存在！");
						return;
					}
					if (areaCode) {
						let areaObj = _this.$store.getters.areaOptions.find(item => item.storageAreaCode ==
							areaCode);
						if (!areaObj) {
							_this.checkStorageLocationBarcode = false;
							_this.$modal.msg("库区不存在！");
							return;
						}
						if (shelvesCode) {
							let shelvesObj = _this.$store.getters.shelvesOptions.find(item => item.storageShelvesCode ==
								shelvesCode);
							if (!shelvesObj) {
								_this.checkStorageLocationBarcode = false;
								_this.$modal.msg("货架不存在！");
								return;
							};
							if (storageLocationCode) {
								let locationObj = _this.$store.getters.locationOptions.find(item => item
									.storageLocationCode == (extra ?
										(storageLocationCode + '-' + extra) : storageLocationCode));
								if (!locationObj) {
									_this.checkStorageLocationBarcode = false;
									_this.$modal.msg("库位不存在！");
									return;
								};
							}
						}
					}
				}
				_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);
					}
				});
			},
			//提交分批入库详情
			async submit() {
				//数量防错
				let allNum = 0;
				for (var i in this.wmsLotNoList) {
					allNum += this.wmsLotNoList[i].number;
				}
				console.log(allNum)
				if (allNum == this.singleInfo.number) {
					let obj = {};
					obj = this.singleInfo;
					obj.batchNo = this.singleInfo.materialBatchNo;
					obj.lotNo = this.singleInfo.materialLotNo;
					obj.eachNumber = this.eachNumber;
					obj.storageInBillDetailCode = this.singleInfo.storageInBillDetailCode;
					obj.storageInBillCode = this.singleInfo.storageInBillCode;
					obj.type = this.singleInfo.type;

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