<template>
	<!-- <u-navbar title="配送客户扫描" placeholder border=true :autoBack="true" leftIconSize='35'></u-navbar> -->
	<u-navbar title="装车滞留" bgColor='#D3832A' leftIconColor='#ffffff' titleStyle='color:#ffffff' placeholder
		:autoBack="true" leftIconSize='35'></u-navbar>
	<view class="hedtopt">
		<view class="typto">
			<view>配车类型：{{items.type_name}}</view>
			<view>配车状态：{{items.vehicleStatus_name}}</view>
		</view>
		<view class="typto">
			<view>车牌号：{{items.vehicleName}}</view>
			<view>司机：{{items.driverName}}</view>
		</view>
		<view class="typto">
			<view>装卸班组：{{items.loadingTeamName}}</view>
			<view>备货是否完成：{{items.isstock}}</view>
		</view>
		<view class="kehupeison">
			<view>
				<view>配送客户数</view>
				<view>{{items.customersNumber}}</view>
			</view>
			<view>
				<view>订单总数</view>
				<view>{{ordernumber}}</view>
			</view>
			<view>
				<view>计划件数</view>
				<view>{{deliveryNumber}}</view>
			</view>
			<view>
				<view>装车件数</view>
				<view>{{scannedNumber}}</view>
			</view>
			<view>
				<view>滞留数</view>
				<view>{{scannedNumber}}</view>
			</view>
		</view>
	</view>
	<view class="soIntip">
		<u-search searchIconSize=42 placeholder="请输入编码" bgColor='#fff' v-model="keyword" @custom='keyInput'></u-search>
	</view>
	<!-- tabBar选项卡 -->
	<view class="tabBar">
		<view :class="{'tabBar-item': true, 'active': tabBarCode === 1}" @click="handleTabBarCode(1)">
			定制/库存品
		</view>
		<view :class="{'tabBar-item': true, 'active': tabBarCode === 2}" @click="handleTabBarCode(2)">
			零担
		</view>
		<view :class="{'tabBar-item': true, 'active': tabBarCode === 3}" @click="handleTabBarCode(3)">
			托盘
		</view>
	</view>

	<scroll-view class="scoolv" scroll-y="true">
		<!-- 加载动画 -->
		<u-overlay :show="show">
			<u-loading-icon :show="true" size='80' color='#d3832a'></u-loading-icon>
		</u-overlay>
		<!-- 定制品/库存品 -->
		<view v-if='tabBarCode==1' class="content">

			<view class="InfoList transition" v-for="(item,index) in  DataList1" :key='item.id'>
				<view>
					<u-icon name="car" top='5'></u-icon> <text class="title">类型</text><text
						:class="{ 'type1':item.conditions==1,'type2':item.conditions==2,'type3': item.conditions==3 }">{{item.conditions==1?'定制品':item.conditions==2?'库存品':'暂无信息'}}</text>
				</view>
				<view>
					<u-icon name="scan" top='5'></u-icon> <text
						class="title">包条码</text><text>{{item.orderPackageCode}}</text>
				</view>

				<view>
					<u-icon name="grid" top='5'></u-icon> <text class="title">订单自编号</text><text>{{item.orderCode}}</text>
				</view>
				<view>
					<u-icon name="tags" top='5'></u-icon> <text
						class="title">预约单号</text><text>{{item.reservationCode}}</text>
				</view>
				<u-button v-if='item.parameter' @click="RemoveData(item,index)" class="uni-Btn" type="primary" icon="close"
					text="移除"></u-button>
			</view>

			<view v-if='!DataList1.length'>
				<u-empty mode="data" text='暂无定制品/库存品数据' marginTop='30px' textSize='20px' iconSize='50px'
					iconColor='#55aaff'>
				</u-empty>
			</view>


		</view>
		<!-- 零担 -->
		<view v-if='tabBarCode==2'>
			<view class="InfoList" v-for="item in  DataList2" :key='item.id'>
				<view>
					<u-icon name="car" top='5'></u-icon> <text class="title">类型</text><text
						:class="{ 'type1':item.conditions==1,'type2':item.conditions==2,'type3': item.conditions==3 }">{{item.conditions==1?'定制品':item.conditions==2?'库存品':'暂无信息'}}</text>
				</view>
				<view>
					<u-icon name="scan" top='5'></u-icon> <text
						class="title">包条码</text><text>{{item.orderPackageCode}}</text>
				</view>

				<view>
					<u-icon name="grid" top='5'></u-icon> <text class="title">订单自编号</text><text>{{item.orderCode}}</text>
				</view>
				<view>
					<u-icon name="tags" top='5'></u-icon> <text
						class="title">预约单号</text><text>{{item.reservationCode}}</text>
				</view>
				<u-button v-if='item.parameter' @click="RemoveData(item,index)" class="uni-Btn" type="primary" icon="close"
					text="移除"></u-button>
			</view>

			<view v-if='!DataList2.length'>
				<u-empty mode="data" text='暂无零担数据' marginTop='30px' textSize='20px' iconSize='50px' iconColor='#55aaff'>
				</u-empty>
			</view>








		</view>
		<!-- 托盘 -->
		<view v-if='tabBarCode==3'>
			<view class="InfoMax" v-for="(item ,index) in  DataList3" :key='index'>
				<view class="InfoList InfoListTP">
					<view>
						<u-icon name="car" top='5'></u-icon> <text class="title">托盘码</text><text>{{item[0].trayCode}}</text>
					</view>
					<view>
						<u-icon name="scan" top='5'></u-icon> <text
							class="title">托盘名称</text><text>{{item[0].trayName?item[0].trayName:'暂无名称'}}</text>
					</view>
					<view>
						<u-icon name="scan" top='5'></u-icon> <text class="title">托盘数量</text><text>{{item.length}}</text>
					</view>
					<u-button v-if='item[0].parameter' @click="RemoveData(item,index)" class="uni-Btn" type="primary"
						icon="close" text="移除"></u-button>
				</view>
				<!-- 子内容 -->
				<view class="InfoZ">
					<u-collapse>
						<u-collapse-item title='查看包件'>
							<view class="InfoList" v-for="(items,indexs) in  item" :key='items.id'>
								<view>
									<u-icon name="car" top='5'></u-icon> <text class="title">类型</text><text
										:class="{ 'type1':items.conditions==1,'type2':item.conditions==2,'type3': items.conditions==3 }">{{items.conditions==1?'定制品':items.conditions==2?'库存品':'暂无信息'}}</text>
								</view>
								<view>
									<u-icon name="scan" top='5'></u-icon> <text
										class="title">包条码</text><text>{{items.orderPackageCode}}</text>
								</view>

								<view>
									<u-icon name="grid" top='5'></u-icon> <text
										class="title">订单自编号</text><text>{{items.orderCode}}</text>
								</view>
								<view>
									<u-icon name="tags" top='5'></u-icon> <text
										class="title">预约单号</text><text>{{items.reservationCode}}</text>
								</view>
								<u-button v-if='items.parameter' @click="RemoveData(items,indexs,index)" class="uni-Btn"
									type="primary" icon="close" text="移除"></u-button>
							</view>

						</u-collapse-item>
					</u-collapse>
				</view>
			</view>

			<view v-if='!DataList3.length'>
				<u-empty mode="data" text='暂无托盘数据' marginTop='30px' textSize='20px' iconSize='50px' iconColor='#55aaff'>
				</u-empty>
			</view>
		</view>
	</scroll-view>
	<view class="button_container">
		<view class="button_item" @click="SaveData">
			提交
		</view>
	</view>

	<!-- 	<view class="button_container">
		<view class="button_item" @click="showPopUp">
			整托滞留
		</view>
	</view> -->
	<tiplist ref="tiplists"></tiplist>
	<!-- #ifdef APP -->
	<saomiao2 :ishidestop="scanState !== 0"></saomiao2>
	<!-- #endif -->
	<!-- 整托滞留弹窗 -->
	<PopUp ref='PopUpMask'>
		<view class="main">
			123
		</view>
	</PopUp>
