<template>
	<view class='container'>
		<view class='content'>
			<view class='title uni-row'>
				<text>当前箱号</text>
			</view>
			<view
				:class="{ 'uni-row': true,'vehicleList':true,'totalBoxHeight':discardVehicleList.length == 0,'halfBoxHeight':discardVehicleList.length > 0}">
				<view class="vehicleNo uni-row" v-for="(item,index) in newBindList">
					<text>{{item.carrierCode}}</text>
					<text @click="handleDelVehicleNo(item,index)">×</text>
				</view>
			</view>
			<view v-if="discardVehicleList.length > 0"
				:class="{ 'disuseList': true, 'halfDisuseList':discardVehicleList.length > 0}">
				<view class="uni-row" style="align-items: center;justify-content: space-evenly;">
					<view>箱号</view>
					<view>是否废弃</view>
					<view>废弃原因</view>
				</view>
				<view class="vehicleNo uni-row" v-for="(item,index) in discardVehicleList"
					style="align-items: center;justify-content: space-around;">
					<view class="uni-row discardVehicleNo"><text>{{item.carrierCode}}</text>
						<text @click="handleDelDiscardVehicleList(item,index)">×</text>
					</view>
					<view class="uni-row">
						<switch color="#ff0000" style="transform:scale(0.7)" @change="handleSwitchChange(item)" />
					</view>
					<view class="uni-row" v-if="item.checked">
						<uni-easyinput v-if="item.inpShow" v-model="item.abandonmentReason" focus placeholder="请输入废箱原因"
							style="width: 240rpx;"></uni-easyinput>
						<uni-data-select v-else v-model="item.abandonmentReason" :localdata="abanonmentList"
							style="width: 240rpx;" :clear="false"
							@change="abandonmentReasonChange(item)"></uni-data-select>
					</view>
					<!-- 占空位用 -->
					<view class="uni-row" v-if="!item.checked">
						<view style="width: 240rpx;"></view>
					</view>
				</view>
			</view>
		</view>
		<view class='bottom uni-row'>
			<button class='bottom-btn left-btn' @click="handleScanCode">扫码</button>
			<button class='bottom-btn right-btn' type=primary @click="debounce(handleSubmit,300)">提交</button>
		</view>
	</view>
</template>
<script setup>
	import {
		ref
	} from 'vue'
	import {
		onMounted,
		getCurrentInstance
	} from 'vue';
	import {
		onLoad,
		onReady
	} from '@dcloudio/uni-app'
	import {
		getDictInfoByType
	} from '@/api/dict/dict.js'
	import {
		getDayworkCarrierList
	} from '@/api/business/dayworkCarrier.js'
	import {
		saveDayWork
	} from '@/api/business/dayWork.js'
	import {
		store
	} from '@/store/index.js'
	import {
		debounce
	} from '@/utils/common.js'
	import {
		addCarrierReject,
		checkCarrier,
		checkCarrierNew
	} from '@/api/business/carrier.js'


	const bindList = ref([])
	const newBindList = ref([])
	const discardVehicleList = ref([])
	const abanonmentList = ref([])

	let dayWorkInfo = store.dayworkInfo;
	onMounted(() => {
		const instance = getCurrentInstance().proxy
		const eventChannel = instance.getOpenerEventChannel();

		eventChannel.on('sortingFromOpenerPage', function(data) {
			dayWorkInfo = data.data.daywork
			let reqParam = {
				dayworkId: data.data.dayworkId,
				isChanged: 0
			}
			init(reqParam);
			console.log("dayWorkInfo = data.data.daywork", dayWorkInfo);
		})

		eventChannel.on('acceptDataFromOpenerPage', function(data) {
			// console.log('acceptDataFromOpenerPage', data)
			if (data && data.data) {
				dayWorkInfo = data.data.daywork
				init({
					dayworkId: data.data.dayworkId,
					isChanged: 0
				})
			} else {
				let reqParam = {
					dayworkId: dayWorkInfo.id,
					isChanged: 0
				}
				init(reqParam);
			}
		})
		if (store.dayworkInfo != null) {
			let reqParam = {
				dayworkId: dayWorkInfo.id,
				isChanged: 0
			}
			init(reqParam);
		}
	})
	// onLoad((option) => {
	// eventChannel.on('acceptDataFromOpenerPage', function(data) {
	// 	console.log(data)
	// })

	// let reqParam = {
	// 	dayworkId: dayWorkInfo.id,
	// 	isChanged: 0
	// }
	// init(reqParam);
	// })

	function init(data) {
		console.log("data", data)
		getDayworkCarrierList(data).then(res => {
			// console.log(res)
			if (res.code == 200) {
				bindList.value = [...res.rows];
				newBindList.value = res.rows;
			}
		})
		getDictInfoByType('reason_for_abandonment').then((res) => {
			for (var i = 0; i < res.data.length; i++) {
				abanonmentList.value[i] = {
					text: res.data[i].dictLabel,
					value: res.data[i].dictLabel
				}
			}
		})
	}

	function handleSwitchChange(item) {
		item.checked = !item.checked
	}

	function abandonmentReasonChange(item) {
		if (item.abandonmentReason == '其他原因') {
			item.inpShow = true;
		} else {
			item.inpShow = false;
		}
	}

	// function handleSelectRejectReason(item) {
	// 	for (var i = 0; i < abanonmentList.value.length; i++) {
	// 		if(abanonmentList.value[i].value == item.reason ) {
	// 			item.reason = abanonmentList.value[i].text
	// 		}
	// 	}
	// }
	function handleDelVehicleNo(item, index) {
		if (bindList.value.some(carrier => carrier.carrierCode == item.carrierCode)) {
			// console.log(bindList.value)
			newBindList.value.splice(index, 1);
			let discardVehicleInfo = {
				carrierCode: item.carrierCode,
				checked: false,
				reason: '',
				carrierId: item.carrierId,
				isAbandoned: 1,
				operationDate: new Date()
			}
			discardVehicleList.value.push(discardVehicleInfo)
		} else {
			newBindList.value.splice(index, 1);
		}
	}

	function handleDelDiscardVehicleList(item, index) {
		discardVehicleList.value.splice(index, 1)
		newBindList.value.push(item)
		item.inpShow = false;
	}
