<template>
	<view class="home-wrap base-container">
		<view class="home-top">
			<view class="home-search">
				<view class="search-wrap">
					<up-search placeholder="搜索农场名称" v-model="typeSearch"></up-search>
				</view>
			</view>
			<div class="home-box" @click="toPage('allGardenMap')">
				<video src="https://birdseye-img.sysuimars.com/youwei-uniapp/home/map-video.mp4" object-fit="cover"
					:show-fullscreen-btn="false" :autoplay="true" class="map-video" loop muted :show-progress="false"
					:show-play-btn="false">
				</video>
				<view class="map-tips">
					飞鸟入驻管理果场详情，点击查看
				</view>
			</div>
		</view>
		<view class="type-wrap">
			<up-scroll-list :indicator="typeList && typeList.length>5" indicatorColor="#F3C11D33" indicatorActiveColor="#F3C11D"
				:indicatorWidth="30" :indicatorBarWidth="13" ref="scrollListRef">
				<view class="item-type">
					<image class="type-img" :src="`${config.BASIC_IMG}home/type-icon.png`" alt="" />
					<view class="type-text">
						全部
					</view>
				</view>
				<view class="item-type" v-for="(item, index) in typeList" :key="index">
					<image class="type-img" :src="item.image" alt="" />
					<view class="type-text">
						{{item.name}}
					</view>
				</view>

			</up-scroll-list>
		</view>
		<!-- 好味热卖 -->
		<view class="home-hot" v-if="gardenList && gardenList.length">
			<hot-component-vue :farmId="gardenList[0].farmId"></hot-component-vue>
		</view>

		<!-- 有味果园 -->
		<view class="garden-wrap">
			<view class="garden-content">
				<view class="hot-title">
					<view class="title-l">
						有味果园
					</view>
					<view class="title-btn" @click="toPage('gardenList')">
						查看全部<up-icon size="10" name="arrow-right"></up-icon>
					</view>
				</view>
				<view class="garden-list">
					<view class="garden-item" v-for="farm in gardenList" :key="farm.farmId || farm.id"
						@click="goGardenItem(farm)">
						<view class="garden-l" v-if="farm.coverVideo">
							<video :id="`home-video-${farm.farmId || farm.id}`" :src="farm.coverVideo"
								:show-progress="false" :show-play-btn="true" :picture-in-picture-mode="[]"
								:show-background-playback-button="false" :show-center-play-btn="false"
								object-fit="cover" :show-fullscreen-btn="false" disable-picture-in-picture
								:autoplay="false" x5-video-player-type="h5" 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">
							<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>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		onUnmounted,
		nextTick
	} from 'vue'
	import config from "@/api/config.js"
	import HOME from '@/api/home'
	import { useUserStore } from '@/store/user' // 引入 Pinia store
	import hotComponentVue from './hotComponent.vue'
	import {
		onLoad,
		onPageScroll
	} from "@dcloudio/uni-app"

	// 获取 user store
	const userStore = useUserStore()
	
	const typeSearch = ref(null)
	const gardenList = ref([])
	const typeList = ref([])
	const playingId = ref(null)

	function toPage(path) {
		uni.navigateTo({
			url: `/pages/tabBar/home/subPages/${path}`
		});
	}

	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}`
		});
	}

	onMounted(() => {
		nextTick(() => {
			setTimeout(updateCenterVideo, 50)
		})
	})

	onPageScroll(() => handlePageScroll())

	onUnmounted(() => {
		pauseAll()
	})

	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() {
		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 = `home-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 = `home-video-${item.farmId || item.id}`
			try {
				uni.createVideoContext(id).pause()
			} catch (e) {}
		})
	}

	onLoad(async () => {
		console.log('onLoad')
		
		try {
			// 显示全局加载状态
			uni.showLoading({
				title: '加载中...',
				mask: true
			})
			
			// 【核心修改】等待token准备就绪
			await userStore.getTokenSafe()
			console.log('登录成功，token已就绪')
			
			// 现在可以安全地执行需要登录状态的请求
			await getTypeList()
			await getFarmData()
			
			// 隐藏加载状态
			uni.hideLoading()
		} catch (error) {
			console.error('初始化失败:', error)
			// 隐藏加载状态
			uni.hideLoading()
			// 登录失败处理，可以跳转到登录页或显示提示
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			})
		}
	})

	async function getTypeList() {
		try {
			const { data } = await HOME.fetchTypeList()
			typeList.value = data
		} catch (error) {
			console.error('获取类型列表失败:', error)
		}
	}

	async function getFarmData() {
		try {
			const { data } = await HOME.getAllFarm()
			if (!data || !data.length)  return
			gardenList.value = data.filter(item => item.recommend !== null)
			nextTick(() => setTimeout(updateCenterVideo, 50))
		} catch (error) {
			console.error('获取果园数据失败:', error)
		}
	}
