<template>
	<view class="container">
		<!-- 滚动区域 -->
		<scroll-view class="scroll-view" scroll-y :scroll-top="scrollTop" @scroll="handleScroll"
			:scroll-with-animation="true">
			<!-- 模拟长内容 -->
			<view v-for="i in 50" :key="i" class="item">
				内容项 {{ i }}
			</view>
		</scroll-view>

		<!-- 返回顶部按钮 -->
		<view v-show="showBackTop" class="back-to-top" @click="backToTop">
			<text class="icon">↑</text>
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue'

	// 滚动位置
	const scrollTop = ref(0)
	// 是否显示返回顶部按钮
	const showBackTop = ref(false)
	// 记录当前滚动位置
	const currentScrollTop = ref(0)

	// 防抖函数
	function debounce(func, wait) {
		let timeout
		return function executedFunction(...args) {
			const later = () => {
				clearTimeout(timeout)
				func(...args)
			}
			clearTimeout(timeout)
			timeout = setTimeout(later, wait)
		}
	}

	// 处理滚动事件
	const handleScroll = debounce((e) => {
		currentScrollTop.value = e.detail.scrollTop
		// 滚动超过200px显示返回顶部按钮
		showBackTop.value = e.detail.scrollTop > 200
	}, 100)

	// 返回顶部
	const backToTop = () => {
		scrollTop.value = 0
		// 立即隐藏按钮，避免动画过程中按钮还显示
		setTimeout(() => {
			showBackTop.value = false
		}, 300)
	}
</script>

<style scoped>
	.container {
		height: 100vh;
		position: relative;
	}

	.scroll-view {
		height: 100%;
		background-color: #f5f5f5;
	}

	.item {
		height: 100rpx;
		line-height: 100rpx;
		text-align: center;
		background-color: #fff;
		margin-bottom: 2rpx;
		font-size: 28rpx;
	}

	.back-to-top {
		position: fixed;
		right: 30rpx;
		bottom: 100rpx;
		width: 90rpx;
		height: 90rpx;
		background-color: #007aff;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
		/* 添加过渡动画 */
		transition: all 0.3s ease;
	}

	.back-to-top:active {
		transform: scale(0.9);
	}

	.icon {
		color: #fff;
		font-size: 40rpx;
		font-weight: bold;
	}
</style>