<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['FEnchaseNo']" 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="inputMaterial" disabled />
					</uni-forms-item> -->
					<uni-forms-item label="盘点数量" name="FCheckNum">
						<uni-easyinput type="number" v-model="item['FCheckNum']" placeholder="盘点数量" />
					</uni-forms-item>
				<!-- 	<uni-forms-item label="剩余数量" v-if="showRemainingQuantity">
						<uni-easyinput disabled v-model="remainingQuantity" placeholder="" />
					</uni-forms-item> -->
					<!-- <uni-forms-item label="即时库存数量" name="FInventoryQty" v-if="showFInventoryQty">
						<uni-easyinput disabled v-model="InventoryQtyValue" placeholder="即时库存数量" />
					</uni-forms-item>
					<uni-forms-item label="生产车间" name="FWorkShopId.fname" v-if="showWorkShop">
						<uni-easyinput disabled v-model="item['FWorkShopId.fname']" />
					</uni-forms-item>
					<uni-forms-item label="仓位" name="FStockLocId.FF102029.fname" v-if="showLocation">
						<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: '请输入实发数量',
							}, {
								validateFunction: function(rule, value, data, callback) {
									if (value < 0) {
										callback('实际作业数量不能小于0')
									}
									return true
								}
							}

						]
					},
					FRMREALQTY: {
						rules: [{
								required: true,
								errorMessage: '请输入实际作业数量',
							}, {
								validateFunction: function(rule, value, data, callback) {
									if (value < 0) {
										callback('实际作业数量不能小于0')
									}
									return true
								}
							}

						]
					},
					FRealQty: {
						rules: [{
								required: true,
								errorMessage: '请输入实际作业数量',
							}, {
								validateFunction: function(rule, value, data, callback) {
									if (value < 0) {
										callback('实际作业数量不能小于0')
									}
									return true
								}
							}

						]
					},
					FSumActualQty: {
						rules: [{
								required: true,
								errorMessage: '请输入实际作业数量',
							}, {
								validateFunction: function(rule, value, data, callback) {
									if (value < 0) {
										callback('实际作业数量不能小于0')
									}
									return true
								}
							}

						]
					},
				},
			};
		},
		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' || this.formId === 'STK_OEMInStockRETURN') {
					return Math.round((this.item["FInventoryQty"] - this.item["FQty"]) * 100) / 100;
				}
				if (this.formId === 'SAL_OUTSTOCK') {
					return Math.round((this.item["FInventoryQty.LT"] - this.item["FRealQty"]) * 100) / 100;
				}
			},
			fieldName() {
				if (this.formId === 'LT_PRD_PMCWorkBench' || (this.formId === 'SP_PickMtrl' && uni.getStorageSync(
						"fbillType") !== "B")) {
					return 'FActualQty';
				} else if (this.formId === 'SP_PickMtrl' && uni.getStorageSync("fbillType") == "B") {
					return 'FSumActualQty';
				} else if (this.formId === 'STK_MisDelivery') {
					return 'FQty';
				} else if (this.formId === 'PUR_MRB') {
					return 'FRMREALQTY';
				} else if (this.formId === 'SAL_OUTSTOCK') {
					return 'FRealQty';
				} else {
					return 'FQty';
				}
			},
			inputFENCHASENUM: {
				get() {
					if (this.formId === 'SP_PickMtrl' && uni.getStorageSync("fbillType") == "B") {
						return this.item["FSumEnchaseNum.LT"];
					} else {
						return this.item["FENCHASENUM.LT"];
					}
				},
				set(value) {
					if (this.formId === 'SP_PickMtrl' && uni.getStorageSync("fbillType") == "B") {
						this.item["FSumEnchaseNum.LT"] = value;
					} else {
						this.item["FENCHASENUM.LT"] = value;
					}
				}
			},
			inputMaterial: {
				get() {
					if (this.formId === 'SP_PickMtrl' && uni.getStorageSync("fbillType") == "B") {
						return this.item["FSumMaterialId.fnumber"];
					} else {
						return this.item["FMaterialId.fnumber"];
					}
				},
				set(value) {
					if (this.formId === 'SP_PickMtrl' && uni.getStorageSync("fbillType") == "B") {
						this.item["FSumMaterialId.fnumber"] = value;
					} else {
						this.item["FMaterialId.fnumber"] = value;
					}
				}
			},
			inputValue: {
				get() {
					if (this.formId === 'LT_PRD_PMCWorkBench' || (this.formId === 'SP_PickMtrl' && uni.getStorageSync(
							"fbillType") !== "B")) {
						return this.item.FActualQty;
					} else if (this.formId === 'SP_PickMtrl' && uni.getStorageSync("fbillType") == "B") {
						return this.item.FSumActualQty;
					} else if (this.formId === 'STK_MisDelivery') {
						return this.item.FQty;
					} else if (this.formId === 'PUR_MRB') {
						return this.item.FRMREALQTY;
					} else if (this.formId === 'SAL_OUTSTOCK') {
						return this.item.FRealQty;
					} else {
						return this.item.FQty;
					}
				},
				set(value) {
					if (this.formId === 'LT_PRD_PMCWorkBench' || (this.formId === 'SP_PickMtrl' && uni.getStorageSync(
							"fbillType") !== "B")) {
						this.item.FActualQty = value;
					} else if (this.formId === 'SP_PickMtrl' && uni.getStorageSync("fbillType") == "B") {
						return this.item.FSumActualQty = value;
					} else if (this.formId === 'STK_MisDelivery' || this.formId === 'STK_OEMInStockRETURN') {
						this.item.FQty = value;
					} else if (this.formId === 'PUR_MRB') {
						this.item.FRMREALQTY = value;
					} else if (this.formId === 'SAL_OUTSTOCK') {
						this.item.FRealQty = value;
					}
				}
			},

			InventoryQtyValue: {
				get() {
					switch (this.formId) {
						case 'SAL_OUTSTOCK':
							return this.item["FInventoryQty.LT"];
						default:
							return this.item.FInventoryQty;
					}
				},
				set(value) {
					switch (this.formId) {
						// case 'LT_PRD_PMCWorkBench':
						// case 'SP_PickMtrl':
						// 	this.item.FActualQty = value;
						// 	break;
						// case 'STK_MisDelivery':
						// case 'STK_OEMInStockRETURN':
						// 	this.item.FQty = value;
						// 	break;
						// case 'PUR_MRB':
						// 	this.item.FRMREALQTY = value;
						// 	break;
						// case 'SAL_OUTSTOCK':
						// 	this.item.FRealQty = value;
						// 	break;
						case 'SAL_OUTSTOCK':
							return this.item["FInventoryQty.LT"] = value;
						default:
							return this.item.FInventoryQty = value;
					}
				}
			},
			showRemainingQuantity() {
				return this.formId !== 'PUR_MRB' && (this.formId === 'SP_PickMtrl' && uni.getStorageSync("fbillType") !=
					"B")
			},
			showFInventoryQty() {
				return this.formId !== 'PUR_MRB' && (this.formId === 'SP_PickMtrl' && uni.getStorageSync("fbillType") !=
					"B")
			},
			showWorkShop() {
				return this.formId !== 'PUR_MRB' && this.formId !== 'SAL_OUTSTOCK' && this.formId !==
					'STK_OEMInStockRETURN'
			},
			showLocation() {
				return this.formId === 'PUR_MRB' || this.formId === 'STK_OEMInStockRETURN'
			},
		},
		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"]||this.item["FSumMaterialId.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)
				if (this.formId === 'SAL_OUTSTOCK') {
					this.item['FInventoryQty.LT'] = secondResponse[0]["FBaseQty"]
				} else {
					this.item['FInventoryQty'] = secondResponse[0]["FBaseQty"]
				}
				let lotFieldName = this.item.hasOwnProperty('FSumLot.FNumber') ? 'FSumLot.FNumber' : 'Flot.FNumber';
				let FAuxPropIdFieldName = this.item.hasOwnProperty('FSumAuxPropId.FF101501.FNumber') ? 'FSumAuxPropId.FF101501.FNumber' : 'FAuxPropId.FF101501.FDATAVALUE';
				let FStockLocIdFieldName = this.item.hasOwnProperty('FSumStockLocId.FF102029.fname') ? 'FSumStockLocId.FF102029.fname' : 'FStockLocId.FF102029.fname';
				this.item[lotFieldName] = firstResponse[0]["FLot.FNumber"];
				this.item[FAuxPropIdFieldName] = secondResponse[0]["FAuxPropId.FF101501.FDATAVALUE"]
				this.item[FStockLocIdFieldName] = 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>