</script>

<style lang="scss" scoped>
	.garden-l {
		::v-deep {
			.uni-video-control-button {
				width: 10px;
				height: 10px;
			}
		}
	}

	/* 或者全局隐藏 */
	::v-deep .uni-video-pip {
		display: none !important;
	}

	.home-wrap {
		background-color: #F2F3F5;
		padding: 0 0 16rpx 0;

		.home-top {
			padding: 20rpx 24rpx 0 24rpx;
			background: linear-gradient(#FFFFFF, rgba(242, 243, 245, 0));
			position: relative;
		}

		.map-video {
			width: 100%;
			height: 280rpx;
			border-radius: 16rpx;
		}

		.map-tips {
			position: absolute;
			bottom: 6rpx;
			left: 24rpx;
			height: 70rpx;
			width: calc(100% - 48rpx);
			background: linear-gradient(rgba(102, 102, 102, 0), rgba(0, 0, 0, 0.55));
			display: flex;
			align-items: center;
			font-size: 24rpx;
			color: #FFFFFF;
			padding-left: 20rpx;
			box-sizing: border-box;
			border-radius: 0 0 16rpx 16rpx;
		}

		.home-search {
			display: flex;
			align-items: center;
			width: 100%;
			border: 2rpx solid #FFD95E;
			border-radius: 40rpx;
			margin-bottom: 40rpx;

			.search-wrap {
				flex: 1;

				// padding-left: 22rpx;
				::v-deep {
					.u-search {
						.u-search__content {
							background-color: transparent !important;

							.u-search__content__input {
								background-color: transparent !important;

							}
						}

						.u-search__action {
							text-align: center;
							line-height: 52rpx;
							border-radius: 40rpx;
							font-size: 28rpx;
							background-color: #FFD95E;
							margin: 6rpx 8rpx;
							width: 112rpx;
							height: 52rpx;
						}
					}
				}
			}

			.search-btn {
				text-align: center;
				line-height: 52rpx;
				border-radius: 40rpx;
				font-size: 28rpx;
				background-color: #FFD95E;
				margin: 6rpx 8rpx;
				width: 112rpx;
				height: 52rpx;
			}
		}

		.type-wrap {
			margin: 20rpx;
			padding: 20rpx;
			background-color: #fff;
			border-radius: 16rpx;
			height: 200rpx;
			box-sizing: border-box;

			// 覆盖 up-scroll-list 的默认样式，实现两端对齐
			:deep(.u-scroll-list__scroll-view__content) {
				display: flex;
				justify-content: space-between;
				align-items: center;
				width: 100%;
				min-width: 100%;
			}

			.item-type {
				text-align: center;
				font-size: 24rpx;
				flex-shrink: 0;

				.type-img {
					width: 92rpx;
					height: 92rpx;
				}
			}

			.item-type+.item-type {
				padding-left: 22rpx;
			}
		}

		.home-hot {
			padding: 0 20rpx 20rpx;
		}

		.garden-wrap {
			margin: 0 20rpx 20rpx;
			background: linear-gradient(#FFFFFF, rgba(255, 255, 255, 0));
			padding: 2rpx;
			border-radius: 16rpx;

			.garden-content {
				background: linear-gradient(#fff6d8 30rpx, #FFFFFF 120rpx);
				border-radius: 16rpx;
				padding: 20rpx;
				box-sizing: border-box;

				.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;
					}
				}
			}

		}


		.hot-title {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding-bottom: 20rpx;

			.title-l {
				font-family: 'PangMenZhengDao';
				font-size: 32rpx;

				.title-color {
					color: #F3C11D;
				}
			}

			.title-btn {
				color: rgba(0, 0, 0, 0.6);
				font-size: 24rpx;
				display: inline-flex;
				align-items: center;
			}
		}


		::v-deep {
			.u-scroll-list__indicator {
				margin-top: 20rpx;
			}
		}
	}
</style>