<template>
	<BasicContainer ref='basicContainer' :option="option">
		<!-- 头部 -->
		<template #head>
			<view class="header-container">
				<!-- <view class="tabBar_container">
					<view :class="{'tabBar_item': true, 'active': details.tabBarCode === 1}" @click="handletabBarState(1)">
						入库扫描
					</view>

					<view :class="{'tabBar_item': true, 'active': details.tabBarCode === 2}" @click="handletabBarState(2)">
						配送回库
					</view>
				</view> -->

				<!-- 顶部背景 -->
				<view class="header">
					<view class="search_row">
						<view class="input_container">
							<input placeholder="请输入包条码" v-model="details.searchText" type="text" name="" id="">
							<u-icon @click="details.searchText = ''" v-show="details.searchText" class="clearIcon"
								name="close-circle" color="#999999" size="40"></u-icon>
						</view>
						<view @click="handleSearch" class="search_button">
							确认
						</view>
					</view>
				</view>

				<view @click='showCalendar' class="timeInput">
					<view class="timerView">
						{{details.datatime|| '请选择时间'}}
					</view>
					<view @click.stop.prevent class="icon_container">
						<u-icon @click='showCalendar' style="margin-right: 10rpx;" v-if="!details.datatime" name="calendar"
							color="#999999" size="50"></u-icon>
						<u-icon @click="cleartime" style="margin-right: 10rpx;" v-else name="reload" color="#999999"
							size="40"></u-icon>
					</view>
				</view>

				<view class="header_total_container" @click="handleClickInfo">
					<PullDownBox ref="pullDownPageInfo">
						<template #title>
							<text class="fwb">
								车次号:
							</text>
							<text>
								{{details.pageInfo.tranNumber || '暂无数据'}}
							</text>
						</template>

						<template #content>
							<view class="header_total">
								<view class="header_total_item">
									<view class="">
										总件数
									</view>

									<view class="total">
										{{ details.info.totalNum || 0 }}
									</view>
								</view>

								<view class="header_total_item">
									<view class="">
										已扫件数
									</view>

									<view class="scanNum">
										{{ details.info.scanNum || 0 }}
									</view>
								</view>

								<view class="header_total_item">
									<view class="">
										未扫件数
									</view>

									<view class="notScanNum">
										{{ (details.info.totalNum || 0) - (details.info.scanNum ||  0) }}
									</view>
								</view>
							</view>
						</template>
					</PullDownBox>
				</view>
			</view>
		</template>

		<!-- 主体 -->
		<template #body>
			<u-divider text="订单列表" textPosition="left"></u-divider>

			<!-- 提货单件数 -->
			<scroll-view class="scollView" scroll-y="true" :style="{height: details.height}"
				@scrolltolower="utils.debounce(reachDown, 500)">
				<block v-for="(item, index) in details.data" :key="item.id">
					<view @click="handleChooseStatus(index)"
						:class="{'list_container': true, 'active': details.chooseIndex === index}"
						:style="index === 0 ? 'margin-top: 0px;': ''">
						<view class="list_row" @click="handleGoDetails(item)">
							订单号: {{item.orderCode || '暂无数据'}}
						</view>

						<view class="list_row">
							<view class="">
								总数：
								<text>
									{{item.totalNum }}
								</text>
							</view>
							<view>
								已扫：
								<text style="color: #10d269;">
									{{item.scanNum }}
								</text>
							</view>
							<view class="">
								未扫：
								<text :style="{color: item.residueNum > 0? '#f00': '#000'}">
									{{item.residueNum }}
								</text>
							</view>
						</view>

						<!-- 状态标签 -->
						<view :class="{
								'list_tips': true, 
								'none':item.scanNum  === 0, 
								'portion':item.scanNum < item.totalNum && item.scanNum  > 0,
								'all':item.scanNum === item.totalNum}">
							{{details.type[item.scanNum ===item.totalNum? 3: item.scanNum  !==0?2: 1]|| '暂无状态数据'}}
						</view>
					</view>
				</block>

				<!-- 底部站位 -->
				<!-- 				<view class="footer">

				</view> -->
			</scroll-view>

			<!-- 底部站位 -->
			<!-- <view class="button_container">
				<view @click="handleConfirm">
					确认打托
				</view>
			</view> -->
		</template>
	</BasicContainer>

	<l-calendar v-model:value="details.show" :initStartDate='details.date[0]' :initEndDate='details.date[1]'
		@hide='showCalendar' @change="onConfirm"></l-calendar>

	<!-- #ifdef APP -->
	<saomiao2 :ishidestop="scanState !== 0"></saomiao2>
	<!-- #endif -->
