<template>
	<BasicContainer ref='basicContainer' :option="option" :leftClick="option.leftClick">
		<!-- 头部 -->
		<template #head>
			<view class="headtop">
				<view @click='showCalendar' class="inputsr">
					<view class="timeInput">
						{{datatime|| '请选择时间'}}
					</view>
					<view @click.stop.prevent>
						<u-icon @click='showCalendar' style="margin-right: 10upx;" v-if="!datatime" name="calendar"
							color="#999999" size="50"></u-icon>
						<u-icon @click="cleartime" style="margin-right: 10upx;" v-else name="close-circle" color="#999999"
							size="40"></u-icon>
					</view>
				</view>
				<view @click="handleSearch">查询</view>
			</view>

		</template>

		<!-- 主体 -->
		<template #body>
			<scroll-view class="scvmabx" :style="{height: details.scrollheight}" @scrolltolower="reachBottomInitPage"
				scroll-y="true" @touchmove.stop>
				<view class="maxboxs">
					<!-- 					<view class="items" v-for="item in datalist">

					</view> -->
					<template v-for="item in datalist">
						<view class="items">
							<view class="items_row">
								<view>
									车次号：{{item.carsNo}}
								</view>
							</view>

							<view class="items_row">
								<view>
									实际装车/计划装车：{{item.realLoadingNumber + '/' +item.planLoadingNumber}}
								</view>

								<view>
									车型：{{''}}
								</view>
							</view>

							<view class="items_row">
								<view>
									主驾司机：{{item.driverName}}
								</view>

								<view>
									电话：{{item.driverMobile}}
								</view>
							</view>

							<view class="items_row">
								<view>
									发车时间：{{item.startTime}}
								</view>

								<view>
									车牌号：{{item.carNumber}}
								</view>
							</view>

							<view class="items_row">
								线路：{{item.carsLineName}}
							</view>

							<view class="button-container" v-if="Number(item.lastStartCarStatus) === 1
								 && (Number(item.loadStatus) === 10 || Number(item.loadStatus) === 30)">
								<view class="button" style="background-color: #86cad0; width: 60%; margin: 0 auto;"
									@click="handleArriveCarByLoadId(item, 1)">
									到车
								</view>
							</view>

							<view class="button-container" v-else-if="Number(item.lastStartCarStatus) === 1
								&& item.showControl 
								&&(Number(item.loadStatus) === 20 || Number(item.loadStatus) === 40)">
								<view class="">
									<view class="button" @click="handleDetailsByOrder(item, 1)">
										按件入库
									</view>

									<view class="button" @click="handleDetailsByOrder(item, 2)">
										整托入库
									</view>

									<view class="button" @click="handleScanByTray(item)">
										卸分一体
									</view>
								</view>

								<view class="" v-if="item.showTruckLoading">
									<view class="button" @click="gostockuplist(item)">
										按件装车
									</view>

									<view class="button" @click="gostockuplistBytray(item)">
										整托装车
									</view>
								</view>
							</view>

							<!-- 标签 -->
							<view class="tag">
								网点到达
							</view>
						</view>
					</template>
				</view>
			</scroll-view>
		</template>

	</BasicContainer>

	<l-calendar v-model:value="show" :initStartDate='date[0]' :initEndDate='date[1]' @hide='showCalendar'
		@change="onConfirm"></l-calendar>
	<!-- #ifdef APP -->
	<saomiao2 :ishidestop="scanState !== 0"></saomiao2>
	<!-- #endif -->
</template>

