<template>
	<view>
		<uni-section title="">
			<view class="example">
				<uni-forms ref="form" :modelValue="item" labelWidth="80px" :rules="rules">
					<uni-forms-item label="装箱单号" name="FBillNo">
						<uni-easyinput v-model="item['FENCHASENUM.LT']" disabled>
						</uni-easyinput>
					</uni-forms-item>
					<uni-forms-item label="新装箱单号" name="Mdd">
						<uni-easyinput v-model="item['NewFENCHASENUM.LT']" @confirm="search">
						</uni-easyinput>
					</uni-forms-item>
					<uni-forms-item label="物料编码" name="Ch">
						<uni-easyinput v-model="item['FMaterialId.fnumber']" disabled />
					</uni-forms-item>
					<uni-forms-item label="实际作业数量" name="FActualQty"
						v-if="formId === 'LT_PRD_PMCWorkBench'||formId === 'SP_PickMtrl'">
						<uni-easyinput type="number" v-model="item.FActualQty" placeholder="实际作业数量" />
					</uni-forms-item>
					<uni-forms-item label="实际作业数量" name="FQty" v-if="formId === 'STK_MisDelivery'">
						<uni-easyinput type="number" v-model="item.FQty" placeholder="实际作业数量" />
					</uni-forms-item>
					<uni-forms-item label="实际作业数量" name="FRMREALQTY" v-if="formId === 'PUR_MRB'">
						<uni-easyinput type="number" v-model="item.FRMREALQTY" placeholder="实际作业数量" />
					</uni-forms-item>
					<uni-forms-item label="剩余数量" v-if="formId !== 'PUR_MRB'">
						<uni-easyinput disabled v-model="remainingQuantity" placeholder="" />
					</uni-forms-item>
					<uni-forms-item label="即时库存数量" name="FInventoryQty" v-if="formId !== 'PUR_MRB'">
						<uni-easyinput disabled v-model="item.FInventoryQty" placeholder="即时库存数量" />
					</uni-forms-item>
					<uni-forms-item label="生产车间" name="FWorkShopId.fname" v-if="formId !== 'PUR_MRB'">
						<uni-easyinput disabled v-model="item['FWorkShopId.fname']" />
					</uni-forms-item>
					<uni-forms-item label="仓位" name="FStockLocId.FF102029.fname" v-if="formId === 'PUR_MRB'">
						<uni-easyinput disabled v-model="item['FStockLocId.FF102029.fname']" />
					</uni-forms-item>
					<uni-forms-item label="采购员" name="FPURCHASERID.fname" v-if="formId === 'PUR_MRB'">
						<uni-easyinput disabled v-model="item['FPURCHASERID.fname']" />
					</uni-forms-item>
				</uni-forms>
				<button type="primary" @click="submit()">确认</button>
			</view>
		</uni-section>
	</view>
</template>

