<template>
	<view class="ezy-page-body xuexi-page-body">
		<!-- 滚动区域 -->
		<scroll-view v-if="existData" :scroll-with-animation="true" scroll-y :scroll-top="scrollTop"
			@scroll="handleScroll">
			<view class="xxjl-card-box-padding">
				<view class="xxjl-card-box">
					<!-- 显示内容 -->
					<view class="card-body-box">
						<img :src="neirongInfo.cover" />
						<view class="body-right">
							<view class="right-name">{{ neirongInfo.chanpinName }}</view>
							<view class="right-item right-item-mini">等级：{{neirongInfo.dengjiName}}</view>
							<view class="right-item">版本：{{neirongInfo.name}}</view>
							<view>课程：{{neirongInfo.curKechengName}}</view>
						</view>
					</view>
					<view class="card-progress-box">
						<view class="xx-progress-box">
							<view class="progress-title">学习进度</view>
							<progress :percent="curProcess" class="xx-progress" stroke-width="20"
								backgroundColor="#3c7dfd" activeColor="#ffd11c" />
						</view>
						<ezyActiveVue class="ezy-btn-active jxxx-btn" @aclick="handlePlay(neirongInfo,'jixu')">
						</ezyActiveVue>
					</view>
				</view>
			</view>

			<view class="xx-item-list">
				<view class="xx-item-title">— 以下为当前等级课程目录 —</view>
				<view v-for="(item, index) in danyuanList" :key="item.danyuanId">
					<!-- 节列表 -->
					<ezyActiveVue class="ezy-list-item-active xx-item-box" :class="item.lock?'xx-disabled-item-box':''"  @aclick="handlePlay(item,'play')">
						<view class="xx-item-status"
							:class="item.wanchengFlag == 1 ? 'completed-status' : 'uncompleted-status'"></view>
						<img :src="item.cover" />
						<view class="xx-text-box">
							<view>{{ item.danyuanName }}</view>
							<view>{{ item.danyuanIntro }}</view>
						</view>
						<view v-if="item.lock" class="xx-item-lock-btn"></view>
						<view v-else class="xx-item-btn"></view>
					</ezyActiveVue>
				</view>

				<view class="xx-item-title">本级别最后一单元啦~</view>
				<view class="xx-more-btn" @click="moreBtn"></view>
			</view>
		</scroll-view>
		<!-- 回到顶部 -->
		<view v-show="showGoTop" class="go-top-btn" @click="goTopBtn"></view>

		<!-- 无数据占位 -->
		<view v-if="!existData" class="ezy-page-body">
			<view class="ezy-no-sj">
				<icon></icon>
				<text>暂无数据</text>
			</view>
		</view>
		<!-- 弹窗组件 -->
		<danyuanInfoVue ref="dyRef" v-if="isShow" @close="isShow = false"></danyuanInfoVue>
		<!-- 购买提示窗 -->
		<tipSmallDialog ref="gmtRef" content="需要购买当前课程才能学习" @confirm-btn="handleConfirmBtn" qrBtnName="前往购买"></tipSmallDialog>
	</view>
</template>