<script lang="ts" setup>
	import {
		postArriveUnloadPageList,
		warehouseTrayTypeorderScanTrayCode,
		postArriveCarByLoadId
	} from '@/api/user.js'
	import {
		onLoad,
		onShow,
		onHide,
	} from '@dcloudio/uni-app'
	import { nextTick, reactive, ref, toRefs, watchEffect } from "vue";
	import utils from '@/utils/utils.js'
	import useSystemSettingsStore from '@/store/useSystemSettingsStore';
	import { storeToRefs } from 'pinia';
	const { scanState } = storeToRefs(useSystemSettingsStore())
	// 组件配置
	const option = reactive({
		leftClick() {
			uni.reLaunch({
				url: "/pages/index/index"
			})
		},
		// 标题
		title: '到车列表',
		// 下拉刷新回调函数
		async pullDownRefreshInitPage() {
			// 重置页码
			details.pageNum = 1
			// 重置渲染列表
			details.datalist = []
			// 重置渲染列表数据请求是否结束状态
			option.isEnd = false
			// 重置是否有数据
			option.haveData = true
			await initpage()
			if (datalist.value.length === 0) {
				uni.showToast({
					title: '暂时没有数据',
					icon: 'error'
				})
				option.haveData = false
			}
			if (option.isEnd) {
				return uni.showToast({
					icon: 'success',
					title: '数据已加载完毕'
				})
			}
			return null
		},
		// 触底加载回到函数
		reachBottomInitPage: async () => { return null },
		haveData: true,
		isEnd: false
	})

	// 组件实例
	const basicContainer = ref()

	// 添加防抖函数
	let antiShake : any = null
	// 触底加载
	function reachBottomInitPage() {
		try {
			// 数据请求完毕, 不再请求
			if (option.isEnd) {
				return uni.showToast({
					icon: 'success',
					title: '数据已加载完毕'
				})
			}
			console.log('antiShake :>> ', antiShake);
			if (antiShake) {
				uni.hideLoading()
				// 清空定时器
				clearTimeout(antiShake)
				return antiShake = null
			}
			// 显示Loading, 并阻止点击屏幕
			uni.showLoading({
				title: '正在加载',
				mask: true
			})
			antiShake = setTimeout(async () => {
				// 触发触底回调
				details.pageNum += 1
				const res = await initpage()
				// 关闭loading效果
				uni.hideLoading()
				// 清空定时器
				antiShake = null
				// 当返回数据数组长度小于每页数量时, 数据请求完毕
				if (res.data && res.data.records.length < details.pageSize) {
					uni.showToast({
						title: '已经到底了',
						icon: 'success'
					})
					clearTimeout(antiShake)
					return option.isEnd = true
				}
				clearTimeout(antiShake)
			}, 500)
		} catch (err) {
			//TODO handle the exception
			console.log('err :>> ', err);
		}
	}

	let details = reactive({
		show: false,
		/** 时间 */
		datatime: '',
		/** 当前页码 */
		pageNum: 1,
		/** 页数 */
		pageSize: 20,
		/** 渲染列表数据 */
		datalist: [],
		/** 扫描的码值 */
		scancode: '',
		scrollheight: '80vh'
	})

	onLoad(() => {
		date.value[0] = (uni as any).$u.timeFormat((new Date().valueOf() - 1000 * 60 * 60 * 24 * 3), 'yyyy-mm-dd')
		date.value[1] = (uni as any).$u.timeFormat((new Date().valueOf()), 'yyyy-mm-dd')
		details.datatime = date.value[0] + ' 至 ' + date.value[1]
		// #ifdef APP
		utils.ttsspke('请选择配载计划')
		// #endif
	})

	onShow(async () => {
		// #ifdef APP
		// 初始化关闭监听
		uni.$off('scancodedate')
		// init()
		uni.$on('scancodedate', function (code) {
			console.log('code :>> ', code);
			if (code) {
				console.log(code);
				details.scancode = code
				scandata()
			}
		})
		// #endif

		await nextTick()
		basicContainer.value.startPullDownRefresh()
		details.scrollheight = await utils.getViewDistanceFormTop('.scvmabx')
	})
	// onHide(() => {
	// 	uni.$off('scancodedate')
	// })
	/** 时间 */
	const date = ref<(string | number)[]>([])

	async function scandata() {
		let data = {
			trayCode: details.scancode
		}
		let res = await warehouseTrayTypeorderScanTrayCode(data)
		if (res.code !== 200) return

		console.log('res', res);
		if (Number(res.data.isHasData) === 0) {
			utils.ttsspke('请选择分拣方式')
			uni.setStorageSync('trayCodeType', res.data.data)
			uni.navigateTo({
				url: '/pagesHome/pages/ScanSortingType/ScanSortingType?trayCode=' + details.scancode
			})
		} else {
			uni.navigateTo({
				url: '/pagesHome/pages/OrderSortingDetail/OrderSortingDetail?trayCode='
					+ res.data.data.trayCode + '&trayType='
					+ res.data.data.trayType
			})
		}
	}
	async function initpage() {
		try {
			let submitData = {
				type: '1',
				pageNum: details.pageNum,
				pageSize: details.pageSize,
				createDateStart: date.value[0] || '',
				createDateEnd: date.value[1] || '',
			}
			const res = await postArriveUnloadPageList(submitData)
			if (res.code !== 200) return
			const { code, data } = res
			if (code === 200 && data) {
				// 当前仓库的Id
				const _wareHouseId = uni.getStorageSync('checkname').id

				for (let iterator of data.records) {
					const _endWarehouseIds = iterator.endWarehouseIds.split(',')
					// 是否在当前节点
					iterator.showControl = false
					// 是否为中间节点
					iterator.showTruckLoading = false

					// 查询本仓在任务路线中的节点位置
					const _index = _endWarehouseIds.indexOf(_wareHouseId)

					if (_index !== -1) {
						// 是否在当前节点
						iterator.showControl = true

						// 是否为中间节点
						if (_index !== _endWarehouseIds.length - 1) iterator.showTruckLoading = true
					}
				}
				details.datalist = [...details.datalist, ...data.records]
			}
			if (data && data.pages <= details.pageNum) option.isEnd = true
			console.log('details.datalist :>> ', details.datalist);
			return res
		} catch (err) {
			//TODO handle the exception
			console.log('err :>> ', err);
		}
	}

	const handleSearch = () => {
		basicContainer.value.startPullDownRefresh()
	}

	function showCalendar() {
		details.show = !details.show
	}
	function onConfirm(e : any) {
		console.log(e);
		date.value[0] = e.startDate
		date.value[1] = e.endDate
		details.datatime = date.value[0] + ' 至 ' + date.value[1]

		basicContainer.value.startPullDownRefresh()
	}

	function cleartime() {
		details.datatime = ''
		date.value = []

		basicContainer.value.startPullDownRefresh()
	}

	/** 到车 */
	const handleArriveCarByLoadId = async (item) => {
		try {
			const submitData = {
				loadId: item.id
			}

			const res = await postArriveCarByLoadId(submitData)

			if (res.code !== 200) return
			utils.handleToast('到车成功')
			basicContainer.value.startPullDownRefresh()
		} catch (err) {
			console.log('err :>> ', err);
			//TODO handle the exception
		} finally {

		}
	}

	/** 按件入库 || 整托入库 */
	const handleDetailsByOrder = (item, type) => {
		uni.navigateTo({
			url: '/pagesHome/pages/VehicleArrivalDetails/VehicleArrivalDetails?id=' + item.id + '&type=' + type + '&page=' + 'ArrivalList'
		})
	}

	/** 卸分一体 */
	const handleScanByTray = (item) => {
		uni.navigateTo({
			url: '/pagesHome/pages/VehicleArrivalDetailsByTray/VehicleArrivalDetailsByTray?id=' + item.id + '&carsNo=' + item.carsNo
		})
	}

	/** 按件装车 */
	function gostockuplist(item : any) {
		uni.navigateTo({
			url: '/pagesHome/pages/StowageListDetails/StowageListDetails?id=' + item.id + '&type=' + 1
		})
	}
	/** 按托装车 */
	function gostockuplistBytray(item : any) {
		uni.navigateTo({
			url: '/pagesHome/pages/StowageListDetails/StowageListDetails?id=' + item.id + '&type=' + 2
		})
	}

	const {
		show,
		datatime,
		datalist,
		scancode,
	} = toRefs(details)