</template>

<script lang="ts" setup>
	import {
		postIncomingIncomingPackage,
		postIncomingBillladingBillladingList
	} from '@/api/user.js'
	import {
		onLoad,
		onShow,
	} from '@dcloudio/uni-app'
	import { nextTick, reactive, ref } from "vue";
	import utils from '@/utils/utils.js'
	import useSystemSettingsStore from '@/store/useSystemSettingsStore';
	import { storeToRefs } from 'pinia';
	const { scanState } = storeToRefs(useSystemSettingsStore())
	// 组件配置
	const option = reactive({
		// 标题
		title: '入库扫描',
		// 下拉刷新回调函数
		async pullDownRefreshInitPage() {
			// 重置被选中数据
			details.chooseIndex = -1

			details.data = []
			details.page.pageNum = 1
			initpage()

			return null
		},
		// 触底加载回到函数
		reachBottomInitPage: async () => { return null },
		haveData: true,
		isEnd: false
	})

	let details = reactive({
		/** 时间 */
		date: [],
		/** 是否显示时间选择框 */
		show: false,
		datatime: '',
		/** 提货批次列表 */
		data: [] as any[],
		/** 页面数据 */
		info: {},
		/** 页面分页 */
		page: {
			pageSize: 10,
			pageNum: 1,
			total: 0
		},
		/** 被选中的元素的索引 */
		chooseIndex: -1,
		/** 提货状态 */
		type: {
			1: '未 扫', 2: '部分扫', 3: '齐 套',
		},
		/** 滚动区高度 */
		height: '80vh',
		/** 页面数据 */
		pageInfo: {} as any,
		/** 扫描的码值 */
		scancode: '',
		detauser: {},
		/** tabBar激活状态 */
		tabBarCode: 1,
		/** 搜索框的值 */
		searchText: ''
	})

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

	/** 扫描后执行的回调函数 */
	const scandata = async () => {
		const _code = details.scancode

		const _submitData : any = {
			orderPackageCode: _code,
			billladingId: details.pageInfo.id,
			incomingType: "2",
		}

		if (details.pageInfo.tranNumber) _submitData.customerTrain = details.pageInfo.tranNumber

		const res = await postIncomingIncomingPackage(_submitData)

		if (res.code !== 200) return

		basicContainer.value.startPullDownRefresh()
		console.log('res :>> ', res);
	}

	/** 初始化时间 */
	const initTime = () => {
		details.date[0] = (uni as any).$u.timeFormat((new Date().valueOf() - 1000 * 60 * 60 * 24 * 3), 'yyyy-mm-dd')
		details.date[1] = (uni as any).$u.timeFormat((new Date().valueOf()), 'yyyy-mm-dd')
		details.datatime = details.date[0] + ' 至 ' + details.date[1]
	}

	onLoad(async (op) => {
		console.log('op :>> ', op);
		details.pageInfo = JSON.parse(op.pageInfo)

		// 初始化时间
		initTime()
		// #ifdef APP
		utils.ttsspke('请扫描或输入包条码')
		// #endif

		await nextTick()
		pullDownPageInfo.value.handleShowPullDown(true)
	})

	onShow(async () => {
		// #ifdef APP
		// 初始化关闭监听
		uni.$off('scancodedate')

		uni.$on('scancodedate', (code) => {
			if (code) {
				details.scancode = code

				scandata()
			}
		})
		// #endif

		await nextTick()
		basicContainer.value.startPullDownRefresh()

		const timer = setTimeout(async () => {
			// 设置滚动区高度
			details.height = await utils.getViewDistanceFormTop('.scollView')
			clearTimeout(timer)
		}, 10)

	})

	/** 数据请求 */
	async function initpage() {
		if (details.date.length === 0) return uni.showToast({
			title: '请选择时间',
			icon: 'none'
		})
		try {
			const _submitData : any = {
				...details.page,
				startDateStr: details.date[0],
				endDateStr: details.date[1]
			}

			if (details.pageInfo.tranNumber) _submitData.customerTrain = details.pageInfo.tranNumber

			const res = await postIncomingBillladingBillladingList(_submitData)

			const { code, data } = res
			const { page } = data

			if (code !== 200) return

			for (let item of page.records) {
				item.scanNum = item.scanNum || 0
				item.totalNum = item.totalNum || 0
				item.residueNum = (item.totalNum || 0) - (item.scanNum || 0)
			}

			details.data = [...details.data, ...page.records]
			details.page.total = data.total
			details.info = data

			return null
		} catch (err) {
			//TODO handle the exception
			console.log('err :>> ', err);
		} finally {
			return null
		}
	}

	/** tabBar激活状态 */
	const handletabBarState = (code : number) => {
		details.tabBarCode = code
	}

	/** 搜索 */
	const handleSearch = () => {
		details.scancode = details.searchText
		scandata()
	}

	/** 显示日期选择器 */
	function showCalendar() {
		details.show = !details.show
	}

	function onConfirm(e : any) {
		const startTime = new Date(e.startDate).getTime()
		const endTime = new Date(e.endDate).getTime()

		// 一周的时间戳
		const maxTime = 1000 * 60 * 60 * 24 * 7

		if (endTime - startTime > maxTime) {
			details.show = true
			return uni.showToast({
				title: '时间范围最大暂时为一周',
				icon: 'none'
			})

		}

		console.log(e);
		details.date[0] = e.startDate
		details.date[1] = e.endDate
		details.datatime = details.date[0] + ' 至 ' + details.date[1]
		basicContainer.value.startPullDownRefresh()
		// details.datatime=(uni as any).$u.timeFormat(date.value[0], 'yyyy-mm-dd')+' 至 '+(uni as any).$u.timeFormat(date.value[1], 'yyyy-mm-dd')
	}

	/** 清空时间 */
	function cleartime() {
		// details.datatime = ''
		// details.date = []
		initTime()
		basicContainer.value.startPullDownRefresh()
	}

	const handleClickInfo = async () => {
		await nextTick()
		// 设置滚动区高度
		details.height = await utils.getViewDistanceFormTop('.scollView')
	}

	/** 触底加载 */
	const reachDown = () => {
		console.log('111 :>> ', 111);
		details.page.pageNum += 1
		if (details.page.total <= details.data.length) return uni.showToast({
			title: '数据加载完毕',
			icon: 'none'
		})
		initpage()
	}

	/** 元素激活状态 */
	const handleChooseStatus = (index : number) => {
		// details.chooseIndex = details.chooseIndex === index ? -1 : index
	}

	/** 确认 */
	const handleConfirm = () => {

	}

	/** 跳转包件明细 */
	const handleGoDetails = (item) => {
		uni.navigateTo({
			url: '/pagesHome/pages/onLoadOrderDetails/onLoadOrderDetails?pageInfo=' + JSON.stringify(item)
		})
	}
