<template>
	<view class="container">
		<!-- 当前单元标题（吸顶效果） -->
		<view class="sticky-title" v-if="currentUnitName">
			 {{ showStickyTitle ? currentUnitName : "学习" }}
		</view>

		<!-- 返回顶部按钮 -->
		<view class="back-top" v-if="showBackTop" @click="scrollToTop">
			<text>↑</text>
		</view>

		<scroll-view scroll-y class="scroll-view" :scroll-top="scrollTop" @scroll="onScroll">
			<view class="subject-info" v-if="subjectDetail">
				<text class="course-name">{{ subjectDetail.chanpinName }}</text>
				<text class="course-name">等级:{{ subjectDetail.dengjiName }}</text>
				<text class="course-name">版本:{{ subjectDetail.dengjiName }}</text>
				<text class="course-name">单元:{{ subjectDetail.curDanyuanName }}</text>
				<progress :percent="20" class="exam-progress-box" stroke-width="10" backgroundColor="#3c7dfd"
					activeColor="#ffd11c" />
				<text class="course-name" @click="handlePlay(subjectDetail,'jixu')">继续学习</text>
			</view>
			<!-- 单元列表 -->
			<view v-for="(unit, index) in danyuanList" :key="unit.danyuanId" :id="'unit-' + index" class="unit-item">
				<!-- 单元标题 -->
				<view class="unit-title" @click="handleClickDanyuan(unit)">
					<text class="unit-name">{{ unit.danyuanName }}</text>
					<text class="unit-intro">{{ unit.danyuanIntro }}</text>
				</view>
				<text class="unit-name">{{ unit.danyuanName }}</text>
				<!-- 节列表 -->
				<view v-for="section in unit.jieList" :key="section.jieId" class="section-item">
					<view class="status" :class="section.wanchengFlag === 1 ? 'completed' : 'uncompleted'">
						{{ section.wanchengFlag === 1 ? '已完成' : '未开始' }}
					</view>
					<view class="section-left">
						<image class="section-cover" :src="section.cover" mode="aspectFill"></image>
						<view class="section-info">
							<text class="section-name">{{ section.jieName }}</text>
							<text class="section-desc">{{ section.jieIntro }}</text>
						</view>
					</view>
					<view class="section-right">
						<text class="section-number">第{{ section.number }}节</text>
						<text @click="handlePlay(section,'play')">播放按钮</text>
					</view>
				</view>
			</view>

			<!-- 底部占位 -->
			<view style="height: 100px; text-align: center;">查看更多内容</view>
		</scroll-view>
		
		<danyuanInfoVue ref="dyRef" v-if="isShow" @close="isShow= false"></danyuanInfoVue>
		
		<CustomTabBar :currentTabNumber="1"></CustomTabBar>
	</view>
</template>

