<template>
	<view class="page-container uni-column">
		<view class="search-container uni-row">
			<input type="text" v-model="quer.keyword" placeholder="请输入关键字" />
			<view class="btn uni-row" @click="handleSearch">搜索</view>
			<!-- <uni-icons type="scan" size="24" /> -->
		</view>

		<view class="time-controls" style="margin-top: 10rpx;display: flex;margin-right: 0px;background-color: #ffffff;">
			<view class="uni-row sta">
			<span style="align-items: center;display: flex;font-size: 16px;margin-left: 12rpx;">检查日期:</span>
				<view class="uni-row" style="flex: 1;width: 100%;">
				<input v-model="startTime" type="date" @input="timeSizer" style="flex: 1;width: 100%;" />
				<span style="align-items: center;display: flex;">—</span>
				<input v-model="endTime" type="date" @input="timeSizer" />
				</view>
			</view>
		</view>
		<view class="uni-row" style="margin-top: 10rpx;">
			<view class="scan-btn " style="min-height: 80rpx;" @click.stop="handleAddDeliveryInspection">新增交检</view>
			<view class="scan-btn " style="background-color: #aaaaff;min-height: 80rpx;margin-left: 24rpx;" @click.stop="handleScan">扫码</view>
		</view>
		<view class="daywork-item uni-column" v-for="(item, index) in inspecionList" :key="index"
			@click="handleSelection(item)">
			<view class="lot-code uni-row">
				<text>批次号：{{ item.lotCode }}</text>
				<text :style="selectType(item)">{{ selectText(item) }}</text>
				<text v-if="delable(item)" class="fa fa-trash" style="font-size: 16; color: red;"
					@click.stop="deleteItem(item)"></text>
				<text v-else class="fa fa-trash" style="font-size: 16; color: white;"></text>
			</view>
			<view class="info">
				<view class="info-row uni-row">
					<view class="label">交检箱号：</view>
					<view class="value">{{ item.carrierCode }}</view>
					<view class="label">检察员：</view>
					<view class="value">{{ item.technicianName }}</view>
				</view>
				<view class="info-row uni-row">
					<view class="label">检查数量：</view>
					<view class="value">{{ item.examiningNum }}</view>
					<view class="label">不良品量：</view>
					<view class="value">{{ item.disqualificationNum }}</view>
				</view>
				<view class="info-row uni-row">
					<view class="label">产品描述：</view>
					<view class="value">{{ item.productDescription }}</view>
				</view>
				<view class="info-row uni-row">
					<view class="label">检测载具：</view>
					<view class="value">{{ item.inspectionCarrierCode }}
						{{ item.isInspectionCarrierChanged == 1 ? '(已解绑)' : ''}}
					</view>
					<button class="reporting-tag" size="mini" type="primary"
						@click.stop="changeCheckCarrier(item)">检测载具</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue'
	import {
		getProcessInspecionList,
		getLotInfo,
		delProcessInspection
	} from '@/api/business/processInspection.js'
	import {
		timestampToTime,
		toHHmmss
	} from '@/utils/common.js'
	import {
		onLoad,
		onReady,
		onUnload,
		onShow,
		onReachBottom
	} from '@dcloudio/uni-app'
	import {
		store
	} from '@/store/index.js'
	const keyword = ref('')
	const inspecionList = ref([]); //时间后筛选数组
	const original = ref([]); //原始数组
	const startTime = ref(new Date().toISOString().split("T")[0])
	const endTime = ref(new Date().toISOString().split("T")[0])
	const pageSize = ref(10)
	const pageNum = ref(1)
	const status = ref(true)
	const showPicker = ref(false)
	const range = [{
		value: 0,
		text: "待确认",
		type: "color: #fcab53"
	}, {
		value: 1,
		text: "合格",
		type: "color: #55ff7f"
	}, {
		value: 2,
		text: "不合格",
		type: "color: #ff0c2c"
	}]

	const quer = ref({}) //用于查询


	/***************************** 页面生命周期函数 *****************************/
	onShow(() => {
		getList()
		// uni.showLoading({
		// 	title: '加载中'
		// });
		// quer.value.userId = store.userInfo.userId;
		// quer.value.startTime = startTime.value;
		// getProcessInspecionList(quer.value).then(res => {
		// 	console.log("res", res);
		// 	if (res.code == 200) {
		// 		original.value = res.rows;
		// 		// timeSizer();
		// 		uni.hideLoading();
		// 		// uni.hideLoading();
		// 	}
		// });
	})
	onReachBottom(()=>{
			console.log(status.value)
			if(status.value) {
			pageNum.value += 1
			quer.value.pageNum = pageNum.value
			quer.value.pageSize = pageSize.value
			getProcessInspecionList(quer.value).then(res =>{
			 const existingIds = new Set(inspecionList.value.map(item => item.id));
			
			  // 过滤出那些不在 existingIds 中的项，即新数据
			  const newRows = res.rows.filter(row => !existingIds.has(row.id));
			
			  // 如果有新数据，将其添加到 listData
			  if (newRows.length > 0) {
				inspecionList.value = inspecionList.value.concat(newRows);
				original.value = original.value.concat(newRows);
			  } else {
				// 如果没有新数据，更新状态表示没有更多数据
				status.value = false;
			  }
			})
			}
		})
	

	/***************************** 定义了一些方法 *****************************/

	function getList() {
		uni.showLoading({
			title: '加载中'
		});
		pageNum.value = 1
		quer.value.startTime = startTime.value;
		quer.value.endTime = endTime.value;
		quer.value.deptId = store.curDeptDetails.deptId
		quer.value.type = "deliveryInspection"
		quer.value.pageNum = pageNum.value
		quer.value.pageSize = pageSize.value
		if(!checkTime(quer.value.startTime,quer.value.endTime)) {
			console.log("777")
			uni.showToast({
				icon: 'none',
				title: "开始日期不能大于结束日期",
				duration:2000
			})
		}else{
				getProcessInspecionList(quer.value).then(res => {
			console.log("res", res);
			if (res.code == 200) {
				original.value = res.rows;
				inspecionList.value = res.rows;
				uni.hideLoading();
			}
		});
		}	
	}
	function handleSearch() {
		pageNum.value = 1
		status.value = true
		getList()
	}
	//扫码
	function handleScan() {
		// 引入原生插件
		const mpaasScanModule = uni.requireNativePlugin("Mpaas-Scan-Module");
		if (mpaasScanModule) {
			// 调用插件的 mpaasScan 方法
			mpaasScanModule.mpaasScan({
					// 扫码识别类型，参数可多选，qrCode、barCode，
					// 如不设置，默认识别所有扫码类型，可能有些许影响识别效率
					scanType: ["qrCode", "barCode"],
					// 是否隐藏相册，默认false不隐藏
					hideAlbum: false,
				},
				(ret) => {
					console.log(ret);
					let vehicleObj = {
						carrierCode: ret.resp_result
					};
					if (!vehicleObj.carrierCode || vehicleObj.carrierCode == "") {
						uni.showToast({
							icon: "none",
							title: "请扫载具码",
							duration: 1000
						})
						return;
					}
					quer.value.keyword = vehicleObj.carrierCode
					getList()
				}
			);
		} else {
			// 测试时用
				quer.value.keyword = ""
				getList()
		}
	}
	//判断开始时间是否大于结束时间
	function checkTime(time1,time2){
		let date1 = new Date(startTime.value);
		let date2 = new Date(endTime.value);
		if(date1 > date2) {
			return false
		}
		return true
		}
	function delable(item) {
		return true
		// if (store.userInfo.permissions.some(item => item === 'business:outsourcedInspection:remove') && item.status == 0) {
		// 	return true
		// }
		// if (item.creatorId === userId.value && item.status == 0) {
		// 	return true
		// }
		// return false
	}
	const changeCheckCarrier = (item) => {
		const openItem = {
			dayworkId: item.dayworkId,
			processInspectionId: item.id,
			daywork: item
		}
		uni.navigateTo({
			url: "/pages/changeInspectionBox/index",
			success: function(res) {
				// 通过eventChannel向被打开页面传送数据
				res.eventChannel.emit('outsourceFromOpenerPage', {
					data: openItem
				})
			}
		})
	}
	const deleteItem = (item) => {
		uni.showModal({
			title: '确认',
			content: '确认删除该交检么?',
			success: function(res) {
				if (res.confirm) {
					delProcessInspection(item.id).then(res => {
						if (res.code === 200) {
							console.log(res)
							getList()
						} else {
							uni.showToast({
								icon: 'none',
								title: res.msg
							})
						}
					})
	
				} else if (res.cancel) {
					uni.showToast({
						title: '已取消',
						icon: 'none'
					})
				}
			}
		})
	}

	//时间筛选，暂时注释，使用搜索向
	function timeSizer() {
		if(!checkTime(startTime.value,endTime.value)) {
			console.log("777")
			uni.showToast({
				icon: 'none',
				title: "开始日期不能大于结束日期",
				duration:2000
			})
		}else{
			getList()	
		}
		
	}

	// 筛选函数
	const filterSameDayItems = (inspectionList, startTime) => {

		// 使用filter方法筛选出与startTime同一天的元素
		const filteredList = inspectionList.filter(item => {
			// 将数组中每个元素的date属性转换为不包含时分秒的字符串
			const itemDateString = item.createTime.split(' ')[0];
			// 比较两个日期字符串是否相同
			return itemDateString === startTime;
		});
		return filteredList;
	};


	function isSameDate(date1, date2) {
		// 使用Date对象的toISOString()方法来格式化日期，并去除时分秒部分
		const formatDate = (date) => date.toISOString().split('T')[0];

		// 比较两个日期的年月日部分是否相同
		return formatDate(date1) === formatDate(date2);
	}

	//查看序捡详情
	function handleSelection(item) {
		store.processInspection = item;
		uni.navigateTo({
			url: '/pages/deliveryInspection/form'
		})
	}

	//状态文本
	function selectText(item) {
		for (var i = 0; i < range.length; i++) {
			if (item.status == range[i].value) {
				return range[i].text
			}
		}
	}

	//状态样式
	function selectType(item) {
		for (var i = 0; i < range.length; i++) {
			if (item.status == range[i].value) {
				return range[i].type
			}
		}
	}

	const addProcessInspection = (data) => {
		const info = {
			title: data.title,
			standard: data.standard,
			result: '',
			number: 1
		}
		unfitInfos.value.push(info)
	}

	/***************************** 定义了一些事件 *****************************/
	// 新增巡检
	const handleAddDeliveryInspection = () => {
		store.processInspection = null
		uni.navigateTo({
			url: '/pages/deliveryInspection/scan'
		})
	}