<script>
	import ezyActiveVue from "@/components/ezyActive/ezyActive.vue";
	import CustomTabBar from '@/components/custom-tabbar/index.vue';
	import cacheManager from "@/utils/cacheManager.js";
	import {
		yingyuDanciInfo,
		yingyuSave2
	} from "@/api/chanpinneirong.js"
	import {
		onLoad,
		onShow,
		onHide,
		onUnload
	} from "@dcloudio/uni-app"
	import danyuanInfoVue from '@/pages/xinshuxue/components/danyuanInfo.vue';
	import {
		toast
	} from '../../utils/common';
	import {
		updateChanpin3Process
	} from "./useNeirongChanpin3"
	import tipSmallDialog from "@/components/dialog/tipSmallDialog.vue";
	// 产品2 计算特训
	export default {
		data() {
			return {
				canExitApp: false,

				danyuanList: [],
				neirongInfo: {},
				banbenId: '',
				danyuanId: '',
				chanpinId: '',
				dengjiId: '',
				curProcess: '',
				existData: false,
				isShow: false,

				stickyHeight: 0, // 吸顶栏高度（px）
				currentStickyTitle: '', // 初始为空，不显示吸顶
				currentStickyIntro: '',
				currentDanyuanId: '',
				currentStickyDengjiId: '',
				titlePositions: [],
				scrollTop: 0,
				showGoTop: false,
				scrollThreshold: 300,
			}
		},
		components: {
			CustomTabBar,
			danyuanInfoVue,
			ezyActiveVue,
			tipSmallDialog
		},

		onHide() {
			console.log('学习页面隐藏')
		},
		onUnload() {
			// 页面卸载无需特殊处理
		},
		methods: {
			handleConfirmBtn() {
				// 加锁视频需要购买
				uni.navigateTo({
					url: "/pages/chanpinShop/cp4/dingdan"
				})
			},
			initData(banbenId) {
				console.log('33333');
				const cacheData = cacheManager.get('contentInfo');
				if (cacheData) {
					console.log('使用缓存数据');
					this.updateFromCache();
				} else {
					console.log('重新请求数据');
					this.initFromOptions(banbenId);
				}
			},
			goTopBtn() {
				// 替换原来的 uni.pageScrollTo
				this.scrollTop = Math.random(); // 先设置一个随机值
				this.$nextTick(() => {
					this.scrollTop = 0; // 再设置回0
				});

				this.showGoTop = false;
			},
			moreBtn() {
				uni.switchTab({
					url: '/pages/chanpinXuanze/index'
				})
			},

			initFromOptions(banbenId) {

				this.loadDataFromApi(banbenId);
			},
			// 从缓存更新数据方法
			updateFromCache() {
				console.log('12311');
				updateChanpin3Process()
				const cacheData = cacheManager.get('contentInfo');
				console.log('cacheData 从缓存更新数据方法', cacheData);
				if (cacheData) {
					this.neirongInfo = {
						...cacheData
					};
					this.curProcess = cacheData.curProcess;
					this.danyuanList = [...(cacheData.danyuanList || [])];
					this.banbenId = cacheData.banbenId;
          this.dengjiId = cacheData.dengjiId;


					if (this.danyuanList.length == 0) {
						this.existData = false
					} else {
						this.existData = true
					}
					// this.$nextTick(() => {
					// 	this.updateTitlePositions();
					// });
				} else {
					this.existData = false;
				}
			},

			loadDataFromApi(banbenId) {
				uni.showLoading({
					title: '加载中'
				});
				this.banbenId = banbenId
				this.neirongInfo = {}
				this.curProcess = ''
				this.danyuanList = []
				const req = {
					banbenId: banbenId
				}
				yingyuDanciInfo(req).then(res => {
					if (res.code === 0) {
						
						this.neirongInfo = res.data;
						this.neirongInfo.danyuanId = res.data.curDanyuanId;
						this.curProcess = res.data.curProcess * 100;
						this.danyuanList = res.data.danyuanList || [];
						if (this.danyuanList.length == 0) {
							this.existData = false
						} else {
							this.existData = true
						}
						const cacheData = {
							...res.data,
							banbenId: banbenId,
						};
						cacheManager.set('contentInfo', cacheData);
						uni.hideLoading();
					}
				}).catch(res => {
					cacheManager.remove("contentInfo");
					toast("加载失败，请重试");
					uni.hideLoading();
				});
			},


			handleScroll(e) {
				const scrollTop = e.detail.scrollTop;
				console.log('scrollTop', scrollTop);
				this.showGoTop = scrollTop > this.scrollThreshold;
			},

			getJieAndDanyuan(data, danyuanId) {
				for (let danyuan of data.danyuanList) {
						if (danyuan.danyuanId == danyuanId) {
							return {
                danyuan
							}
						}
					
				}
				return null;
			},

			async saveAndNavigate(danyuanId,  da, code) {

				if (code == 'jixu') {
					if (!da.danyuanId) {
						toast("danyuanId 丢失")
						return false
					}
				}

				let req = {
					"banbenId": this.banbenId,
					"danyuanId": da.danyuanId
				}
				console.log('req', req);
				const res = await yingyuSave2(req);
				if (res.code == 0) {
					let curJieAndDanyuan = this.getJieAndDanyuan(this.neirongInfo, danyuanId);
					console.log('curJieAndDanyuan',curJieAndDanyuan);
					
					if (!curJieAndDanyuan) {
						toast("未找到课程信息");
						return false;
					}

					const cacheData = cacheManager.get('contentInfo') || {};
					cacheData.curKechengName = curJieAndDanyuan.danyuan.danyuanIntro;
					cacheData.danyuanId = curJieAndDanyuan.danyuan.danyuanId;
					cacheData.curDanyuanId = danyuanId;
					cacheData.type = curJieAndDanyuan.danyuan.type;
					cacheManager.set('contentInfo', cacheData);

					uni.navigateTo({
						url: `/pages/chaojidanci/wordList/wordList?danyuanId=${danyuanId}&banbenId=${this.banbenId}`
					})
				} else {
					return false;
				}
			},
			handlePlay(da, code) {
				console.log('ddd',da)
				if (da.lock && code == 'play') {
					
					this.$refs.gmtRef.handleShow();
					
					// 加锁视频需要购买
					// uni.navigateTo({
					// 	url: "/pages/chanpinShop/cp1/dingdan"
					// })
					return;
				}
				let danyuanId = code === 'jixu' ? da.curDanyuanId : da.danyuanId;
				if (!danyuanId) {
					toast("无课程ID");
					return;
				}
				this.saveAndNavigate(danyuanId, da, code);
			},
			handleClickDanyuan(danyuanId) {

				if (!danyuanId) {
					toast("danyuanId丢失")
					return false
				}
				this.isShow = true;
				setTimeout(() => {
					// 更新为点击的动态单元Id [临时]
					this.$refs.dyRef.handleShow(danyuanId)
				}, 100)
			}
		},

		// 计算吸顶栏下方的偏移（确保内容不被遮挡）
		computed: {


		}
	}
</script>