/*
	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);
				if (!vehicleObj.carrierId || vehicleObj.carrierId == "") {
					uni.showToast({
						icon: "none",
						title: "请扫载具码"
					})
					return;
				}
				for (let i = 0; i < newBindList.value.length; i++) {
					if (newBindList.value[i].carrierId === vehicleObj.carrierId) {
						uni.showToast({
							icon: "none",
							title: "载具已存在"
						})
						return;
					}
				}
				const checkData = {
					...dayWorkInfo,
					dayworkCarriers: newBindList.value,
					newCarrierId: vehicleObj.carrierId
				}
				console.log("dayWorkInfo", dayWorkInfo);
				checkCarrierNew(checkData).then(response => {
					// console.log(response)
					// uni.showToast({
					// 	icon: 'none',
					// 	title: response.msg
					// })
					if (response.code == 200) {
						newBindList.value.push(JSON.parse(ret.resp_result));
					} else {
						uni.showToast({
							icon: 'none',
							title: response.msg
						})
						return;
					}
				}).catch(err => {
					uni.showToast({
						icon: 'none',
						title: '箱码检测检测错误' + err.message
					})
				})
				// checkCarrier(vehicleObj.carrierId).then(response => {
				// 	console.log(response)
				// 	if (response.code == 200) {
				// 		newBindList.value.push(JSON.parse(ret.resp_result));
				// 	} else {
				// 		uni.showToast({
				// 			icon: 'none',
				// 			title: response.msg
				// 		})
				// 		return;
				// 	}
				// })
			}
		);
	}
*/
	function handleScanCode() {
		// 引入原生插件
		const mpaasScanModule = uni.requireNativePlugin("Mpaas-Scan-Module");

		// 调用插件的 mpaasScan 方法
		mpaasScanModule.mpaasScan({
				// 扫码识别类型，参数可多选，qrCode、barCode，
				// 如不设置，默认识别所有扫码类型，可能有些许影响识别效率
				scanType: ["qrCode", "barCode"],
				// 是否隐藏相册，默认false不隐藏
				hideAlbum: false,
			},
			(ret) => {
				let vehicleObj = { carrierCode: ret.resp_result };
				if (!vehicleObj.carrierCode || vehicleObj.carrierCode == "") {
					uni.showToast({
						icon: "none",
						title: "请扫载具码"
					})
					return;
				}
				for (let i = 0; i < newBindList.value.length; i++) {
					if (newBindList.value[i].carrierCode === vehicleObj.carrierCode) {
						uni.showToast({
							icon: "none",
							title: "载具已存在"
						})
						return;
					}
				}
				const checkData = {
					...dayWorkInfo,
					dayworkCarriers: newBindList.value,
					newCarrierCode: vehicleObj.carrierCode
				}
				console.log("dayWorkInfo", dayWorkInfo);
				checkCarrierNew(checkData).then(response => {
					if (response.code == 200) {
						newBindList.value.push(JSON.parse(ret.resp_result));
					} else {
						uni.showToast({
							icon: 'none',
							title: response.msg
						})
						return;
					}
				}).catch(err => {
					uni.showToast({
						icon: 'none',
						title: '箱码检测检测错误' + err.message
					})
				})
			}
		);
	}

	function handleSubmit() {
		let carrierRejectList = []
		for (var i = 0; i < discardVehicleList.value.length; i++) {
			if (discardVehicleList.value[i].checked && discardVehicleList.value[i].abandonmentReason == "") {
				uni.showToast({
					icon: 'none',
					title: '第' + (i + 1) + '条未选择废弃原因'
				});
				return;
			}
			if (discardVehicleList.value[i].checked && discardVehicleList.value[i].abandonmentReason !== "") {
				carrierRejectList.push(discardVehicleList.value[i])
			}
		}
		if (carrierRejectList.length > 0 && newBindList.value.length > 0) {
			addCarrierReject(carrierRejectList).then((response) => {
				if (response.code == 200) {
					uni.showToast({
						icon: 'success',
						title: '操作成功',
					});
				} else {
					uni.showToast({
						icon: 'none',
						title: '添加失败',
					});
				}
			})
		}
		console.log("dayWorkInfo", dayWorkInfo);
		dayWorkInfo.dayworkCarriers = newBindList.value;
		saveDayWork(dayWorkInfo).then(res => {
			if (res.code === 200) {
				uni.showToast({
					icon: 'success',
					title: '添加成功',
				});
				uni.$emit('refreshQuickReport')
				uni.navigateBack({
					delta: 1
				});
			} else {
				uni.showToast({
					icon: 'none',
					title: res.msg,
					duration: 2500
				});
			}
		})
	}