</script>

<style lang="scss">

	.time-controls {
		.title {
			margin: 20% auto 40% auto;
		}

		.sta {
			justify-content: flex-start;
		    align-items: center;

			input {
				border: 1rpx solid gray;
				border-radius: 8rpx;
				width: 100%;
				// width: 400rpx;
				flex:1;
				height: 64rpx;
			}
		}
	}

	.page-container {
		//height: 100%;
		background-color: #ececec;
		font-size: 28rpx;
		padding: 24rpx;
		box-sizing: border-box;
	}

	.search-container {
		border-radius: 12rpx;
		align-items: center;

		input {
			flex: 1;
			background-color: #ffffff;
			height: 64rpx;
			box-sizing: border-box;
			padding: 0 16rpx;
		}

		.btn {
			width: 120rpx;
			height: 64rpx;
			background-color: #1684FC;
			justify-content: center;
			font-size: 24rpx;
			color: #ffffff;
			justify-content: center;
			align-items: center;
		}
	}

	.scan-btn {
		height: 64rpx;
		color: #ffffff;
		background-color: #f47c3c;
		align-items: center;
		justify-content: center;
		border-radius: 8rpx;
		flex:1;
	}

	.daywork-item {
		padding: 24rpx;
		background-color: #ffffff;
		margin-top: 24rpx;
		border-radius: 8rpx;

		.lot-code {
			align-items: center;
			justify-content: space-between;
			font-weight: 700;
		}

		.info {
			font-size: 24rpx;
			color: #767676;

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

				.label {
					width: 120rpx;
				}

				.value {
					flex: 1;
				}
			}
		}
	}
</style>