<template>
	<view class="page-container uni-column">
		<view class="lot-info uni-column">
			<view class="lot-code uni-row">
				<text>批次号</text>
				<text style="margin-left: 24rpx;">{{ dayworkItem.lotCode }}</text>
			</view>
			<view class="product-info">
				产品描述: {{ dayworkItem.productDescription }}
			</view>
			<view class="product-info">
				原材料厂家: {{ dayworkInfo.furnaceNoInfo.factory }}
			</view>
			<view class="product-info">
				投产数量: {{ dayworkItem.prodNum }}
			</view>
		</view>

		<!-- 不合格信息 -->
		<view class="title unfit-title uni-row">
			<text>不合格信息</text>
			<view v-if="Number(dayworkItem.status) < 3" class="add-btn" @click="handleAddUnfit">添加</view>
		</view>
		<view class="unfit-container">
			<view class="unfit-item-container uni-column" v-for="(item, index) in unfitInfos" :key="index">
				<view class="title uni-row">
					<text>检查标准-{{ item.checkStandard }}</text>
					<uni-icons v-if="Number(dayworkItem.status) < 3" type="trash" size="24" color="#fc6565"
						@click="handleDelUnfit(index)" />
				</view>
				<!-- <view class="standard">检查标准：{{ item.checkStandard }}</view> -->
				<view class="result uni-row">
					<view class="label">检查结果</view>
					<input v-if="Number(dayworkItem.status) < 3" v-model="item.reason" placeholder="请输入检查结果" />
					<span v-else>{{ item.reason }}</span>
					<view class="label" style="text-align: right; padding-right: 16rpx;">数量</view>
					<input v-if="Number(dayworkItem.status) < 3" class="number" type="number" v-model="item.rejectNum"
						@blur="rejectNumberChange" />
					<span v-else>{{ item.rejectNum }}</span>
				</view>
			</view>
		</view>

		<!-- 咨询部分 -->
		<view class="title">咨询</view>
		<view class="consultation-container uni-column">
			<view class="consultation-item-container" v-for="(item, index) in consultations" :key="index">
				<view class="question uni-column">
					<view class="label uni-row">
						<text>问题描述</text>
						<text :style="{ color: showStatusColor(item.status) }">{{ showStatus(item.status) }}</text>
					</view>
					<view class="content">{{ item.content }}</view>
				</view>
				<!-- <view v-if="item.answer !== ''" class="answer"
					style="margin-top: 24rpx; padding-top: 24rpx; border-top: 1px dotted #aaaaaa;">
					<view class="label">回复</view>
					<view class="content">{{ item.answer }}</view>
				</view> -->
			</view>
		</view>

		<!-- 报工部分 -->
		<view class="daywork-container">
			<view class="result uni-row">
				<view class="label">合格量</view>
				<input v-if="Number(dayworkItem.status) < 3" type="number" placeholder="请输入合格量"
					v-model="dayworkItem.qualifiedNum" />
				<span v-else>{{ dayworkItem.qualifiedNum }}</span>
				<view class="label" style="text-align: right; padding-right: 24rpx">废品量</view>
				<input v-if="Number(dayworkItem.status) < 3" :disabled="true" type="number" placeholder="请输入废品量"
					v-model="dayworkItem.rejectNum" />
				<span v-else>{{ dayworkItem.rejectNum }}</span>
			</view>
			<view class="remark uni-row">
				<view class="label">备注</view>
				<textarea v-if="Number(dayworkItem.status) < 3" v-model="dayworkItem.remark" />
				<span v-else>{{ dayworkItem.remark }}</span>
			</view>

			<view class="btns-container uni-row">
				<!-- 最后一步完成不能更换载具 -->
				<view v-if="dayworkItem.daywork != null && dayworkItem.daywork.status != 2" class="bottom-btn left-btn "
					@click="handleChangeCarrier">
					更换载具</view>
				<view v-if="checkFinishable()&&Number(dayworkItem.status) < 3" class="finished-btn"
					@click.stop="handleFinishDaywork">结束报工</view>
				<view v-if="!checkFinishable()&&Number(dayworkItem.status) < 3" class="pause-btn"
					@click.stop="handleUpdateDaywork">暂停</view>
				<view v-if="Number(dayworkItem.status) < 3" class="question-btn uni-column"
					@click.stop="handleAddConsultation">
					<uni-icons type="headphones" size="24" />
					<text>咨询</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue'
	import {
		onMounted,
		getCurrentInstance
	} from 'vue';
	import {
		getSortingDayworkItem,
		saveConsult,
		finish,
		update
	} from '@/api/business/sortDaywork.js'
	import {
		onLoad,
		onReady,
		onUnload,
		onShow
	} from '@dcloudio/uni-app'
	import {
		store
	} from '@/store/index.js'

	const isEventTriggered = ref(false); // 创建一个标志位
	const unfitInfos = ref([])
	const consultations = ref([])
	const dayworkInfo = ref({})
	// 创建一个引用来存储最后一次请求的时间戳
	const lastRequestTimestamp = ref(0);
	const dayworkItem = ref({})

	/***************************** 页面生命周期函数 *****************************/
	onShow(() => {

	})
	onMounted(() => {
		const instance = getCurrentInstance().proxy
		const eventChannel = instance.getOpenerEventChannel();

		eventChannel.on('acceptDataFromOpenerPage', function(data) {
			if (data && data.data) {
				dayworkInfo.value = data.data
				init({
					id: data.data.id
				})
			} else {
				let reqParam = {
					id: dayworkInfo.value.id
				}
				init(reqParam);
			}
		})
	})

	/***************************** 定义了一些方法 *****************************/
	const init = (data) => {
		console.log("dayworkInfo", dayworkInfo.value);
		// 获取当前报工信息
		getSortingDayworkItem(data).then(res => {
			console.log(res)
			if (res.code === 200) {
				dayworkItem.value = res.data
				console.log(dayworkItem.value)
				if (dayworkItem.value.qualifiedNum === 0 && dayworkItem.value.rejectNum === 0) {
					dayworkItem.value.qualifiedNum = res.data.prodNum
				}
				consultations.value = res.data.consults
				unfitInfos.value = res.data.rejectList
			} else {
				uni.showToast({
					icon: none,
					title: res.message
				})
			}
		})
	}
	const addUnfitInfo = (data) => {
		console.log(data)
		if (data.index > unfitInfos.value.length) {
			const info = {
				inspectionInstructionId: data.id,
				title: data.title,
				standard: data.standard,
				checkStandard: data.standard,
				type: data.type,
				reason: ''
			}
			unfitInfos.value.push(info)
		}
	}
	const addConsultation = (data) => {
		const info = {
			dayworkItemId: dayworkItem.value.id,
			content: data.content,
			userId: store.userInfo.userId,
			nickName: store.userInfo.nickName,
			dayworkId: dayworkItem.value.dayworkId,
			productionPlandetailId: dayworkItem.value.productionPlandetailId,
			productionPlanDetailSubDetailId: dayworkItem.value.productionPlanDetailSubDetailId,
			lotId: dayworkItem.value.lotId,
			lotCode: dayworkItem.value.lotCode,
			productId: dayworkItem.value.productId,
			productDescription: dayworkItem.value.productDescription,
			technologicalProcessId: dayworkItem.value.technologicalProcessId,
			technologicalProcessDetailId: dayworkItem.value.technologicalProcessDetailId,
			processId: dayworkItem.value.processId,
			processAlias: dayworkItem.value.process.processAlias,
			technicianId: dayworkItem.value.technicianId
		}
		saveConsult(info).then(res => {
			if (res.code === 200) {
				consultations.value = res.data
				console.log(consultations.value)
			} else {
				uni.showToast({
					icon: 'none',
					title: res.message
				})
			}
		})
		isEventTriggered.value = true; // 更新标志位状态
		// consultations.value.push(info)
	}

	/***************************** 定义了一些事件 *****************************/
	// 添加不合格信息
	const handleAddUnfit = () => {
		// 监听事件
		uni.$once('addUnfitInfoEvent', (data) => {
			addUnfitInfo(data)
		})
		uni.navigateTo({
			url: "/pages/sorting/options",
			success: (res) => {
				// 通过eventChannel向被打开页面传送数据
				res.eventChannel.emit('acceptDataFromOpenerPage', {
					data: dayworkItem.value,
					index: unfitInfos.value.length
				})
			}
		})
	}
	// 删除不合格信息
	const handleDelUnfit = (index) => {
		let tempInfo = unfitInfos.value[index]
		console.log(tempInfo)
		uni.showModal({
			title: '提示',
			content: '确定删除该项？',
			success: function(res) {
				if (res.confirm) {
					dayworkItem.value.rejectNum = dayworkItem.value.rejectNum - tempInfo.rejectNum
					dayworkItem.value.qualifiedNum = parseInt(dayworkItem.value.qualifiedNum) + parseInt(
						tempInfo.rejectNum)
					unfitInfos.value.splice(index, 1)
				} else if (res.cancel) {
					return
				}
			}
		})
	}

	/* 更换载具*/
	function handleChangeCarrier(item) {
		// uni.$once('refreshQuickReport', () => {
		// 	init()
		// })
		store.dayworkInfo = null
		uni.navigateTo({
			url: "/pages/changeBox/index",
			success: function(res) {
				// 通过eventChannel向被打开页面传送数据
				res.eventChannel.emit('sortingFromOpenerPage', {
					data: dayworkItem.value
				})
			}
		})
	}

	// 添加不合格信息
	const handleAddConsultation = () => {
		isEventTriggered.value = false; // 更新标志位状态
		// 监听事件
		uni.$once('addConsulttationEvent', (data) => {
			if (!isEventTriggered.value) {
				// 如果事件尚未触发，则执行事件触发逻辑
				addConsultation(data)
			}

		})
		uni.navigateTo({
			url: "/pages/sorting/consultation",
			success: (res) => {
				// 通过eventChannel向被打开页面传送数据
				res.eventChannel.emit('acceptDataFromOpenerPage', {
					data: dayworkItem.value
				})
			}
		})
	}
	const checkFinishable = () => {
		if (consultations.value.findIndex(v => v.status === 0) >= 0) {
			return false
		} else {
			return true
		}
	}
	const showStatus = (status) => {
		// console.log(status)
		switch (status) {
			case 0:
				return '未确认'
			case 1:
				return '不合格'
			case 2:
				return '合格'
			default:
				return ''
		}
	}

	const showStatusColor = (status) => {
		// console.log(status)
		switch (status) {
			case 0:
				return '#fcab53'
			case 1:
				return '#fc044f'
			case 2:
				return '#1deb19'
			default:
				return ''
		}
	}
	const rejectNumberChange = () => {
		let sumReject = 0
		unfitInfos.value.forEach(v => {
			sumReject += v.rejectNum == null ? 0 : Number(v.rejectNum)
		})
		dayworkItem.value.rejectNum = sumReject
		dayworkItem.value.qualifiedNum = dayworkItem.value.prodNum - sumReject
		console.log(dayworkItem.value)
	}

	const validHandle = () => {
		for (let i = 0; i < unfitInfos.value.length; i++) {
			const e = unfitInfos.value[i]
			if (e.rejectNum == null || e.rejectNum == 0) {
				uni.showToast({
					icon: 'none',
					title: `第${i + 1}条不合格信息未输入不合格数量`
				})
				return false
			}
		}

		if (!dayworkItem.value.qualifiedNum) {
			uni.showToast({
				icon: 'none',
				title: "合格数不能为空",
				duration: 2000
			})
			return false;
		}

		if (dayworkItem.value.qualifiedNum < 0) {
			uni.showToast({
				icon: 'none',
				title: "合格数不能为负数，请检查不合格信息后提交",
				duration: 2000
			})
			return false;
		}
		return true
		// unfitInfos.value.forEach((e, i) => {
		// 	if (e.name)
		// })
	}

	const handleFinishDaywork = () => {
		if (!validHandle()) {
			return
		}

		const saveData = {
			rejectList: unfitInfos.value,
			consult: consultations.value,
			id: dayworkItem.value.id,
			prodNum: dayworkItem.value.prodNum,
			rejectNum: dayworkItem.value.rejectNum,
			qualifiedNum: dayworkItem.value.qualifiedNum,
			remark: dayworkItem.value.remark
		}
		const currentTime = Date.now();

		// 检查是否已经过去了 2 秒
		if (currentTime - lastRequestTimestamp.value < 2000) {
			// 如果在 2 秒 内已经点击，那么不执行
			uni.showToast({
				icon: 'none',
				title: `请勿重复点击`,
				duration: 2000
			})
			return;
		}
		finish(saveData).then(res => {
			if (res.code === 200) {
				uni.navigateBack()
			} else {
				uni.showToast({
					icon: 'none',
					title: res.message
				})
			}
		})
	}
	const handleUpdateDaywork = () => {
		if (!validHandle()) {
			return
		}
		const saveData = {
			rejectList: unfitInfos.value,
			consult: consultations.value,
			id: dayworkItem.value.id,
			prodNum: dayworkItem.value.prodNum,
			rejectNum: dayworkItem.value.rejectNum,
			qualifiedNum: dayworkItem.value.qualifiedNum,
			remark: dayworkItem.value.remark
		}
		update(saveData).then(res => {
			if (res.code === 200) {
				uni.$emit("formBack")
				uni.navigateBack()
			} else {
				uni.showToast({
					icon: 'none',
					title: res.message
				})
			}
		})

	}
</script>

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

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

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

		.lot-code {
			font-size: 32rpx;
			font-weight: 700;
			margin-bottom: 16rpx;
		}

		.product-info {
			font-size: 28rpx;
			color: #9f9f9f;
		}
	}

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

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

		.add-btn {
			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 {}

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

				.label {
					flex: 1;
				}

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

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

		.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;
			}
		}

		.remark {
			margin-top: 24rpx;

			.label {
				width: 112rpx;
			}

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

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

			.bottom-btn {
				display: flex;
				flex: 1;
				height: 80rpx;
				background-color: #5555ff;
				color: #ffffff;
				text-align: center;
				justify-content: center;
				align-items: center;
				border-radius: 8rpx;
				margin-right: 10rpx;

				&.left-btn {
					background-color: rgba(85, 85, 255, 1.0);
				}

				&.right-btn {
					margin-left: 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: #55d90d;
				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>