<template>
	<view class="page-container uni-column">
		<view class="consultation-container uni-column">
			<view class="title uni-row">箱号：{{ lot.carrierCode }}</view>
			<view class="info-row uni-row">
				<view class="label">批次号</view>
				<view class="value">{{ lot.lotCode }}</view>
			</view>
			<view class="info-row uni-row">
				<view class="label">产品描述</view>
				<view class="value">{{ lot.productDescription }}</view>
			</view>
			<!-- 选择被辅助工序 -->
			<view class="info-row uni-row">
				<view class="label">生产工序</view>
				<view class="value">
					<uni-data-select style="width: 70%;" v-model="lot.technologicalProcessDetailId"
						:localdata="processes" @change="handleProcessChange"></uni-data-select>
				</view>
			</view>
			<view class="info-row uni-row">
				<view class="label">辅助工序</view>
				<view class="value">
					<uni-data-select style="width: 70%;" v-model="lot.auxiliaryProcessId"
						:localdata="auxiliaryProcesses" @change="handleAuxiliaryProcessChange"></uni-data-select>
				</view>
			</view>
			<!-- 选择辅助工序 -->
			<view class="info-row uni-row">
				<view class="label">投产数量</view>
				<view class="value">{{ lot.pudName }}</view>
			</view>
			<view class="info-row uni-row">
				<view class="label">批次箱号</view>
				<view class="value">{{ lot.allCarrierName }}</view>
			</view>
			<!-- <input type="text" v-model="carrierCode" placeholder="请输入箱号或检查载具号" /> -->
			<view class="btn uni-row" style="background-color: #ff5555;" @click.stop="handleScanCode">
				<uni-icons type="scan" size="16" style="color: #ffffff; margin-right: 8rpx;" />
				<text>扫描箱码或载具二维码</text>
			</view>
			<!-- <view class="btn uni-row" style="margin-top: 48rpx;" @click.stop="handleConfirm">箱码确定</view>
			<view class="btn uni-row" style="background-color: #26d01d;" @click.stop="handleSave">保存
			</view> -->
			<view class="btn uni-row" style="margin-top: 48rpx;" @click.stop="handleSave">保存</view>
		</view>
		<!-- <dialog-processInspection ref='selectProcessInspection'
			@handleSelectProcessInspection='handleSelectProcessInspection'></dialog-processInspection> -->
		<dialog-daywork-choice ref="selectDaywork" @handleSelectDaywork="handleSelectDaywork"></dialog-daywork-choice>
		<QrScanner v-if="showQrCodeReader" @decode="onDecodeHandler" @close="qrReaderClose" />
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue'
	import {
		onLoad,
		onReady,
		onUnload,
		onShow
	} from '@dcloudio/uni-app'
	import QrScanner from '../vueQrCode/index.vue'
	import {
		saveOutsourcedInspecion,
		getCarrierInfo,
		getLotOutsourcedInfo
	} from '@/api/business/processInspection.js'
	import {
		getInfoByCarrierCode,
		getAuxiliaryProcesses,
		saveAuxiliaryDayowrk
	} from '@/api/business/auxiliaryDaywork.js'
	import {
		store
	} from '../../store';
	import {
		debounce
	} from '../../utils/common';
	const carrierCode = ref('')
	const lot = ref({})
	const query = ref({})
	const showQrCodeReader = ref(false);
	const selectDaywork = ref(null)
	const lastRequestTimestamp = ref(0);
	const auxiliaryProcesses = ref([])
	const processes = ref([])

	// 页面生命周期函数
	onLoad(() => {})
	//H5扫码器回调
	function onDecodeHandler(data) {
		showQrCodeReader.value = false;
		const result = {
			carrierCode: data,
			processCode: ''
		}
		if (!result.carrierCode || result.carrierCode == "") {
			uni.showToast({
				icon: "none",
				title: "请扫载具码",
				duration: 1000
			})
			return
		}
		//判断该箱是否绑定批次

		result.processCode = store.outsourcedCode;
		// console.log(result.processCode)
		/************************ 根据扫码查询到的数据和需要检查的工序查询信息 ************************/
		getInfoByCarrierCode(result).then(response => {
			if (response.code == 200) {
				// 判断是哪种返回值 假设是想信息则给lot附检查箱信息
				// 假设是dayworkCarriers 则 判断是几个批次，假设为多批，则弹出选择框。
				if (response.data != null) {
					if (response.data.length > 1) {
						query.value = result;
						selectDaywork.value.open(response.data)
					} else {
						// console.log(response)
						uni.showLoading({
							title: '加载中'
						})
						uni.hideLoading()
						lot.value = response.data[0]
						processes.value = lot.value.processSequence.map(v => ({
							text: v.processAlias,
							value: v.technologicalProcessDetailId,
							...v
						}))
					}
				}
			} else {
				uni.showToast({
					icon: 'none',
					title: response.msg,
					duration: 2000
				})
			}
		}).catch(err => {
			uni.showToast({
				icon: 'none',
				title: err.message,
				duration: 2000
			})
		})
	}


	//H5扫码器关闭
	function qrReaderClose() {
		showQrCodeReader.value = false;
	}

	const handleScanCode = () => {
		showQrCodeReader.value = true;
		// 引入原生插件
		// const mpaasScanModule = uni.requireNativePlugin("Mpaas-Scan-Module");
		// if (mpaasScanModule) {
		// 	// 调用插件的 mpaasScan 方法
		// 	mpaasScanModule.mpaasScan({
		// 			// 扫码识别类型，参数可多选，qrCode、barCode，
		// 			// 如不设置，默认识别所有扫码类型，可能有些许影响识别效率
		// 			scanType: ["qrCode", "barCode"],
		// 			// 是否隐藏相册，默认false不隐藏
		// 			hideAlbum: false,
		// 		},
		// 		(ret) => {
		// 			console.log(ret)
		// 			const result = {
		// 				carrierCode: ret.resp_result,
		// 				processCode: ''
		// 			}
		// 			if (!result.carrierCode || result.carrierCode == "") {
		// 				uni.showToast({
		// 					icon: "none",
		// 					title: "请扫载具码",
		// 					duration: 1000
		// 				})
		// 				return
		// 			}
		// 			//判断该箱是否绑定批次

		// 			result.processCode = store.outsourcedCode;
		// 			// console.log(result.processCode)
		// 			/************************ 根据扫码查询到的数据和需要检查的工序查询信息 ************************/
		// 			getInfoByCarrierCode(result).then(response => {
		// 				if (response.code == 200) {
		// 					// 判断是哪种返回值 假设是想信息则给lot附检查箱信息
		// 					// 假设是dayworkCarriers 则 判断是几个批次，假设为多批，则弹出选择框。
		// 					if (response.data != null) {
		// 						if (response.data.length > 1) {
		// 							query.value = result;
		// 							selectDaywork.value.open(response.data)
		// 						} else {
		// 							// console.log(response)
		// 							uni.showLoading({
		// 								title: '加载中'
		// 							})
		// 							uni.hideLoading()
		// 							lot.value = response.data[0]
		// 							processes.value = lot.value.processSequence.map(v => ({
		// 								text: v.processAlias,
		// 								value: v.technologicalProcessDetailId,
		// 								...v
		// 							}))
		// 						}
		// 					}
		// 				} else {
		// 					uni.showToast({
		// 						icon: 'none',
		// 						title: response.msg,
		// 						duration: 2000
		// 					})
		// 				}
		// 			}).catch(err => {
		// 				uni.showToast({
		// 					icon: 'none',
		// 					title: err.message,
		// 					duration: 2000
		// 				})
		// 			})
		// 		}
		// 	)
		// } else {
		// 	const result = {
		// 		carrierCode: '001135',
		// 		processCode: store.outsourcedCode
		// 	}
		// 	getInfoByCarrierCode(result).then(response => {
		// 		if (response.code == 200) {
		// 			// 判断是哪种返回值 假设是想信息则给lot附检查箱信息
		// 			// 假设是dayworkCarriers 则 判断是几个批次，假设为多批，则弹出选择框。
		// 			if (response.data != null) {
		// 				if (response.data.length > 1) {
		// 					query.value = result;
		// 					selectDaywork.value.open(response.data)
		// 				} else {
		// 					// console.log(response)
		// 					uni.showLoading({
		// 						title: '加载中'
		// 					})
		// 					uni.hideLoading()
		// 					lot.value = response.data[0]
		// 					processes.value = lot.value.processSequence.map(v => ({
		// 						text: v.processAlias,
		// 						value: v.technologicalProcessDetailId,
		// 						...v
		// 					}))
		// 				}
		// 			}
		// 		} else {
		// 			uni.showToast({
		// 				icon: 'none',
		// 				title: response.msg,
		// 				duration: 2000
		// 			})
		// 		}
		// 	}).catch(err => {
		// 		uni.showToast({
		// 			icon: 'none',
		// 			title: err.message,
		// 			duration: 2000
		// 		})
		// 	})
		// }
	}

	//选择批号弹窗带回
	function handleSelectDaywork(data) {
		console.log("带回", data)
		lot.value = data
		processes.value = lot.value.processSequence.map(v => ({
			text: v.processAlias,
			value: v.technologicalProcessDetailId,
			...v
		}))
		uni.hideLoading()
		// query.value.lotCode = data
		// uni.showLoading({
		// 	title: '加载中'
		// });
		// getLotOutsourcedInfo(query.value).then(res => {
		// 	if (res.code == 200) {
		// 		lot.value = res.data;
		// 		console.log(res)
		// 		lot.value.carrierCode = query.value.carrierCode
		// 		carrierCode.value = query.value.carrierCode;
		// 		// console.log("res", res);
		// 		uni.hideLoading();
		// 	} else {
		// 		uni.showToast({
		// 			icon: 'none',
		// 			title: res.msg,
		// 			duration: 2000
		// 		})
		// 	}
		// });
	}

	function checkSave() {
		// uni.showToast({
		// 	title: 'lotCode:' + lot.value.lotCode + 'inspectionCarrierId: ' + lot.value.inspectionCarrierId,
		// 	icon: 'none'
		// })
		if (lot.value.lotCode == '' || lot.value.lotCode == null) {
			debounce(handleScanCode, 700)
		}
		if (lot.value.inspectionCarrierId == null || lot.value.inspectionCarrierId == '') {
			debounce(handleScanCode, 700)
		}
	}

	// 确定后，将批次id，批次号，传递过去
	const handleConfirm = () => {
		/** 因为调试时无法扫码所以暂时用确定方法代替扫码 **/
		/** 调用查询方法查询箱号信息 **/
		/**
		 * 如果返回的是载具信息表示这是检查载具，将载具的id和code存到lot.inspectionCarrierId和lot.inspectionCarrierCode中
		 * 如果返回的是1条dayweorCarrier的载具绑定信息则调用查询方法查询批次信息
		 * 如果返回的是多条dayweorCarrier的载具绑定信息，则表示这是一箱多批需要调用选择批号弹窗在processInspection文件scan229行有对应的方法
		 * 
		 * */
		if (lot.carrierCode || carrierCode.value !== "") {
			// lot.value.carrierCode = carrierCode.value
			const result = {
				// ...lot.value
				carrierCode: carrierCode.value
			}
			result.processCode = store.outsourcedCode;
			// console.log(result.processCode)
			getInfoByCarrierCode(result).then(response => {
				if (response.code == 200) {
					// 判断是哪种返回值 假设是想信息则给lot附检查箱信息
					// 假设是dayworkCarriers 则 判断是几个批次，假设为多批，则弹出选择框。
					if (response.data != null) {
						if (response.data.length > 1) {
							query.value = result;
							selectDaywork.value.open(response.data)
						} else {
							// console.log(response)
							uni.showLoading({
								title: '加载中'
							})
							uni.hideLoading()
							lot.value = response.data[0]
							processes.value = lot.value.processSequence.map(v => ({
								text: v.processAlias,
								value: v.technologicalProcessDetailId,
								...v
							}))
						}
					}
				} else {
					uni.showToast({
						icon: 'none',
						title: response.msg,
						duration: 2000
					})
				}
			}).catch(err => {
				uni.showToast({
					icon: 'none',
					title: err.message,
					duration: 2000
				})
			})
		} else {
			uni.showToast({
				icon: 'none',
				title: "请输入箱号",
				duration: 2000
			})
			return;
		}
	}

	const getProcesses = () => {
		getAuxiliaryProcesses().then(res => {
			if (res.code == 200) {
				auxiliaryProcesses.value = res.data.map(v => ({
					text: v.name,
					value: v.id,
					...v
				}))

				console.log(auxiliaryProcesses.value)
			}
		})
	}

	const handleSave = () => {
		// 判断是否已有批次和检查载具
		if (lot.value.lotCode == '' || lot.value.lotCode == null) {
			uni.showToast({
				icon: 'none',
				title: "请先扫载具码",
				duration: 2000
			})
			return
		}

		if (lot.value.technologicalProcessDetailId == null) {
			uni.showToast({
				icon: 'none',
				title: '请先选择生产工序'
			})
			return
		}

		if (lot.value.auxiliaryProcessId == null) {
			uni.showToast({
				icon: 'none',
				title: '请先选择辅助工序'
			})
			return
		}
		// 保存

		const currentTime = Date.now();

		// 检查是否已经过去了 2 秒
		if (currentTime - lastRequestTimestamp.value < 2000) {
			// 如果在 2 秒 内已经点击，那么不执行
			uni.showToast({
				icon: 'none',
				title: `请勿重复点击`,
				duration: 2000
			})
			return;
		}
		lastRequestTimestamp.value = currentTime;

		let pages = getCurrentPages();

		saveAuxiliaryDayowrk({
			productId: lot.value.productId,
			userId: store.userInfo.userId,
			nickName: store.userInfo.nickName,
			userName: store.userInfo.userName,
			deptId: store.curDeptDetails.deptId,
			deptName: store.curDeptDetails.deptName,
			processId: lot.value.currentProcess.id,
			processStepNumber: lot.value.currentProcess.processStepNumber,
			technologicalProcessDetailId: lot.value.technologicalProcessDetailId,
			auxiliaryProcessId: lot.value.auxiliaryProcessId,
			daywork: lot.value
		}).then(res => {
			if (res.code == 200) {
				let index = 0;
				for (let i = 0; i < pages.length; i++) {
					if (pages[i].$page.fullPath == "/pages/auxiliaryDaywork/index") {
						index = pages.length - i - 1;
					}
				}
				console.log("index", index);
				uni.navigateBack({
					delta: index
				});
			} else {
				uni.showToast({
					icon: 'none',
					title: res.msg,
					duration: 2000
				})
			}
		});
	}

	function handleProcessChange() {
		console.log(lot.value.processId)
		// 获取投产数量
		const process = processes.value.find(v => v.technologicalProcessDetailId == lot.value.technologicalProcessDetailId)
		console.log(process)
		const item = lot.value.dayworkItemList.find(e => e.processId == process.id && process.processStepNumber == e
			.processStepNumber)
		console.log(item)
		lot.value.pudName = item.prodNum
		lot.value.currentProcess = process

	}

	function handleAuxiliaryProcessChange() {
		console.log(lot.value.auxiliaryProcessId)
	}

	getProcesses()
</script>

<style lang="scss">
	.page-container {
		height: 100%;
		background-color: #ececec;
		font-size: 28rpx;
		padding: 24rpx;
		box-sizing: border-box;
	}

	.consultation-container {
		background-color: #ffffff;
		padding: 24rpx;
		border-radius: 12rpx;

		.title {
			justify-content: center;
			font-size: 32rpx;
			font-weight: 700;
		}

		.info-row {
			margin-top: 24rpx;

			.label {
				width: 160rpx;
			}

			.value {
				flex: 1;

				textarea {
					flex: 1;
					border: 1px solid #888888;
					box-sizing: border-box;
					padding: 16rpx;
				}
			}
		}

		.btn {
			background-color: #1684fc;
			color: #ffffff;
			border-radius: 8rpx;
			margin: 4rpx 24rpx 24rpx 24rpx;
			height: 64rpx;
			justify-content: center;
			align-items: center;
		}

		input {
			margin: 48rpx 24rpx 0 24rpx;
			height: 64rpx;
			border: 1px solid #888888;
			text-align: center;
		}
	}
</style>