</template>

<script lang="ts" setup>
	import {
		deliverycustom,
		deliveryloadingscan,
		$_initRetentionList,
		$_retentionScan,
		$_saveRetentionList,
		$_updateRetentionList,
		$_retentionTrayScan,
	} from '@/api/user.js'
	import {
		onLoad,
		onShow,
		onHide,
		onPullDownRefresh
	} from '@dcloudio/uni-app'
	import { computed, reactive, ref, toRefs } from "vue";
	import useSystemSettingsStore from '@/store/useSystemSettingsStore';
	import { storeToRefs } from 'pinia';
	import loginVue from '../../../pages/login/login.vue';
	import utils from '@/utils/utils.js';
	const { scanState } = storeToRefs(useSystemSettingsStore())
	let details = reactive({
		id: '',
		renderList: [],
		items: {} as any,
		scancode: '',
		authbuts: uni.getStorageSync('authbuts'),
		tabBarCode: 1,
		// 整托滞留弹窗显示
		showTrayRetention: true
	})
	const StatusUpdate = ref(true);//用于判断保存按钮是更新还是新增(默认是没有值的)
	const tiplists = ref(null)
	const PopUpMask = ref(null)
	const keyword = ref(null)//搜索框的参数
	const DataList1 = ref([])//列表数据定制品/库存品
	const DataList2 = ref([])//列表数据零担
	const DataList3 = ref([])//列表数据托盘

	const show = ref(false);
	const OrType = ref(1)//参数类型
	const id = ref(null);//更新数据必要参数
	const transition = ref(false)//动画参数
	onLoad((op) => {
		details.id = op.id
		details.items = JSON.parse(op.item)
		console.log(details.items, '页面参数');
		init(details.items.id)
	})
	// 页面初始化
	function init(val) {
		show.value = true;//开启加载效果
		$_initRetentionList({
			deliveryId: val
		}).then(res => {
			show.value = false;//关闭加载效果
			//重置表单
			DataList1.value = [];
			DataList2.value = [];
			DataList3.value = [];
			console.log(res, '初始化请求返回参数');
			if (res.data == null) {
				StatusUpdate.value = true;//标记为新增数据状态（说明这里没有参数走新增）
				console.log('暂无数据走新增接口');
			} else {
				id.value = res.data.id;//存储ID用于更新使用
				StatusUpdate.value = false;//标记为更新数据状态（说明这里有参数）
				if (res.data.retentionScanVOList) {
					res.data.retentionScanVOList.forEach(item => {
						if (item.scanType == 1) {
							DataList1.value.push(item)//定制品/库存品
						}
						if (item.scanType == 2) {
							DataList2.value.push(item)//零担
						}
						if (item.scanType == 3) {
							DataList3.value.push(item)//托盘
						}
					})


					// 托盘分组
					const groupedData = DataList3.value.reduce((acc, obj) => {
						const key = obj.trayCode;
						if (!acc[key]) {
							acc[key] = [];
						}
						acc[key].push(obj);
						return acc;
					}, {});

					DataList3.value = Object.values(groupedData);

					console.log(DataList3.value, '托盘分组处理');
				}
			}
		})

	}
	// onHide(() => {
	// 	uni.$off('scancodedate')
	// 	console.log("uni", uni)
	// })
	onShow(() => {
		initpage()
		// #ifdef APP
		uni.$off('scancodedate')
		uni.$on('scancodedate', function (code) {
			if (code) {
				console.log(code, '扫码的参数');
				details.scancode = code
				scandata()
				QRcodeScanning(code, OrType.value)
			}
		})
		// #endif
	})
	// 点击搜索按钮
	function keyInput(val) {
		show.value = true;//开启加载效果
		console.log(val, '来自搜索框的值');
		QRcodeScanning(val, OrType.value)
	}
	// 扫码或者输入点击搜索调用此函数
	function QRcodeScanning(val, type) {
		show.value = true;//开启加载效果
		console.log('执行了此函数');
		if (OrType.value == 1 || OrType.value == 2) {	// 定制品/库存品/零担
			$_retentionScan({
				deliveryId: details.items.id,
				barcode: val,
				retentionType: type,
			}).then(res => {
				show.value = false;//关闭加载效果
				console.log(res, '添加获取的值============>');
				console.log(DataList1, '移除之前的值');
				if (res.audio) {
					utils.ttsspke(res.audio)//暂无数据
					return;
				}
				res.data.forEach(item => {
					item.parameter = true;//新增的数据标记为可以移除
					if (item.scanType == 1) {
						DataList1.value.unshift(item)//定制品/库存品
					}
					if (item.scanType == 2) {
						DataList2.value.unshift(item)//零担
					}
					// if (item.scanType == 3) {
					// 	DataList3.value.unshift(item)//托盘
					// }
				})


			})
		} else {
			// 托盘接口
			$_retentionTrayScan({
				deliveryId: details.items.id,
				barcode: val
			}).then(res => {
				show.value = false;//关闭加载效果
				console.log(res, '托盘返回值');
				if (!res.data) {
					utils.ttsspke(res.msg)//暂无数据
					return
				}
				if (res.data.audio) {
					utils.ttsspke(res.data.audio)//暂无数据
					return;
				}
				if (res.data.data.goodsList) {
					res.data.data.goodsList.forEach(item => {
						item.trayCode = res.data.data.trayCode;
						item.parameter = true;//新增的数据标记为可以移除
						item.trayName = res.data.data.trayName;
						item.trayId = res.data.data.trayTypeId;
						item.warehosueId = res.data.data.warehosueId;
						item.warehosueName = res.data.data.warehosueName;
					})


					// 托盘分组
					const groupedData = res.data.data.goodsList.reduce((acc, obj) => {
						const key = obj.trayCode;
						if (!acc[key]) {
							acc[key] = [];
						}
						acc[key].push(obj);
						return acc;
					}, {});

					DataList3.value.unshift(...Object.values(groupedData))

					console.log(DataList3.value, '处理好的托盘');
				}
			})
		}
	}
	// 保存提交
	function SaveData() {
		show.value = true;//开启加载效果
		const tpArray = DataList3.value.reduce((acc, array) => acc.concat(array), []); // 合并托盘数组
		const mergedArray = [...DataList1.value, ...DataList2.value, ...tpArray];
		console.log(mergedArray, '提交处理好的数据');
		let loadingId = uni.getStorageSync('checkvehicle').id
		// StatusUpdate为真说明没有数据走新增接口===否则走更新接口
		if (StatusUpdate.value) {
			$_saveRetentionList({
				deliveryId: details.items.id,
				trainNumber: details.items.trainNumber,
				loadingId: loadingId,
				assembleCarPersonId: details.items.driverId,// 司机ID
				assembleCarPersonName: details.items.driverName,//司机名称
				warehouseRetentionScanDTOS: mergedArray
			}).then(res => {
				console.log(res, '保存成功之后的返回值');
				init(details.items.id)//保存数据之后刷新数据
			})
		} else {
			$_updateRetentionList({
				id: id.value,
				deliveryId: details.items.id,
				warehouseRetentionScanDTOS: mergedArray
			}).then(res => {
				console.log('更新数据后的返回值');
				init(details.items.id)//保存数据之后刷新数据
			})
		}

	}

	// 移除公共函数
	function removeItem(list, index) {
		list.splice(index, 1);
		console.log(DataList3.value, '移除之后的参数');
	};
	// 移除按钮
	function RemoveData(val, indexs, index) {
		// if (OrType.value == 1) {
		// 	removeItem(DataList1.value, indexs)
		// }
		// if (OrType.value == 2) {
		// 	removeItem(DataList2.value, indexs)
		// }
		// if (OrType.value == 3) {                    
		// 	removeItem(DataList3.value, indexs)
		// }

		console.log(val, '点击移除的信息');
		console.log(indexs, '点击移除的下标');
		console.log(index, '点击移除的下标');
	}
	onPullDownRefresh(() => {
		const timer = setTimeout(() => {
			initpage()
			init(details.items.id)
			uni.stopPullDownRefresh()
			clearTimeout(timer)
		}, 500)
	})
	const ordernumber = computed(() => {
		let num = 0
		details.renderList.map(item => {
			num += Number(item.ordNub)
		})
		return num
	})
	const deliveryNumber = computed(() => {
		let num = 0
		details.renderList.map(item => {
			num += Number(item.reservationNum)
		})
		return num
	})
	const scannedNumber = computed(() => {
		let num = 0
		details.renderList.map(item => {
			num += Number(item.loadingNub)
		})
		return num
	})

	async function scandata() {

	}
	async function initpage() {

	}

	// 改变选项卡激活状态
	function handleTabBarCode(code : number) {
		tabBarCode.value = code
		console.log(code);
		if (code == 1) {
			OrType.value = code
		}
		else if (code == 2) {
			OrType.value = code
		} else {
			OrType.value = code
		}
	}

	/**
	 * 显示整托滞留弹出层
	 */
	const showPopUp = () => {
		console.log('PopUpMask :>> ', PopUpMask);
		PopUpMask.value.setDetails({
			// 显示弹出层
			showPopUp: true,
			confirmText: '确定整托',
			height: '60%',
			title: '整托滞留',
			success() {
				console.log('123 :>> ', 123);
			}
		})
	}

	const { items, renderList, tabBarCode } = toRefs(details)
