<template>
	<dialog-base ref="baseDialog" title="结束报工">
		<view class="list-container">
			<view class="list-title uni-row">
				<text class="label">合格量</text>
				<input class="input" @input="handleInputQualifiedNum" style="width: 70%;"
					v-model="workInfo.qualifiedNum" placeholder="请输入合格量" />
			</view>
			<view class="list-title uni-row">
				<text class="label">废品信息</text>
				<view class="uni-row" style="justify-content: flex-end;"><text class="label" style="color: blue;"
						@click="handleAddWasteInfo">+添加</text></view>
			</view>
			<view class="list-title uni-row" v-for="(item, index) in wasteInfo">
				<input class="input" @input="handleInputRejectNum" style="width: 20%;" v-model="item.rejectNum"
					placeholder="废品量" />
				<uni-data-select style="margin-left: 40rpx;width: 70%;" v-model="item.reason" :localdata="reasonList"
					@change="handleTenantChange"></uni-data-select>

				<uni-icons class="icon-gear" type="close" size="60" color="red"
					@click="handleDeleteWasteInfo(index)"></uni-icons>
			</view>

			<view class="list-title uni-row">
				<text class="label">当前序是否完成</text><text>否</text>
				<switch class="switch" @change="switchChange" color="rgba(255,85,85,1)" />
				<text>是</text>
			</view>
			<view v-if="showCarrierList && !store.isProPreProcess" class="confirmCarrier">
				<text class="label">确认载具</text>
				<view class="vehicleList uni-row">
					<view v-for="(item,index) in bindList" :key="index"
						:class="{ 'vehicleNo': true, 'uni-row': true, 'blueBorder': item.flag }">
						<text>{{item.carrierCode}}</text>
					</view>
				</view>
			</view>
		</view>
		<view v-if="store.isProPreProcess" class="add-btn-container uni-row">
			<button type="default" class="btn" @click="handlePreFinishReporting">结束报工</button>
		</view>
		<view v-if="!store.isProPreProcess" class="add-btn-container uni-row">
			<button v-if="showCarrierList" type="primary" class="btnScan" @click="handleScanCode">扫码确认载具</button>
			<button type="default" class="btn" @click="handleFinishReporting">结束报工</button>
		</view>
	</dialog-base>
</template>