</script>

<style lang="scss">
	.container {
		height: 100%;
		background-color: #f5f5f5;
	}

	.bottom {
		position: fixed;
		right: 0;
		bottom: 0;
		left: 0;
		height: 100rpx;
		padding: 16rpx 24rpx;
		align-items: center;
		background-color: #FFFFFF;
		justify-content: space-between;

		.bottom-btn {
			flex: 1;
			font-size: 28rpx;
			color: #FFFFFF;

			&.left-btn {
				background-color: rgba(0, 226, 166, 1);
			}

			&.right-btn {
				margin-left: 24rpx;
			}
		}
	}

	.content {
		width: 90%;
		height: calc(100% - 100rpx - 100rpx - 80rpx);
		background-color: rgba(255, 255, 255, 1);
		margin: 50rpx auto;
		padding-bottom: 50rpx;
		border-radius: 12rpx;

		.totalBoxHeight {
			height: calc(100% - 20rpx);
		}

		.halfBoxHeight {
			height: 480rpx;
		}

		.halfDisuseList {
			height: calc(100% - 480rpx - 20rpx);
		}

		.vehicleList {
			justify-content: baseline;
			align-content: flex-start;
			flex-wrap: wrap;
			width: 100%;
			//height: 480rpx;
			padding: 0 64rpx;
			overflow: auto;

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

		.disuseList {
			border-top: 2rpx solid #e1e1e1;
			//height: calc(100% - 480rpx - 20rpx);
			overflow: auto;
			width: 90%;
			margin: 0 auto;
			padding-top: 20rpx;
		}
	}

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

	.title {
		margin: 30rpx auto;
		width: 30%;
		font-size: 36rpx;
		font-weight: bold;
	}

	// .btn {
	// 	position: fixed;
	// 	top: 940rpx;
	// 	left: 0;
	// 	right: 0;
	// }

	// .segment {
	// 	width: 280rpx;
	// 	height: 1rpx;
	// 	border: 1px solid rgba(187, 187, 187, 1);
	// }
</style>