</script>

<style lang="scss" scoped>
	$subjectColor: #D3832A;

	.scoolv {
		width: 100%;
		height: 60vh;
	}

	.hedtopt {
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		background-color: #ffffff;
		padding: 36upx 32upx;
		box-sizing: border-box;

		.typto {
			display: flex;
			align-items: center;
			justify-content: space-between;
			width: 100%;
			font-size: 28upx;
			font-weight: 400;
			color: #092C4D;
			margin-bottom: 20upx;

			&:nth-last-child(1) {
				margin-bottom: 0;
			}

			>view {
				flex: 1;
			}
		}

		.kehupeison {
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: space-around;
			margin-top: 20upx;

			>view {
				display: flex;
				flex-direction: column;
				align-items: center;
				font-size: 28upx;
				font-weight: 400;
				color: #092C4D;

				&:nth-of-type(1) {
					>view:nth-of-type(2) {
						color: #092C4D;
					}
				}

				&:nth-of-type(2) {
					>view:nth-of-type(2) {
						color: #0086F1;
					}
				}

				&:nth-of-type(3) {
					>view:nth-of-type(2) {
						color: #3AD8BC;
					}
				}

				&:nth-of-type(4) {
					>view:nth-of-type(2) {
						color: #FA8C16;
					}
				}

				>view:nth-of-type(2) {
					font-size: 36upx;
					font-weight: 400;
					color: #092C4D;
					margin-top: 20upx;
				}
			}
		}
	}

	// tabBar选项卡
	.tabBar {
		display: flex;
		justify-content: space-evenly;
		background-color: #fff;
		margin-top: 2upx;
		margin-bottom: 10px;
		border-top: 1px solid #dadbde;
		margin-bottom: 2px;

		&-item {
			position: relative;
			flex: 1;
			flex-basis: 0;
			padding: 20upx 0;
			text-align: center;

			&::after {
				content: '';
				position: absolute;
				bottom: 0;
				left: 50%;
				display: block;
				width: 0;
				box-sizing: border-box;
				border: 1upx solid $subjectColor;
				transition: all 0.5s;
			}

			&.active {
				color: $subjectColor;

				&::after {
					left: 0;
					width: 100%;
				}
			}
		}
	}

	// 按钮容器
	.button_container {
		position: fixed;
		width: 100vw;
		bottom: 0;
		display: flex;
		justify-content: space-around;

		.button_item {
			width: 100%;
			text-align: center;
			border-radius: 0.3125rem;
			border-bottom-right-radius: 0;
			border-bottom-left-radius: 0;
			color: #ffffff;
			background-color: #d3832a;
			height: 42px;
			display: flex;
			align-items: center;
			justify-content: center;

		}
	}

	// 搜索框 
	.soIntip {
		display: flex;
		justify-content: space-between;
		width: 100%;
		box-sizing: border-box;
		height: 36px;
		border: 1px solid #d3832a;
		overflow: hidden;
		background-color: #fff;
	}

	.uni-input-placeholder {
		font-size: 16px;
	}

	:deep(.u-search__action) {
		height: 100%;
		background-color: #d3832a;
		display: flex;
		align-items: center;
		justify-content: center;
		width: 80px;
		color: #fff;
	}

	.InfoList {
		display: flex;
		flex-direction: column;
		background-color: #ffffff;
		color: #ccc;
		padding: 6px 4px;
		padding-right: 0;
		width: 100%;
		margin: 0 auto;
		box-sizing: border-box;
		border-radius: 2px;
		margin-bottom: 4px;
		border: 1px solid;
		position: relative;

		uni-view {
			margin-bottom: 4px;
			height: 38px;
			display: flex;
			align-items: center;
		}

		.title {
			margin-right: 3px;
			width: 78px;
			background-color: #ffffff;
			display: inline-block;
			padding: 4px;
			box-sizing: border-box;
			border-radius: 4px;
			display: flex;
			align-items: center;
			color: #000;
		}

		.uni-Btn,
		.uni-BtnS {
			width: 80px;
			height: 29px;
			position: absolute;
			top: 0px;
			right: 0px;
			border-top-left-radius: 0px;
			border-top-right-radius: 0px;
			border-bottom-right-radius: 0px;
			border-bottom-left-radius: 10px;
		}

		.type1,
		.type2,
		.type3 {
			width: 60px;
			height: 20px;
			display: flex;
			align-items: center;
			justify-content: center;
			border-radius: 2px;
			font-size: 14px;
		}

		.type1 {
			background-color: #3ad8bc;
			color: #fff;
		}

		.type2 {
			background-color: #fb8c16;
			color: #fff;

		}

		.type3 {
			background-color: #3c9cff;
			color: #fff;

		}
	}

	.InfoMax {
		position: relative;
	}

	.InfoMax:last-of-type {
		margin-bottom: 42px;

	}

	:deep(.uni-input-input) {
		background-color: transparent;
	}

	:deep(.u-search__content) {
		background-color: #fff !important;
	}

	:deep(uni-page-body) {
		background-color: #fff !important;
	}

	.InfoList:last-child {
		margin-bottom: 42px;
	}

	.uni-BtnS {
		background-color: #ff0000;
		border: 0;
	}

	.u-loading-icon {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
	}

	:deep(.u-collapse-item__content__text) {
		padding: 0;
	}

	.InfoListTP {
		margin-bottom: 0;
	}


	.InfoMax {
		.InfoZ {
			.InfoList:last-child {
				margin-bottom: 10px;
				border-bottom: 1px solid #d3832a;
				padding-bottom: 44px;
				position: relative;
			}

			.InfoList:last-child::after {
				content: "当前托盘到底了...";
				display: block;
				width: 100%;
				position: absolute;
				bottom: 10px;
				left: 0;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 16px;
				color: #d3832a;
			}
		}

	}
</style>