<template>
	<view class="page-container uni-column">
		<view class="carrier-info uni-column">
			<view class="carrier-code uni-row">
				<text>箱号</text>
				<text style="margin-left: 24rpx;">{{auxiliaryDayworkItem.carrierName}}</text>
			</view>
			<view class="info-row uni-row">
				<view class="label">批次号</view>
				<view class="value">{{ auxiliaryDayworkItem.lotCode }}</view>
			</view>
			<view class="info-row uni-row">
				<view class="label">产品描述</view>
				<view class="value">{{ auxiliaryDayworkItem.product.description }}</view>
			</view>
			<view class="info-row uni-row">
				<view class="label">生产工序</view>
				<view class="value">{{ auxiliaryDayworkItem.process.processAlias }}</view>
			</view>
			<view class="info-row uni-row">
				<view class="label">辅助工序</view>
				<view class="value">{{ auxiliaryDayworkItem.auxiliaryProcess.name }}</view>
			</view>
			<view class="info-row uni-row">
				<view class="label">投产数量</view>
				<view class="value">{{ auxiliaryDayworkItem.prodNum }}</view>
			</view>
		</view>

		<!-- 废品信息 -->
		<view class="title unfit-title uni-row">
			<text>报工信息</text>
		</view>
		<view class="unfit-container">
			<view class="unfit-item-container uni-column" v-for="(item, index) in oldUnfitInfos" :key="index">
				<view class="resu uni-row">
					<view class="label">检查标准</view>
					<view class="value">{{ item.checkStandard }}</view>
				</view>
				<view class="resu uni-row">
					<view class="label">检查结果</view>
					<view class="value">{{ item.checkResult }}</view>
				</view>
				<view class="resu uni-row">
					<view class="label">超差范围</view>
					<view class="value">{{ item.exceedLimits }}</view>
				</view>
				<view class="resu uni-row">
					<view :class="'label'">检查量</view>
					<view class="number value">{{ item.examiningNum }}</view>
					<view :class="'label'">不良品量</view>
					<view class="value">{{ item.disqualificationNum }}</view>
					<view :class="'label'">废品量</view>
					<view class="value">{{ item.rejectNum }}</view>
				</view>
			</view>
			<view class="unfit-item-container uni-column" v-for="(item, index) in unfitInfos" :key="index">
				<view style="position: absolute; top: 10rpx; right: 10rpx;">
					<!-- <view class="add-btn" v-if="editable()"
						style="height: 80rpx;background-color: #393cfc;color: #ffffff;text-align: center;justify-content: center;align-items: center;border-radius: 8rpx;"
						@click="() => addReject(item, index)">废品信息</view> -->
					<button v-if="editable()" @click="() => addReject(item, index)" size="mini" type="primary"
						style="z-index: 50;">废品信息</button>
				</view>
				<view class="resu uni-row">
					<view class="label">报工人</view>
					<view class="value">{{ item.dayworkItem.nickName }}</view>
				</view>
				<view class="resu uni-row">
					<view class="label">开始时间</view>
					<view class="value">{{ item.dayworkItem.startTime }}</view>
				</view>
				<view class="resu uni-row">
					<view class="label">结束时间</view>
					<view class="value">{{ item.dayworkItem.endTime }}</view>
				</view>
				<view class="resu uni-row">
					<!-- <view :class="!editable() ? 'label' : ''">投产数量</view>
					<view class="number value">{{ item.prodNum }}</view> -->
					<view :class="!editable() ? 'label' : ''">合格数量</view>
					<view class="value">{{ item.qualifiedNum }}</view>
					<view :class="!editable() ? 'label' : ''">废品量</view>
					<!-- <input v-if="editable()" class="number" type="number" @blur="rejectNumberChange"
						v-model="item.rejectNum" placeholder="" /> -->
					<view class="value">{{ item.rejectNum }}</view>
				</view>
				<view v-if="index < (unfitInfos.length - 1)"
					style="height: 1px; width: 100%; background-color: burlywood;"></view>
			</view>
		</view>
		<!-- 报工部分 -->
		<view class="daywork-container uni-column unfit-item-container">
			<view class="result uni-row">
				<view class="label">废品总数</view>
				<view class="value" style="margin-left: 10px;">{{ auxiliaryDayworkItem.rejectNum }}</view>

			</view>
			<view class="half-result uni-row">
				<view class="label">合格数量</view>
				<input v-if="editable()" class="number" type="number" v-model="auxiliaryDayworkItem.qualifiedNum"
					placeholder="" style="width: 140rpx" />
				<view v-else class="value">{{ auxiliaryDayworkItem.qualifiedNum }}</view>
			</view>
			<view class="remark uni-row">
				<view class="label">备注</view>
				<textarea v-if="editable()" v-model="auxiliaryDayworkItem.remark" />
				<view v-else class="value">{{ auxiliaryDayworkItem.remark }}</view>
			</view>

			<view class="btns-container uni-row">
				<view v-if="editable()" class="finished-btn" @click="endWork">结束报工</view>
				<view v-if="editable()" class="pause-btn" @click="pauseWork">暂停报工</view>
			</view>
		</view>
		<dialog-reject ref="dialogRejectRef" @resflushItem="handleResFlushItem"></dialog-reject>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		getCurrentInstance

	} from 'vue'
	import {
		onLoad,
		onReady,
		onUnload,
		onShow
	} from '@dcloudio/uni-app'
	import {
		store
	} from '@/store/index.js'
	import {
		getAuxiliaryDayworkItemById,
		finishedDaywork,
		pauseDaywork
	} from '@/api/business/auxiliaryDaywork.js'
	const lot = ref({})
	const unfitInfos = ref([]) //废品信息
	const oldUnfitInfos = ref([])
	const isEventTriggered = ref(false); // 创建一个标志位
	// 创建一个引用来存储最后一次请求的时间戳
	const lastRequestTimestamp = ref(0);
	const currentItem = ref(null)
	const dialogRejectRef = ref(null)
	const consultations = ref([]) //咨询信息
	const auxiliaryDayworkItem = ref({
		remark: "",
		rejectNum: 0,
		examiningNum: 0,
		status: 0,
		product: {},
		process: {},
		auxiliaryProcess: {}
	})
	const initStatus = ref(0)
	const editable = () => {
		// if (store.userInfo.permissions.some(item => item === 'business:outsourcedInspection:edit')) {
		// 	return true
		// }
		if (initStatus.value == 0 || initStatus.value == 1) {
			if (auxiliaryDayworkItem.value.creatorId == store.userInfo.userId) {
				return true
			}
		}
		// if (auxiliaryDayworkItem.value.firstUpdaterId == store.userInfo.userId) {
		// 	return true
		// }
		return false
	}

	const consul = [{
		value: 0,
		text: "待确认",
		type: "color: #fcab53"
	}, {
		value: 2,
		text: "合格",
		type: "color: #55ff7f"
	}, {
		value: 1,
		text: "不合格",
		type: "color: #ff0c2c"
	}]

	const range = [{
		value: 0,
		text: "待确认",
		type: "color: #fcab53"
	}, {
		value: 1,
		text: "合格",
		type: "color: #55ff7f"
	}, {
		value: 2,
		text: "不合格",
		type: "color: #ff0c2c"
	}]

	/***************************** 页面生命周期函数 *****************************/

	onMounted(() => {
		const instance = getCurrentInstance().proxy
		const eventChannel = instance.getOpenerEventChannel();
		eventChannel.on('outsourcedInspectionFrom', function(data) {
			console.log('outsourcedInspectionFrom', data)
			if (data && data.data) {
				auxiliaryDayworkItem.value.lot = data.data;

			}
		})

	})

	onShow(() => {
		if (store.auxiliaryDaywork != null) {
			uni.showLoading({
				title: '加载中'
			});
			auxiliaryDayworkItem.value = store.auxiliaryDaywork
			getAuxiliaryDayworkItemById(auxiliaryDayworkItem.value).then(res => {
				console.log("res", res);
				if (res.code == 200) {
					auxiliaryDayworkItem.value = res.data;
					initStatus.value = res.data.status
					unfitInfos.value = res.data.rejectList.map(e => ({
						...e,
						rejectNum: e.rejectNum == null ? 0 : e.rejectNum
					}));
					console.log("res", res);
					uni.hideLoading();
					// getInspecion();
				} else {
					uni.showToast({
						icon: 'none',
						title: res.msg,
						duration: 2000
					})
				}
			});
		}
	})

	/***************************** 定义了一些方法 *****************************/
	//咨询文本
	function selectText(item) {
		for (var i = 0; i < consul.length; i++) {
			if (item.status == consul[i].value) {
				return consul[i].text
			}
		}
	}


	//打开电子图纸
	function handleDrawingMenu() {
		var outsourceOrderDetailId = encodeURIComponent(auxiliaryDayworkItem.value.outsourceOrderDetailId);
		var lotCode = encodeURIComponent(auxiliaryDayworkItem.value.lot.lotCode);
		// 构建查询参数字符串
		var queryParam = `param1=${outsourceOrderDetailId}&param2=${lotCode}`;

		// 使用模板字符串构建完整的URL
		var navigateUrl = `/pages/outsourcedDrawingMenu/index?${queryParam}`;

		// 导航到指定页面
		uni.navigateTo({
			url: navigateUrl
		});

	}
	const rejectNumberChange = () => {
		let sumReject = 0
		let sumDisqualificationNum = 0
		let sumExaminingNum = 0
		unfitInfos.value.forEach(v => {
			sumReject += (v.rejectNum != null && !isNaN(v.rejectNum) ? Number(v.rejectNum) : 0)
			sumDisqualificationNum += (v.disqualificationNum != null ? Number(v.disqualificationNum) : 0)
			sumExaminingNum += (v.examiningNum != null ? Number(v.examiningNum) : 0)
			// v.qualifiedNum = Number(v.prodNum) - Number(v.rejectNum)
		})
		auxiliaryDayworkItem.value.rejectNum = sumReject
		auxiliaryDayworkItem.value.disqualificationNum = sumDisqualificationNum
		auxiliaryDayworkItem.value.examiningNum = sumExaminingNum
		console.log(auxiliaryDayworkItem.value)
	}

	//结束报工按钮
	function endWork() {
		let unf = unfitInfos.value;
		// for (var i = 0; i < unfitInfos.value.length; i++) {
		// 	if (unf[i].rejectNum > unf[i].prodNum) {
		// 		uni.showToast({
		// 			icon: 'none',
		// 			title: '废品量不能大于合格量'
		// 		})
		// 		return
		// 	}
		// }
		if(auxiliaryDayworkItem.value.rejectNum > auxiliaryDayworkItem.value.prodNum) {
			uni.showToast({
						icon: 'none',
						title: '废品总数不能大于投产量'
					})
					return
		}

		let sumReject = 0
		unfitInfos.value.forEach(v => {
			sumReject += v.rejectNum != null ? Number(v.rejectNum) : 0
		})
		auxiliaryDayworkItem.value.rejectNum = sumReject
		endSave();
	}

	// 暂停报工按钮
	function pauseWork() {
		pauseSave()
	}

	function endSave() {
		const currentTime = Date.now();

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

		let pages = getCurrentPages();
		auxiliaryDayworkItem.value.rejectList = unfitInfos.value;
		auxiliaryDayworkItem.value.user = store.userInfo;

		finishedDaywork(auxiliaryDayworkItem.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 pauseSave() {
		const currentTime = Date.now();

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

		pauseDaywork(auxiliaryDayworkItem.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 addReject(row, index) {
		// console.log('reject', row)
		currentItem.value = row
		dialogRejectRef.value.open(row)
	}

	function handleResFlushItem(data) {
		currentItem.value.rejectList = data.filter(e => e.reason != null && e.reason != '')
		let rejectNum = 0
		currentItem.value.rejectList.forEach(l => {
			rejectNum += l.rejectNum != null ? Number(l.rejectNum) : 0
		})
		currentItem.value.rejectNum = rejectNum
		rejectNumberChange()
		// console.log(currentItem.value)
	}
</script>

<style lang="scss">
	.page-container {
		// height: 100%;
		background-color: #ececec;
		font-size: 28rpx;

		>.title {
			font-weight: 700;
			margin: 24rpx 16rpx;
		}
	}

	.carrier-info {
		margin: 32rpx 16rpx 0 16rpx;
		padding: 24rpx;
		background-color: #ffffff;
		border-radius: 8rpx;

		.carrier-code {
			font-size: 32rpx;
			font-weight: 700;
		}

		.info-row {
			margin-top: 16rpx;
			color: #767676;

			.label {
				width: 160rpx;
			}

			.drawing-btn {
				padding: 12rpx 32rpx;
				background-color: #0055ff;
				color: #ffffff;
				border-radius: 12rpx;
				margin-left: auto;
				font-size: 28rpx;
			}

			.value {
				flex: 1;

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

	.unfit-title {
		margin-bottom: 24rpx;
		justify-content: space-between;
		align-items: center;

		text {
			font-size: 28rpx;
			font-weight: 700;
		}

		.add-btn {
			margin-right: 26rpx;
			padding: 12rpx 32rpx;
			background-color: #a4adb3;
			color: #ffffff;
			border-radius: 12rpx;
			font-size: 24rpx;
		}
	}

	.unfit-container {
		padding: 24rpx;
		margin: 0 16rpx;
		background-color: #ffffff;
		border-radius: 12rpx;

		.unfit-item-container {
			position: relative;

			>* {
				margin-bottom: 24rpx;
			}

			.title {
				font-weight: 700;
				justify-content: space-between;
				align-items: center;

				image {
					width: 40rpx;
					height: 40rpx;
				}
			}

			.standard {}

			.resu {
				width: 100%;
				align-items: center;

				input {
					margin-left: 20rpx;
					width: 200rpx;
					height: 56rpx;
					flex: 1;
					border: 1px solid #9f9f9f;
					font-size: 28rpx;
				}

				.label {
					width: 160rpx;
				}

				.value {
					flex: 1;

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

			.result {
				border-bottom: 1px solid #9f9f9f;
				padding-bottom: 32rpx;
				align-items: center;

				.label {
					width: 160rpx;
				}

				.value {
					flex: 1;

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

				input {
					width: 280rpx;
					height: 56rpx;
					border: 1px solid #9f9f9f;
					font-size: 28rpx;

					&.number {
						width: 104rpx;
						text-align: left;
					}
				}
			}

			.half-result {
				border-bottom: 1px solid #9f9f9f;
				padding-bottom: 32rpx;
				align-items: center;

				.label {
					width: 160rpx;
				}

				.value {
					flex: 1;

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

				input {
					width: 140rpx;
					height: 56rpx;
					border: 1px solid #9f9f9f;
					font-size: 28rpx;

					&.number {
						text-align: left;
					}
				}
			}
		}

		.unfit-item-container:last-child {
			.result {
				border-bottom: none;
				padding-bottom: 0;
			}
		}
	}

	.consultation-container {
		margin: 0 16rpx;
		padding: 24rpx;
		background-color: #ffffff;
		border-radius: 8rpx;

		.consultation-item-container {
			margin-bottom: 24rpx;
			border-bottom: 2px solid #888888;
			padding-bottom: 24rpx;
		}

		.consultation-item-container:last-child {
			margin-bottom: 0;
			border-bottom: 0;
			padding-bottom: 0;
		}

		.question,
		.answer {
			.label {
				justify-content: space-between;
				margin-bottom: 16rpx;
				font-weight: 700;
			}

			.content {
				line-height: 40rpx;
			}
		}

		.answer {
			margin-top: 24rpx;
		}
	}

	.daywork-container {
		margin-top: 24rpx;
		padding: 24rpx;
		background-color: #ffffff;
		border: 1px solid #bcbcbc;

		.result {
			align-items: center;

			.label {
				width: 112rpx;
			}

			input {
				flex: 1;
				height: 56rpx;
				border: 1px solid #9f9f9f;
				font-size: 28rpx;
				text-align: center;

			}
		}

		.half-result {
			align-items: center;

			.label {
				width: 112rpx;
			}

			input {
				width: 20px;
				height: 56rpx;
				border: 1px solid #9f9f9f;
				font-size: 28rpx;
				text-align: center;

				&.number {
					width: 104rpx;
					text-align: left;
				}
			}
		}

		.remark {
			margin-top: 24rpx;

			.label {
				width: 112rpx;
			}

			textarea {
				flex: 1;
				border: 1px solid #9f9f9f;
				height: 168rpx;
			}
		}

		.btns-container {
			margin-top: 24rpx;

			.finished-btn {
				display: flex;
				flex: 1;
				height: 80rpx;
				background-color: #fc6565;
				color: #ffffff;
				text-align: center;
				justify-content: center;
				align-items: center;
				border-radius: 8rpx;
			}

			.pause-btn {
				display: flex;
				flex: 1;
				height: 80rpx;
				background-color: #393cfc;
				color: #ffffff;
				text-align: center;
				justify-content: center;
				align-items: center;
				border-radius: 8rpx;
			}

			.question-btn {
				width: 80rpx;
				align-items: flex-end;

				image {
					width: 48rpx;
					height: 48rpx;
				}

				text {
					font-size: 24rpx;
				}
			}
		}
	}
</style>