<script setup>
	import {
		ref,
		getCurrentInstance
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		updateDayWorkItem,
		saveDayWorkItem
	} from "@/api/business/dayWorkItem.js"
	import {
		getDayworkCarrierList
	} from '@/api/business/dayworkCarrier.js'
	import {
		store
	} from '@/store/index.js'
	import {
		timestampToTime,
		toHHmmss
	} from '@/utils/common.js'
	import {
		getDictInfoByType
	} from '@/api/dict/dict.js'
	import {
		getSpecialDeptProcessList
	} from '@/api/business/deptProcess.js'
	import {
		debounce
	} from '@/utils/common.js'

	const baseDialog = ref(null)
	const workInfo = ref({})
	const wasteInfo = ref([])
	const reasonList = ref([])
	const emit = defineEmits(['reset'])
	const showCarrierList = ref(false) // 工序是否完成显示载具列表
	const bindList = ref([])
	const confirmCarrierList = ref([])
	const endFlag = ref(0)
	const specialDeptProcessList = ref([])
	const temp = ref(0) // 保存workInfo.value.qualifiedNum的值(还原用)

	onLoad(() => {
	})

	function open(data, itemListData) {
		console.log(store.isProPreProcess)
		resetPage();
		workInfo.value = {
			...data,
			qualifiedNum: 0
		};
		getSpecialDeptProcessList().then(res => {
			if (res.code == 200) {
				for (let i = 0; i < res.data.length; i++) {
					specialDeptProcessList.value[i] = res.data[i].processId;
				}
			}
			if (specialDeptProcessList.value.includes(workInfo.value.processId)) {
				let sumReject = 0;
				for (let i = 0; i < itemListData.length; i++) {
					sumReject += itemListData[i].rejectNum;
				}
				workInfo.value.qualifiedNum = store.dayworkInfo.processQualifiedNum > 0 ? store.dayworkInfo.processQualifiedNum - sumReject : store.dayworkInfo.oneLotQuantity - sumReject;
				temp.value = workInfo.value.qualifiedNum;sumReject
				console.log(store.dayworkInfo)
			} else {
				workInfo.value.qualifiedNum = 0;
			}
		})
		wasteInfo.value = []
		init();
		baseDialog.value.open()
	}

	function close() {
		baseDialog.value.close()
	}

	function resetPage() {
		workInfo.value = {};
		wasteInfo.value = [];
		reasonList.value = [];
		showCarrierList.value = false;
		bindList.value = [];
		confirmCarrierList.value = [];
		endFlag.value = 0;
	}

	function init() {
		getDictInfoByType("waste_causes").then(res => {
			for (let i = 0; i < res.data.length; i++) {
				reasonList.value[i] = {
					value: res.data[i].dictValue,
					text: res.data[i].dictLabel
				}
			}
		})
		getDayworkCarrierList({
			dayworkId: store.dayworkInfo.id,
			isChanged: 0
		}).then(res => {
			console.log(res)
			if (res.code == 200) {
				bindList.value = res.rows;
				for (let i = 0; i < bindList.value.length; i++) {
					bindList.value[i].flag = false;
				}
			}
		})
	}

	function switchChange(event) {
		if (event.detail.value) {
			workInfo.value.status = "3"
		} else {
			workInfo.value.status = "2"
		}
		showCarrierList.value = event.detail.value;
	}

	function handleInputQualifiedNum() {
		workInfo.value.qualifiedNum = workInfo.value.qualifiedNum.replace(/^-+|[^\d]/g, '');
	}

	function handleInputRejectNum() {
		let sumRejectNum = 0;
		for (let i = 0; i < wasteInfo.value.length; i++) {
			wasteInfo.value[i].rejectNum = wasteInfo.value[i].rejectNum.replace(/^0+|^-|[^\d]/g, '');
			sumRejectNum += Number(wasteInfo.value[i].rejectNum);
		}
		if (temp.value > 0) {
			debounce(function() {
				workInfo.value.qualifiedNum = temp.value;
				workInfo.value.qualifiedNum -= sumRejectNum;
			}, 500)
		}
	}


	function handleScanCode() {
		// 引入原生插件
		const mpaasScanModule = uni.requireNativePlugin("Mpaas-Scan-Module");
		// 调用插件的 mpaasScan 方法
		mpaasScanModule.mpaasScan({
				// 扫码识别类型，参数可多选，qrCode、barCode，
				// 如不设置，默认识别所有扫码类型，可能有些许影响识别效率
				scanType: ["qrCode", "barCode"],
				// 是否隐藏相册，默认false不隐藏
				hideAlbum: false,
			},
			(ret) => {
				let vehicleObj = JSON.parse(ret.resp_result);
				for (let i = 0; i < bindList.value.length; i++) {
					if (vehicleObj.carrierCode == bindList.value[i].carrierCode) {
						if (!bindList.value[i].flag) {
							endFlag.value += 1;
						}
						bindList.value[i].flag = true;
					}
				}
			}
		);
		// uni.scanCode({
		// 	scanType: ['qrCode'], // 条形码扫描
		// 	onlyFromCamera: true, // 只允许相机扫码
		// 	autoZoom: false,
		// 	success: function(res) {
		// 		let vehicleObj = JSON.parse(res.result);
		// 		for (let i = 0; i < bindList.value.length; i++) {
		// 			if (vehicleObj.carrierCode == bindList.value[i].carrierCode) {
		// 				if (!bindList.value[i].flag) {
		// 					endFlag.value += 1;
		// 				}
		// 				bindList.value[i].flag = true;
		// 			}
		// 		}
		// 	}
		// });
	}

	function handlePreFinishReporting(){
		handleSave();
	}
	
	function handleFinishReporting() {
		if (showCarrierList.value) {
			if (endFlag.value >= bindList.value.length) {
				handleSave();
			} else {
				uni.showToast({
					icon: "none",
					title: "请先扫码确认载具"
				})
				return;
			}
		} else {
			handleSave();
		}
	}

	function handleSave() {
		if (!workInfo.value.qualifiedNum) {
			uni.showToast({
				icon: "error",
				title: "请输入合格数",
			})
			return;
		}
		for (let i = 0; i < wasteInfo.value.length; i++) {
			if ((!wasteInfo.value[i].rejectNum && wasteInfo.value[i].reason) ||
				(wasteInfo.value[i].rejectNum && !wasteInfo.value[i].reason) ||
				(!wasteInfo.value[i].rejectNum && !wasteInfo.value[i].reason)) {
				uni.showToast({
					icon: "error",
					title: "请输入废弃数或废弃原因",
					duration: 2000
				})
				return;
			}
		}
		close();
		if (workInfo.value.status != '3') {
			workInfo.value.status = '2';
		}
		workInfo.value.endTime = timestampToTime(new Date());
		workInfo.value.rejectList = wasteInfo.value;
		console.log(workInfo.value)
		saveDayWorkItem(workInfo.value).then(res => {
			if (res.code === 200) {
				uni.showToast({
					icon: 'success',
					title: '操作成功',
				});
				uni.$emit('dayworkItemUpdate');
				baseDialog.value.close();
				workInfo.value.qualifiedNum = null;
			} else {
				uni.showToast({
					icon: 'none',
					title: res.msg
				});
			}
		})
	}

	function handleAddWasteInfo() {
		wasteInfo.value.push({
			rejectNum: '',
			reason: ''
		})
	}

	function handleDeleteWasteInfo(index) {
		wasteInfo.value.splice(index, 1);
		handleInputRejectNum();
	}

	function handleTenantChange() {

	}

	defineExpose({
		open
	})