<script>
	import CustomTabBar from '@/components/custom-tabbar/custom-tabbar.vue';
	import {
		shuxueChanpinBanben
	} from "@/api/chanpinneirong.js"
	import danyuanInfoVue from '@/pages/xinshuxue/components/danyuanInfo.vue';
	
	export default {
		data() {
			return {
				danyuanList: [],
				currentUnitName: "",
				subjectDetail: null,
				showBackTop: false,
				scrollTop: 0,
				pageCacheKey: 'learn_page_scroll_cache',
				hasRestoredScroll: false,
				showStickyTitle: false,
				isShow: true
			}
		},
		components: {
			CustomTabBar,
			danyuanInfoVue,
		},
		onShow() {

			console.log('学习页面显示，尝试恢复滚动位置')
			// 如果没有恢复过，从缓存恢复
			if (!this.hasRestoredScroll) {
				this.restoreScrollPosition()
			}
		},

		// 新增：页面隐藏时保存滚动位置
		onHide() {

			console.log('学习页面隐藏，保存滚动位置')
			this.saveScrollPosition()
		},

		onLoad() {

			this.loadDataFromApi()
		},

		onReady() {

			// 页面渲染完成后执行
			setTimeout(() => {
				this.getUnitPositions();
			}, 300);
		},

		methods: {
			handlePlay(da,code) {
				let jieId = null;
				if (code == 'jixu') {
					jieId = da.curJieId;
				} else {
					jieId = da.jieId;
				}
				uni.navigateTo({
					url: `/pages/xinshuxue/lookShipin?jieId=${jieId}`
				})
			},
			handleClickDanyuan(item){
				console.log('item', item)
				this.isShow = true;
				setTimeout(() => {
					this.$refs.dyRef.handleShow(item.danyuanId)
				},100)
			},

			loadDataFromApi() {
				const req = {
					banbenId: 7
				}
				shuxueChanpinBanben(req).then(res => {
					this.subjectDetail = res.data
					this.danyuanList = res.data.danyuanList || []
					// 初始化当前单元
					if (this.danyuanList.length > 0) {
						this.currentUnitName = this.danyuanList[0].danyuanName
					}
				})
			},

			// 保存滚动位置到缓存
			saveScrollPosition() {
				if (this.scrollTop > 0) {
					const scrollData = {
						scrollTop: this.scrollTop,
						currentUnit: this.currentUnitName,
						timestamp: Date.now()
					}
					uni.setStorageSync(this.pageCacheKey, scrollData)
					console.log('保存滚动位置到缓存:', scrollData.scrollTop, '当前单元:', scrollData.currentUnit)
				}
			},

			// 从缓存恢复滚动位置
			restoreScrollPosition() {
				try {
					const saved = uni.getStorageSync(this.pageCacheKey)
					if (saved && saved.scrollTop > 0) {
						this.showStickyTitle = true
						// 延迟执行滚动
						setTimeout(() => {
							this.scrollTop = saved.scrollTop

							// 恢复当前单元名称
							if (saved.currentUnit) {
								this.currentUnitName = saved.currentUnit
							}

							this.hasRestoredScroll = true

							// 再次延迟确保滚动生效
							// setTimeout(() => {
							// 	this.scrollTop = saved.scrollTop + 0.01
							// }, 50)
						}, 100)
					} else {
						this.showStickyTitle = false
					}
				} catch (e) {
					console.error('读取缓存失败:', e)
				}
			},

			// 获取每个单元的位置信息
			getUnitPositions() {
				const query = uni.createSelectorQuery().in(this);

				this.danyuanList.forEach((unit, index) => {
					query.select('#unit-' + index).boundingClientRect();
				});

				query.exec((res) => {
					console.log('单元位置信息:', res);
				});
			},

			// 滚动事件处理
			onScroll(e) {
				const scrollTop = e.detail.scrollTop;

				// 更新滚动位置
				this.scrollTop = scrollTop;

				// 实时保存到缓存
				const saveData = {
					scrollTop: scrollTop,
					currentUnit: this.currentUnitName,
					timestamp: Date.now()
				}
				uni.setStorageSync(this.pageCacheKey, saveData)

				// 显示/隐藏返回顶部按钮
				this.showBackTop = scrollTop > 400;

				// 监听滚动，更新当前显示的单元
				this.updateCurrentUnit(scrollTop);
			},

			// 更新当前显示的单元
			updateCurrentUnit(scrollTop) {

				const query = uni.createSelectorQuery().in(this);

				for (let i = 0; i < this.danyuanList.length; i++) {
					query.select('#unit-' + i).boundingClientRect();
				}
				query.exec((res) => {
					// 添加一个偏移量，让切换更平滑
					const offset = 80;
					for (let i = 0; i < res.length; i++) {
						const rect = res[i];
						if (rect) {
							// 计算单元在页面中的实际位置（考虑滚动）
							const unitTop = rect.top + scrollTop;
							if (scrollTop + offset >= unitTop) {
								if (i == res.length - 1 || scrollTop + offset < (res[i + 1].top + scrollTop)) {
									// 每次滚动都设置吸顶标题显示状态
									this.showStickyTitle = i >= 1

									if (this.currentUnitName !== this.danyuanList[i].danyuanName) {
										this.currentUnitName = this.danyuanList[i].danyuanName;

										// 单元变化时立即保存
										const saveData = {
											scrollTop: this.scrollTop,
											currentUnit: this.currentUnitName,
											timestamp: Date.now()
										}
										uni.setStorageSync(this.pageCacheKey, saveData)
									}
									break;
								}
							}
						}
					}
				});
			},

			// 返回顶部
			scrollToTop() {
				// 清除缓存
				uni.removeStorageSync(this.pageCacheKey)
				this.hasRestoredScroll = false
				this.showStickyTitle = false
				// 回到顶部
				this.scrollTop = this.scrollTop + 1; // 先改变值触发重新渲染
				this.$nextTick(() => {
					this.scrollTop = 0;
					this.currentUnitName = this.danyuanList[0].danyuanName;
				});
			}
		}
	}
</script>

<style scoped>
	.container {
		height: 100vh;
		background-color: #f5f5f5;
	}

	/* 吸顶标题 */
	.sticky-title {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 100;
		background-color: #1890ff;
		color: white;
		padding: 12px 16px;
		font-size: 16px;
		font-weight: bold;
		text-align: center;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
	}

	/* 返回顶部按钮 */
	.back-top {
		position: fixed;
		right: 16px;
		bottom: 100px;
		z-index: 99;
		width: 44px;
		height: 44px;
		background-color: #1890ff;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		color: white;
		font-size: 20px;
		box-shadow: 0 2px 8px rgba(24, 144, 255, 0.4);
	}

	.back-top:active {
		background-color: #096dd9;
		transform: scale(0.95);
	}

	/* 滚动区域 */
	.scroll-view {
		height: 100%;
		padding-top: 50px;
		/* 给吸顶标题留出空间 */
		box-sizing: border-box;
	}

	/* 单元样式 */
	.unit-item {
		margin: 12px;
		background: white;
		border-radius: 8px;
		overflow: hidden;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
	}

	.unit-title {
		padding: 16px;
		background: linear-gradient(135deg, #1890ff, #36cfc9);
		color: white;
	}

	.unit-name {
		font-size: 18px;
		font-weight: bold;
		display: block;
		margin-bottom: 4px;
	}

	.unit-intro {
		font-size: 14px;
		opacity: 0.9;
	}

	/* 节样式 */
	.section-item {
		padding: 12px 16px;
		border-bottom: 1px solid #f0f0f0;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.section-item:last-child {
		border-bottom: none;
	}

	.section-left {
		display: flex;
		align-items: center;
		flex: 1;
	}

	.section-cover {
		width: 60px;
		height: 60px;
		border-radius: 6px;
		margin-right: 12px;
	}

	.section-info {
		flex: 1;
	}

	.section-name {
		font-size: 16px;
		color: #333;
		display: block;
		margin-bottom: 4px;
		font-weight: 500;
	}

	.section-desc {
		font-size: 13px;
		color: #666;
	}

	.section-right {
		display: flex;
		flex-direction: column;
		align-items: flex-end;
		margin-left: 12px;
	}

	.section-number {
		font-size: 12px;
		color: #999;
		margin-bottom: 4px;
	}

	.status {
		font-size: 12px;
		padding: 2px 8px;
		border-radius: 10px;
	}

	.status.completed {
		background-color: #f6ffed;
		color: #52c41a;
		border: 1px solid #b7eb8f;
	}

	.status.uncompleted {
		background-color: #fff7e6;
		color: #fa8c16;
		border: 1px solid #ffd591;
	}
</style>