<template>
	<BasicContainer ref="basicContainer" :option="option">
		<template #head>
			<!-- tabBar选项卡 -->
			<view class="tabBar">
				<view :class="{'tabBar-item': true, 'active': details.tabBarCode === 10}" @click="handleTabBarCode(10)">
					未签收
				</view>
				<view :class="{'tabBar-item': true, 'active': details.tabBarCode === 20}" @click="handleTabBarCode(20)">
					已签收
				</view>
			</view>
			<view class="schbox">
				<view>配车日期：</view>
				<view @click='showtime(true)' class="inputsr">
					<view class="timeInput">
						{{datatime|| '请选择时间'}}
					</view>
					<view @click.stop.prevent>
						<u-icon @click='showtime(true)' style="margin-right: 10rpx;" v-if="!datatime" name="calendar"
							color="#999999" size="50"></u-icon>
						<u-icon @click="cleartime" style="margin-right: 10rpx;" v-else name="close-circle" color="#999999"
							size="40"></u-icon>
					</view>
				</view>
				<view @click="init">
					查询
				</view>
			</view>
		</template>

		<template #body>
			<scroll-view scroll-y="true" class="scvbx" :style="{height: details.scrollHeight}" @scrolltolower="jiazai">
				<view class="mabxslist">
					<view class="item" v-for="item in recordsList">
						<view class="headtop">
							<view class="type1s">
								<view>
									<text style="color: #90A0AF;">商场名称：</text>{{item.mallName}}
								</view>
								<view>
									<text style="color: #90A0AF;">商场联系人：</text>{{item.mallPerson}}
								</view>
							</view>
							<view class="type1s">
								<view>
									<text style="color: #90A0AF;">商场联系电话：</text>{{item.mallMobile}}
								</view>
								<view>
									<text style="color: #90A0AF;">商场地址：</text>{{item.mallAddress}}
								</view>
							</view>
							<view class="type1s">
								<view>
									<text style="color: #90A0AF;">签收时间：</text>{{item.signTime}}
								</view>
							</view>
							<view class="type1s">
								<view>
									<text style="color: #90A0AF;">司机：</text>{{item.driverName}}
								</view>

								<view class="bhcolor">
									<text style="color: #90A0AF ;">车次号：</text><text>{{item.carsNo || '暂无数据'}}</text>
								</view>
							</view>
							<view class="liebs">
								<view>
									<view>计划数</view>
									<view>{{item.planNum}}</view>
								</view>
								<view>
									<view>装车数</view>
									<view>{{item.loadingNum}}</view>
								</view>
								<view>
									<view>签收数</view>
									<view>{{item.signNum}}</view>
								</view>

							</view>
						</view>
						<view class="buts">
							<view @click="goselscan(item)">签收</view>
							<view v-if="details.tabBarCode === 20" @click="handleShowImg(item)">签收图片</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</template>
	</BasicContainer>

	<PopUp ref="UploadImg">
		<u-upload :fileList="details.imgFileList" @afterRead="handleUploadImg" @delete="deletePic" multiple></u-upload>
	</PopUp>

	<!-- 日期选择器 -->
	<l-calendar v-model:value="show" :initStartDate='date[0]' :initEndDate='date[1]' @hide='showCalendar'
		@change="onConfirm"></l-calendar>
	<tiplist ref="tiplists"></tiplist>
	<tips ref="tip"></tips>
</template>