</script>

<style lang="scss" scoped>
	.inputsr {
		width: 100%;
		height: 64upx;
		background: #F5F5F6;
		border-radius: 8upx 8upx 8upx 8upx;
		opacity: 1;
		border: 2upx solid #EEEEEE;
		padding: 16upx 18upx;
		box-sizing: border-box;
		padding-right: 0;
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-size: 26upx;
		font-weight: 400;
		color: #092C4D;

		>.timeInput {
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
			flex: 1;
			font-size: 26upx;
		}
	}

	.schbox {
		display: flex;
		align-items: center;
		justify-content: flex-start;
		padding: 15upx 32upx;
		box-sizing: border-box;
		background-color: #ffffff;

		>view:nth-of-type(1) {
			// width: 150upx;
			font-size: 28upx;
			font-weight: 400;
			flex: none;
			color: #092C4D;
		}

		>view:nth-of-type(2) {
			width: 380upx;
			// height: 64upx;
		}

		>view:nth-of-type(3) {
			width: 128upx;
			height: 64upx;
			background: var(--subjectColor);
			border-radius: 8upx;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 32upx;
			font-weight: 400;
			color: #FFFFFF;
		}
	}

	.headtop {
		display: flex;
		align-items: center;
		justify-content: space-between;
		// margin-top: 20upx;
		background-color: #FFFFFF;
		padding: 20upx 30upx;
		box-sizing: border-box;

		>view:nth-of-type(1) {
			width: 540upx;
			border: 1upx solid #00000020;
			padding: 10upx 20upx;
			box-sizing: border-box;

			// flex: 1;
			// margin-right: 50upx;
			// border-radius: 10upx;
			>input {
				flex: 1;
				font-size: 28upx;
			}
		}

		>view:nth-of-type(2) {
			width: 128upx;
			height: 64upx;
			background: var(--subjectColor);
			border-radius: 8upx;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 32upx;
			font-weight: 400;
			color: #FFFFFF;
		}
	}

	.scvmabx {
		width: 100%;
		height: 71vh;
		margin-top: 20upx;

		.maxboxs {
			width: 100%;
			display: flex;
			flex-direction: column;
			align-items: center;

			>.items {
				width: 100%;
				display: flex;
				flex-direction: column;
				background-color: #ffffff;
				margin-bottom: 20upx;
				padding: 16upx 30upx;
				box-sizing: border-box;
				position: relative;

				.items_row {
					zoom: 0.9;
					display: flex;
					font-size: 28upx;
					padding-bottom: 15upx;

					>view {
						width: 60%;

						&:nth-child(2) {
							width: 40%;
						}
					}
				}
			}

			// 标签
			.tag {
				position: absolute;
				right: 0;
				top: 0;
				font-size: 28upx;
				padding: 10upx;
				color: #fff;
				background: var(--subjectColor);
				border-bottom-left-radius: 10upx;
			}

			.button-container {
				border-top: 4upx solid #eee;
				padding-top: 10upx;

				>view {
					display: flex;

					.button {
						margin-right: 20upx;
					}
				}
			}

			.button {
				color: #fff;
				border-radius: 5upx;
				padding: 15upx 20upx;
				font-size: 28upx;
				background: var(--subjectColor);
				margin-bottom: 10upx;
				display: flex;
				justify-content: center;
			}
		}
	}

	.w100 {
		width: 100%;
	}
</style>