</script>

<style lang="scss" scoped>
	// tabBar
	.tabBar_container {
		display: flex;


		>view {
			flex: 1;
			text-align: center;
			padding: 20upx 0;
			position: relative;
			background: #fff;

			&::after {
				content: '';
				display: block;
				width: 0;
				height: 4upx;
				position: absolute;
				background: var(--subjectColor);
				left: 0;
				bottom: 0;
				transition: all cubic-bezier(0.075, 0.82, 0.165, 1) .3s;
				transform: translateX(-50%);
				left: 50%;
			}

			&:first-child {
				&::before {
					content: '';
					display: block;
					width: 4upx;
					height: 60%;
					position: absolute;
					background: var(--subjectColor);
					right: 0;
					top: 50%;
					transform: translateY(-50%);
				}
			}

			&.active {

				&::after {
					width: 50%;
				}
			}
		}
	}

	// 顶部背景
	.header-container {
		position: relative;
	}

	// 头部统计容器
	.header_total_container {
		padding: 0 10upx;
	}

	// 头部统计
	.header_total {
		padding: 10upx;
		border-radius: 10upx;
		margin-top: 20upx;
		display: flex;
		align-items: center;
		justify-content: space-around;
		background: #f5f7fb;
		font-size: 0.9rem;
	}

	.header_total_item {
		height: 100upx;
		text-align: center;
		display: flex;
		flex-direction: column;
		justify-content: space-between;

		>view {
			&:nth-child(2) {
				font-size: 1.2rem;

				&.total {
					color: var(--subjectColor);
				}

				&.scanNum {
					color: #0f0;
				}

				&.notScanNum {
					color: #f00;
				}
			}
		}
	}

	// 头部
	.header {
		width: calc(100vw - 60upx);
		background: #fff;
		padding: 20upx;
		border-radius: 10upx;
		margin: 10upx 10upx;
		font-size: 0.8rem;



		// 搜索行
		.search_row {
			display: flex;
			align-items: center;

			.input_container {
				flex: 1;
				position: relative;
			}

			input {
				margin-right: 20upx;
				background: #eee;
				padding: 10upx 20upx;
				border-radius: 5upx;
			}

			.clearIcon {
				position: absolute;
				right: 40upx;
				top: 50%;
				transform: translateY(-50%);
			}

			.search_button {
				padding: 10upx 30upx;
				background: var(--subjectColor);
				color: #fff;
				border-radius: 5upx;
			}
		}

		.header_row {
			margin-top: 10upx;
			display: flex;

			>view {
				flex: 1;
			}
		}
	}

	.timeInput {
		position: relative;
		background: #fff;
		margin: 10upx;
		border-radius: 5upx;

		.timerView {
			padding: 20upx;
			font-size: 0.8rem;
		}

		.icon_container {
			position: absolute;
			right: 0;
			top: 50%;
			transform: translateY(-50%);
		}
	}

	// 分割线
	:deep(.u-divider__text) {
		font-size: 1rem !important;
		color: var(--subjectColor) !important;
	}

	:deep(.u-line) {
		border-color: var(--subjectColor) !important;
	}

	// 列表容器
	.list_container {
		// 边框圆角
		$borderRadius: 10upx;

		position: relative;
		margin: 20upx;
		font-size: 0.8rem;
		background: #fff;
		padding: 10upx;
		border-radius: $borderRadius;
		box-shadow: 0 0 10px #eee, 3px 3px #eee;

		&.active {
			box-shadow: 0 0 10px var(--subjectColor), 3px 3px var(--subjectColor);
		}

		.list_row {
			padding: 10upx;
			display: flex;

			>view {
				flex: 1;
			}
		}

		.list_tips {
			position: absolute;
			top: 0;
			right: 0;
			padding: 10upx 20upx;
			background: var(--subjectColor);
			color: #fff;
			border-top-right-radius: $borderRadius;

			&.none {
				color: #f8625a;
				background-color: #feeded;
			}

			&.all {
				color: #0086F1;
				background-color: #e5f2fd;
			}

			&.portion {
				color: #fa8c16;
				background: #fef3e7;
			}
		}
	}

	// 底部按钮
	.button_container {
		display: flex;
		justify-content: center;
		position: fixed;
		width: 100%;
		bottom: 40upx;
		left: 0;

		>view {
			width: 60vw;
			padding: 20upx;
			text-align: center;
			background: var(--subjectColor);
			border-radius: 5upx;
			color: #fff;
			box-shadow: 0 0 10px var(--subjectColor);
		}
	}

	// 底部站位
	.footer {
		height: 160upx;
	}

	.fwb {
		font-weight: bold;
	}
</style>