<script lang="ts" setup>
	import {
		onLoad,
		onShow,
		onHide,
		onUnload,
		onPullDownRefresh
	} from '@dcloudio/uni-app'
	import {
		postFinaSignOrderList,
		postUploadSignPhoto
	} from '@/api/user.js'
	import { reactive, toRefs, ref, watchEffect, nextTick } from "vue";
	import utils from '@/utils/utils.js';
	import functions from '@/utils/functions.js';

	// 获取组件实例
	const tip = ref<any>(null)
	const tiplists = ref<any>(null)
	const date = ref<number | string[]>([])
	const basicContainer = ref(null)

	// 上传图片 -- 弹窗
	const UploadImg = ref()

	const option = {
		title: '直发商家未签收列表',
		haveData: true,
		isEnd: false,
		async pullDownRefreshInitPage() {
			return await init()
		}
	}

	// 页面基础数据
	let details = reactive({
		datatime: '',
		show: false,
		recordsList: [],
		current: 1,
		size: 10,
		/** 总数 */
		total: 0,
		/** 滚动区高度 */
		scrollHeight: '80vh',
		tabBarCode: 10,
		imgFileList: [],
		/** 是否在上传图片 */
		isUpload: false
	})

	onShow(async () => {
		// #ifdef APP
		uni.$off('scancodedate')
		// #endif

		option.isEnd = false
		details.current = 1
		details.recordsList = []

		await nextTick()
		!details.isUpload && basicContainer.value.startPullDownRefresh()
		details.scrollHeight = await utils.getViewDistanceFormTop('.scvbx')
	})
	onHide(() => {
		uni.stopPullDownRefresh();
	})
	function showCalendar() {
		details.show = !details.show
	}

	async function init() {
		details.current = 1
		details.recordsList = []
		return initpage()
	}
	function jiazai() {
		if (option.isEnd) return uni.showToast({
			title: '数据加载完毕',
			icon: 'none'
		})
		details.current++
		initpage()
	}
	watchEffect(() => {
		if ((date.value as []).length != 0) {
			details.datatime = date.value[0] + ' 至 ' + date.value[1]
		}
	})
	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()
		// details.datatime=(uni as any).$u.timeFormat(date.value[0], 'yyyy-mm-dd')+' 至 '+(uni as any).$u.timeFormat(date.value[1], 'yyyy-mm-dd')
	}
	onLoad(() => {
		date.value[0] = (uni as any).$u.timeFormat((new Date().valueOf() - 1000 * 60 * 60 * 24 * 7), 'yyyy-mm-dd')
		date.value[1] = (uni as any).$u.timeFormat((new Date().valueOf()), 'yyyy-mm-dd')
		details.current = 1
	})
	function showtime(value : boolean) {
		console.log(value);
		details.show = value
	}
	async function initpage() {
		try {
			if (date.value.length === 0) {
				utils.handleToast('请选择签收时间')
				details.recordsList = []
				return
			}

			let submitData = {
				pageNum: details.current,
				pageSize: details.size,
				enterTimeStartStr: date.value[0] || '',
				enterTimeEndStr: date.value[1] || '',
				// 签收状态
				signStatus: details.tabBarCode
			}

			let response = await postFinaSignOrderList(submitData)

			const { code, data } = response

			if (code !== 200 && code !== details.tabBarCode) return
			if (details.current == 1) {
				details.recordsList = response.data.records
			} else {
				if (data.records.lngth == 0) {
					uni.showToast({
						title: '已经到底了。',
						icon: 'none'
					})
					details.current--
					return null
				}
				details.recordsList = details.recordsList.concat(data.records)
			}
			details.total = data.total

			if (details.recordsList.length === details.total) {
				option.isEnd = true

				uni.showToast({
					title: '数据加载完毕',
					icon: 'none'
				})
			}
			else option.isEnd = false

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

	}

	// 改变选项卡激活状态
	function handleTabBarCode(code : number) {
		console.log('details :>> ', details);
		details.tabBarCode = code
		// if (code === 10) date.value = details.searchInfo1.date
		// else if (code === 20) date.value = details.searchInfo2.date
		// 开启刷新请求
		basicContainer.value.startPullDownRefresh()
	}

	/**
	 * 跳转装车页面
	 */
	async function goselscan(item : any) {
		uni.navigateTo({
			url: '/pagesHome/pages/directGoMarketDetails/directGoMarketDetails?id=' + item.id
		})
	}

	function cleartime() {
		// console.log(cleartime);
		details.datatime = ''
		date.value = []
		basicContainer.value.startPullDownRefresh()
	}

	/** 显示上传图片弹窗 */
	const handleShowImg = async (item) => {
		details.imgFileList = []

		if (item.signPhotoList && item.signPhotoList.length > 0) {
			for (let i = 0; i < item.signPhotoList.length; i++) {
				const { photoUrl, id } = item.signPhotoList[i]
				photoUrl && details.imgFileList.push({ url: photoUrl, id })
			}
		}

		details.isUpload = true

		UploadImg.value.setDetails({
			title: '上传图片',
			showPopUp: true,
			async success() {
				if (details.imgFileList.length === 0) return uni.showToast({
					icon: 'none',
					title: '请上传图片再提交'
				})

				const submitData = {
					signOrderId: item.id,
					signPhotoList: []
				}

				for (let i = 0; i < details.imgFileList.length; i++) {
					const value = details.imgFileList[i]

					// 存在id, 为已存在数据, 不做上传
					// if (value.id) continue

					submitData.signPhotoList.push({
						signOrderId: item.id,
						photoType: 1,
						photoUrl: value.url
					})
				}

				const res = await postUploadSignPhoto(submitData)

				const { code } = res
				if (code !== 200) return

				UploadImg.value.details.showPopUp = false
				details.isUpload = false
				basicContainer.value.startPullDownRefresh()
			},
			close() {
				UploadImg.value.details.showPopUp = false
				details.isUpload = false
			}
		})
	}

	/** 上传图片 */
	const handleUploadImg = async (event) => {

		try {
			uni.showLoading({
				title: '上传中',
				mask: true
			})

			const writeArr = ['jpg', 'jpeg', 'png']
			const PromiseAll = []

			for (let i = 0; i < event.file.length; i++) {
				const item = event.file[i]
				let type = ''

				item.url && (type = item.url.split('.').slice(-1)[0])
				item.name && (type = item.name.split('.').slice(-1)[0])

				if (writeArr.indexOf(type) === -1) continue

				console.log('type :>> ', type);

				PromiseAll.push(functions.upfile(item.url))
			}


			const res = await Promise.all(PromiseAll)

			console.log('res :>> ', res);

			for (let i = 0; i < res.length; i++) {
				const response = res[i]

				const { link } = response

				if (!link) continue

				details.imgFileList.push({ url: link })
			}
		} catch (err) {
			console.log('err :>> ', err);
			//TODO handle the exception
		} finally {
			uni.hideLoading()
		}


	}

	/** 删除图片 */
	const deletePic = (event) => {
		console.log('event :>> ', event);

		details.imgFileList.splice(event.index, 1)
	}
	const { datatime, recordsList, show } = toRefs(details)
</script>

<style lang="scss">
	// tabBar选项卡
	.tabBar {
		display: flex;
		justify-content: space-evenly;
		background-color: #fff;
		margin-bottom: 10upx;

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

			&::after {
				content: '';
				position: absolute;
				bottom: 0;
				left: 50%;
				transform: translateX(-50%);
				display: block;
				width: 0;
				box-sizing: border-box;
				border: 2upx solid var(--subjectColor);
				transition: all 0.5s;
			}

			&.active {
				color: var(--subjectColor);

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

	.inputsr {
		width: 400upx !important;
		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;
		}
	}

	.scvbx {
		width: 100%;
		height: 75vh;
		margin-top: 20upx;

		.mabxslist {
			display: flex;
			flex-direction: column;
			align-items: center;

			>.item {
				width: 686upx;
				// height: 610upx;
				background: #FFFFFF;
				border-radius: 8upx;
				padding: 20upx 0;
				box-sizing: border-box;
				margin-bottom: 20upx;

				>.headtop {
					display: flex;
					flex-direction: column;
					padding: 24upx;

					>.type1s {
						display: flex;
						align-items: flex-start;
						justify-content: space-between;
						margin-bottom: 20upx;
						box-sizing: border-box;
						font-size: 28upx;
						font-weight: 400;
						color: #092C4D;

						>view {
							flex: 1;
						}

						.bhcolor {
							color: #0086F1;
						}
					}

					>.liebs {
						display: flex;
						align-items: flex-start;
						justify-content: space-around;

						>view {
							display: flex;
							flex-direction: column;
							align-items: center;
							margin-top: 10upx;

							&: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(1) {
								font-size: 28upx;
								font-weight: 400;
								color: #092C4D;
							}

							>view:nth-of-type(2) {
								font-size: 36upx;
								font-weight: 400;
								margin-top: 10upx;

							}
						}
					}
				}

				>.buts {
					border-top: 3upx solid #EEEEEE;
					display: flex;
					align-items: center;
					justify-content: space-around;
					padding-top: 20upx;

					>view {
						width: 204upx;
						height: 64upx;
						border-radius: 8upx;
						opacity: 1;
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 28upx;
					}

					>view:nth-of-type(1) {
						border: 2upx solid #0086F1;
						color: #0086F1;
					}

					>view:nth-of-type(2) {
						border: 2upx solid #69bd85;
						color: #69bd85;
					}

					>view:nth-of-type(3) {
						border: 2upx solid #D3832A;
						color: #D3832A;
					}
				}
			}
		}
	}

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

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

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

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



	// 上传
	:deep(.u-upload__button) {
		width: 4.5rem !important;
		height: 4.5rem !important;

		.u-icon__icon {
			font-size: 1.5rem !important;
			line-height: 1.5rem !important;
		}
	}

	:deep(.u-upload__wrap__preview__image) {
		width: 4.5rem !important;
		height: 4.5rem !important;


	}

	:deep(.u-upload__deletable) {
		width: 36upx;
		height: 36upx;

		.u-icon__icon {
			font-size: 28upx !important;
			line-height: 28upx !important;
		}
	}

	:deep(.popUpMask) {
		z-index: 99;
	}
</style>