<script>
	import {
		getInfoByBarcode,
		getStockInfo
	} from '../../api/production_replenishment';
	import {
		playVoice,
		audioUrls
	} from '@/utils/audio.js'
	import modal from '../../uni_modules/uview-ui/libs/config/props/modal';
	export default {
		onLoad(option) {
			this.formId = uni.getStorageSync("formId")
			const item = JSON.parse(decodeURIComponent(option.item))
			const index = JSON.parse(decodeURIComponent(option.index))
			console.log(item)
			console.log(index)
			this.item = item
			this.index = index
		},
		data() {
			return {
				formId: '',
				item: {},
				index: '',
				isReplace: false,
				rules: {
					FActualQty: {
						rules: [{
								required: true,
								errorMessage: '请输入实发数量',
							},

						]
					},
					FQty: {
						rules: [{
								required: true,
								errorMessage: '请输入实发数量',
							},

						]
					},
					FRMREALQTY: {
						rules: [{
								required: true,
								errorMessage: '请输入实际作业数量',
							},

						]
					},
				},
			};
		},
		computed: {
			remainingQuantity() {
				console.log(this.item["FInventoryQty"] - this.item["FActualQty"])
				if (this.formId === 'LT_PRD_PMCWorkBench' || this.formId === 'SP_PickMtrl') {
					return Math.round((this.item["FInventoryQty"] - this.item["FActualQty"]) * 100) / 100;
				}
				if (this.formId === 'STK_MisDelivery') {
					return Math.round((this.item["FInventoryQty"] - this.item["FQty"]) * 100) / 100;
				}
			}
		},
		methods: {
			async search() {

				if (this.item['NewFENCHASENUM.LT'] == "") {
					uni.showToast({
						title: '请扫描条码',
						icon: 'none',
						duration: 3000
					})
					return
				}
				const data = {
					"parameters": [{
						"FormId": "LT_BD_MtlLotCodeMap",
						"FieldKeys": "FEntity_FSEQ,FMaterialId,FMaterialId.fnumber,FLot.FNumber,FLot,",
						"FilterString": [{
							"Left": "",
							"FieldName": "FNumber",
							"Compare": "67",
							// "Value": "T23091000852",
							"Value": this.item['NewFENCHASENUM.LT'],
							"Right": "",
							"Logic": 0
						}],
						"OrderString": "FEntity_FSEQ DESC",
					}]
				}
				this.$modal.loading('替换中，请耐心等待...');
				const firstResponse = await getInfoByBarcode(JSON.stringify(data))
				console.log(firstResponse)
				if (firstResponse.length === 0) {
					console.log("dafafadf")
					uni.showToast({
						title: '请确认条码有效！',
						duration: 2000,
						icon: 'none'
					});
					return; // 停止保存操作
				}
				if (firstResponse[0]["FMaterialId.fnumber"] != this.item["FMaterialId.fnumber"]) {
					console.log("dafafadf")
					uni.showToast({
						title: '编码与原物料编码不一致，请重新替换装箱单号',
						duration: 3000,
						icon: 'none'
					});
					playVoice(audioUrls.failVoiceUrl)
					return; // 停止保存操作
				}
				const data2 = {
					"parameters": [{
						"FormId": "STK_Inventory",
						"FieldKeys": "FAuxPropId.FF101501,FAuxPropId.FF101501.FDATAVALUE,FStockLocId.FF102029.fname,FBaseQty",
						"FilterString": [{
								"Left": "",
								"FieldName": "FMaterialId.FNumber",
								"Compare": "67",
								// "Value": "CAW04044-1611088-1",
								"Value": firstResponse[0]["FMaterialId.fnumber"],
								"Right": "",
								"Logic": 0
							},
							{
								"Left": "",
								"FieldName": "FLot.FNumber",
								"Compare": "67",
								// "Value": "智能工厂-智能1220/20230821&T23091000852&无&23122000002",
								"Value": firstResponse[0]["FLot.FNumber"],
								"Right": "",
								"Logic": 0
							},
							{
								"Left": "",
								"FieldName": "FBaseQty",
								"Compare": "21",
								"Value": "0",
								"Right": "",
								"Logic": 0
							}
						],
						"OrderString": "",
					}]
				}
				const secondResponse = await getStockInfo(JSON.stringify(data2))
				if (secondResponse.length > 1) {
					this.handleError("即时库存存在多个仓位，不允许选择！")
					this.$modal.closeLoading()
					this.item['NewFENCHASENUM.LT'] = ""
					return
				}
				console.log("原item", this.item)
				this.item['FInventoryQty'] = secondResponse[0]["FBaseQty"]
				this.item['Flot.FNumber'] = firstResponse[0]["FLot.FNumber"]
				this.item['FAuxPropId.FF101501.FDATAVALUE'] = secondResponse[0]["FAuxPropId.FF101501.FDATAVALUE"]
				this.item['FStockLocId.FF102029.fname'] = secondResponse[0]["FStockLocId.FF102029.fname"]
				this.item['smzt'] = 1
				console.log("替换后item", this.item)
				console.log(secondResponse)
				this.isReplace = true
				this.$modal.closeLoading()
				uni.showToast({
					title: '替换成功',
					icon: 'none',
					duration: 3000
				})
				playVoice(audioUrls.successVoiceUrl)

			},
			handleError(error) {
				playVoice(audioUrls.failVoiceUrl)
				console.error('操作失败:', error);
				modal.confirm(error).then(res => {
					if (res) {} else {}
				})
			},
			submit() {
				this.$refs.form.validate().then(res => {
					if (this.item["FActualQty"] < 0) {
						uni.showToast({
							title: '实发数量不能小于0',
							icon: 'none',
							duration: 3000
						})
						return
					}
					console.log(typeof this.item["NewFENCHASENUM.LT"])
					if ((typeof this.item["NewFENCHASENUM.LT"] != "undefined" && this.item["NewFENCHASENUM.LT"] !=
							"") && this.isReplace == false) {
						uni.showToast({
							title: '装箱单号未替换',
							icon: 'none',
							duration: 3000
						})
						return
					}
					console.log(this.item)
					this.item["index"] = this.index
					let self = this
					uni.navigateBack({
						success: function() {
							// 传递数据给上一页
							uni.$emit('item', self.item);
						}
					});
				}).catch(err => {
					console.log(err);
				})
			},
		}
	};
</script>
<style>
	/deep/ .is-disabled {
		background-color: #ffffff !important;
		color: #0d0d0d !important;
	}

	.example {
		padding-left: 10px;
		padding-right: 10px;
		background-color: #fff;
	}

	.segmented-control {
		margin-bottom: 15px;
	}

	.button-group {
		margin-top: 15px;
		display: flex;
		justify-content: space-around;
	}

	.form-item {
		display: flex;
		align-items: center;
	}

	.button {
		display: flex;
		align-items: center;
		height: 35px;
		margin-left: 10px;
	}
</style>