</script>

<style lang="scss">
	.dialog-body {
		.list-container {
			width: 100%;
			display: flex;
			align-items: flex-start;
			padding: 0 4rpx;

			.list-title {
				width: 100%;
				margin-top: 16rpx;
				height: 64rpx;
				line-height: 64rpx;
				align-items: center;

				.label {
					flex: 1;
					font-size: 32rpx;
				}

				.input {
					width: 40%;
					height: 66rpx;
					padding-left: 10rpx;
					font-size: 22rpx;
					border: 1rpx solid #e1e1e1;
					border-radius: 8rpx;
				}

				.icon-gear {
					font-size: 56rpx;
				}
			}

			.switch {
				margin-top: -8rpx;
				align-items: center;
				transform: scale(0.7);
			}

			.confirmCarrier {
				.label {
					padding-top: 20rpx;
					font-size: 32rpx;
				}

				.vehicleList {
					justify-content: baseline;
					align-content: flex-start;
					flex-wrap: wrap;
					width: 100%;
					height: 120rpx;
					overflow: auto;

					.vehicleNo {
						padding: 0 10rpx;
						margin: 10rpx 20rpx 0 0;
						justify-content: space-between;
						align-items: center;
						width: auto;
						height: 60rpx;
						border: 2rpx solid rgba(213, 213, 213, 1);
						border-radius: 6rpx;
					}

					.blueBorder {
						background-color: #1684fc;
						color: #FFFFFF;
					}

				}
			}


		}

		.add-btn-container {
			margin-top: 32rpx;


			.btn {
				flex: 1;
				background-color: rgba(255, 85, 85, 1);
				color: #FFFFFF;
				margin-left: 5rpx;
				padding: 0;
			}

			.btnScan {
				flex: 1;
				color: #FFFFFF;
				margin-right: 5rpx;
				padding: 0;
			}
		}
	}
</style>