<template>
	<view class="list-page">
		<view class="garden-list">
			<view class="garden-item" v-for="farm in gardenList" :key="farm.farmId || farm.id"
				>
				<view class="garden-l" v-if="farm.coverVideo">
					<video :id="`gl-video-${farm.farmId || farm.id}`" :src="farm.coverVideo" :show-progress="false" :show-play-btn="true"
						:show-center-play-btn="false" object-fit="cover" :show-fullscreen-btn="false"
						  disable-picture-in-picture :autoplay="false" class="video-dom"
						loop muted>
					</video>
				</view>
				<view class="garden-l" v-else>
					<image class="garden-img" :src="`${config.BASIC_IMG}home/garden.png`" mode=""></image>
					<text class="img-text">无人机实拍视频</text>
				</view>
				<view class="garden-r" @click="goGardenItem(farm)">
					<view class="garden-title">
						{{ farm.name }}
					</view>
					<view class="garden-info">
						品种：荔枝（{{ farm.pz }}）
					</view>
					<view class="garden-info">
						位置：{{ (farm.cityName + farm.countyName) || '—' }}
					</view>
					<view class="garden-btn-group">
						<view class="btn-second">
							有味指数
							<text>{{ farm.envScore || '—' }}分</text>
						</view>
						<view class="btn-primary" @click.stop="goSourceReport(farm)">
							溯源报告
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		onMounted,
		onUnmounted,
		ref,
		nextTick
	} from "vue";
	import config from "@/api/config.js"
	import HOME from '@/api/home'
	import { onPageScroll } from '@dcloudio/uni-app'

	onMounted(() => {
		getGardenList()
		// 初始计算
		nextTick(() => {
			setTimeout(updateCenterVideo, 50)
		})
	})

	onPageScroll(() => handlePageScroll())

	onUnmounted(() => {
		// 离开页面时全部暂停
		pauseAll()
	})

	const gardenList = ref([])
	const playingId = ref(null)

	function throttle(fn, wait = 150) {
		let lastTime = 0
		let timer = null
		return function(...args) {
			const now = Date.now()
			if (now - lastTime >= wait) {
				lastTime = now
				fn.apply(this, args)
			} else {
				clearTimeout(timer)
				timer = setTimeout(() => {
					lastTime = Date.now()
					fn.apply(this, args)
				}, wait - (now - lastTime))
			}
		}
	}

	const handlePageScroll = throttle(() => {
		updateCenterVideo()
	}, 200)

	function updateCenterVideo() {
		// 计算视口中心点附近的 video，播放该 video，其余暂停
		const query = uni.createSelectorQuery()
		query.selectAll('.video-dom').fields({ id: true, rect: true, size: true }, rects => {
			if (!rects || !rects.length) return
			const viewportHeight = uni.getSystemInfoSync().windowHeight
			const viewportCenter = viewportHeight / 2
			let minDistance = Number.POSITIVE_INFINITY
			let closestId = null
			rects.forEach(rect => {
				if (!rect) return
				const height = (typeof rect.height === 'number' ? rect.height : (rect.bottom - rect.top))
				const elementCenter = rect.top + height / 2
				// 仅考虑在可视区域内的元素
				if (rect.bottom < 0 || rect.top > viewportHeight) return
				const distance = Math.abs(elementCenter - viewportCenter)
				if (distance < minDistance) {
					minDistance = distance
					closestId = rect.id
				}
			})
			if (closestId && playingId.value !== closestId) {
				playOnly(closestId)
			}
		}).exec()
	}

	function playOnly(targetId) {
		// 暂停所有，再播放目标
		const ctxs = []
		gardenList.value.forEach(item => {
			if (!item.coverVideo) return
			const id = `gl-video-${item.farmId || item.id}`
			const ctx = uni.createVideoContext(id)
			ctxs.push({ id, ctx })
		})
		ctxs.forEach(({ id, ctx }) => {
			if (id === targetId) {
				try { ctx.play() } catch (e) {}
				playingId.value = id
			} else {
				try { ctx.pause() } catch (e) {}
			}
		})
	}

	function pauseAll() {
		gardenList.value.forEach(item => {
			if (!item.coverVideo) return
			const id = `gl-video-${item.farmId || item.id}`
			try { uni.createVideoContext(id).pause() } catch (e) {}
		})
	}

	function getGardenList() {
		HOME.getAllFarm().then(({
			data
		}) => {
			gardenList.value = data.filter(item => item.recommend !== null)
			nextTick(() => setTimeout(updateCenterVideo, 50))
		})
	}

	function goGardenItem(farm) {
		const id = farm?.farmId
		uni.navigateTo({
			url: `/pages/tabBar/home/subPages/gardenItem?farmId=${id}`
		});
	}

	function goSourceReport(farm) {
		const id = farm?.farmId
		uni.navigateTo({
			url: `/pages/tabBar/home/subPages/sourceReport?farmId=${id}`
		});
	}
</script>

<style lang="scss" scoped>
	.list-page {
		padding: 20rpx 40rpx;

		.garden-list {
			.garden-item {
				display: flex;

				.garden-l {
					position: relative;

					.video-dom {
						width: 234rpx;
						height: 200rpx;
						object-fit: cover;
						border-radius: 10rpx;
					}

					.garden-img {
						width: 254rpx;
						height: 200rpx;
						object-fit: cover;
						border-radius: 10rpx;
					}

					.img-text {
						position: absolute;
						left: 0%;
						top: 0%;
						background: rgba(0, 0, 0, 0.3);
						backdrop-filter: 8rpx;
						border-radius: 10rpx 0 10rpx 0;
						font-size: 20rpx;
						color: #FFFFFF;
						padding: 6rpx 14rpx;
					}
				}

				.garden-r {
					padding-left: 20rpx;

					.garden-title {
						font-size: 28rpx;
						line-height: 42rpx;
						color: #000000;
						font-weight: 600;
						padding-bottom: 10rpx;
					}

					.garden-info {
						color: rgba(0, 0, 0, 0.5);
						font-size: 24rpx;
						line-height: 36rpx;
					}

					.garden-btn-group {
						padding-top: 20rpx;
						display: flex;
						align-items: center;

						.btn-second {
							padding: 0 20rpx;
							border-radius: 40rpx;
							font-size: 24rpx;
							color: #C49600;
							background: rgba(255, 217, 94, 0.2);
							height: 56rpx;
							line-height: 56rpx;
						}

						.btn-primary {
							padding: 0 20rpx;
							border-radius: 40rpx;
							font-size: 24rpx;
							color: #000000;
							background: #FFD95E;
							font-weight: bold;
							height: 56rpx;
							line-height: 56rpx;
							margin-left: 20rpx;
						}
					}
				}
			}

			.garden-item+.garden-item {
				margin-top: 20rpx;
			}
		}
	}
</style>