<template>
	<view class="page">
		<view class="video-wrap" :style="{paddingTop:statusBarHeight}">
			<video
				:key="activeIndex"
				@timeupdate="onTimeUpdate"
				@loadedmetadata="onVideoLoadedMetadata"
				@progress="progressChange"
				@error="videoErrorCallback"
				@play="getPlay"
				@pause="getPause"
				@ended="getEnded"
				@fullscreenchange="fullscreenchange"
				:title="courseInfo.title"
				style="width: 100%;height: 420rpx;"
				:poster="poster"
				id="video-content-box"
				controls
				:auto-pause-if-open-native="true"
				:auto-pause-if-navigate="true"
				:enable-progress-gesture="false"
				:show-progress="true"
				:picture-in-picture-mode="[]"
				:show-background-playback-button="false"
				:src="videoUrl"
			>
			<cover-view v-if="!isFull" class="back-box" :style="{'top':menuButtonInfo.gapToStatusBar}" @click="goBack()">
			  <cover-view :style="{'height':menuButtonInfo.height}" style="display: flex;align-items: center;justify-content: center;">
				  <cover-image style="width: 18px;height: 18px;" src="/static/images/ai_right_icon.png"></cover-image>
			  </cover-view>
			</cover-view>
			</video>
		</view>

		<scroll-view class="page-scroll" scroll-y @scrolltolower="loadMoreComments">
			<view class="content">
				<view class="course-title">{{ courseInfo.courseName }}</view>
				<view class="course-desc">{{ courseInfo.description ||'暂无简介'}}</view>
				<view class="course-views">{{ courseViewsDisplay }}次播放</view>
			</view>

			<view class="section-head">
				<view class="left">
					<image class="dot" src="https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/class/list.png"></image>
					<text class="section-title">视频标题</text>
				</view>
				<view class="count" @click="showCatalog = true">共{{ catalogNum||0 }}个作品
				  <image class="w16 h20 ml10" src="https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/class/right.png"></image>
				</view>
			</view>

			<scroll-view class="catalog-scroll" scroll-x>
				<view class="catalog-row">
					<view
						v-for="(item, index) in catalogList"
						:key="item.videoId"
						class="catalog-item"
						:class="{ active: activeIndex == item.videoId }"
						@click="selectCourse(item)"
					>
						<view class="catalog-top">
							<view class="catalog-index-wrap">
								<!-- <text class="catalog-index">第{{ index + 1 }}讲</text> -->
								<image class="catalog-active-dot" v-if="activeIndex == item.videoId" src="https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/class/live.png" /></image>
							</view>
							<text class="free-tag">限时免费</text>
						</view>
						<view class="catalog-name ellipsis2" :class="{ active: activeIndex == item.videoId }">{{ item.title }}</view>
					</view>
				</view>
			</scroll-view>

			<view class="comment-wrap">
				<view class="comment-title">评论</view>
				<view v-if="commentInitLoaded && !commentLoading && (!comments || comments.length === 0)" class="comment-empty">暂无评论</view>
				<view class="comment-item" v-for="item in comments" :key="item.id">
					<image class="avatar" :src="item.avatar" mode="aspectFill"></image>
					<view class="comment-main">
						<view class="name">
							{{ item.name }}
							<text v-if="item.selfOnly" class="self-only-tag">（仅自己可见）</text>
						</view>
						<view class="time">{{ item.time }}</view>
						<view class="text" style="word-break: break-all;">{{ item.content }}</view>
					</view>
				</view>
				<view v-if="commentInitLoaded && comments && comments.length > 0" class="comment-load-status">
					{{ commentLoading ? "加载中..." : (commentHasMore ? "上拉加载更多" : "没有更多评论了") }}
				</view>
			</view>
			<view class="bottom-space"></view>
		</scroll-view>
		
		<view v-if="showAnswerEntry" class="answer-entry" @click="openAnswerPopup">
			<image class="gift-icon" src="https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/class/box.png"></image>
			<view class="answer-tip y-bc" :class="{ done: hasAward }">
				<template v-if="answerShowCountdownLines">
					<view class="answer-tip-line answer-tip-line-first">再观看{{ answerCountdownText }}</view>
				</template>
				<template v-else-if="answerStatus==4">
					<view class="answer-tip-single2">
						已得
					<view class="jifen">{{awardScore||0}}</view>
					   积分
					</view>
				</template>
				<text v-else class="answer-tip-single">{{ answerEntryTip }}</text>
				<view class="answer-btn" v-if="answerStatus!==3&&answerStatus!==4">答题</view>
			</view>
		</view>

		<view class="bottom-bar">
			<input
				class="input comment-input"
				v-model.trim="commentContent"
				placeholder="发表我的态度"
				placeholder-class="comment-input-placeholder"
				confirm-type="send"
				:maxlength="50"
				@confirm="submitComment"
			/>
			<view class="send-btn" :class="{ disabled: isSendingComment }" @click="submitComment">
				{{ isSendingComment ? "发送中..." : "发送" }}
			</view>
			<view class="share-btn" @click="handleShare">
				<image class="share" src="https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/class/share.png" mode="aspectFit"></image>
				<text>分享</text>
			</view>
		</view>
		
		<view class="answer-mask" v-if="showAnswerPopup" @click="closeAnswerPopup">
			<view class="answer-panel" @click.stop>
				<view class="answer-head">
					<view class="left">
						<image class="dot" src="https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/class/qus.png" mode="aspectFit"></image>
						<text class="section-title">问答题</text>
					</view>
					<view class="close-btn" @click="closeAnswerPopup">
						<image src="https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/class/close.png"></image>
					</view>
				</view>
				<view class="answer-divider"></view>
				<scroll-view class="popup-scroll" scroll-y>
				<view v-for="(ques, idx) in answerQuestion" :key="idx">
				<view class="question-title">{{ ques.title }}</view>
				<view
					v-for="(option, index) in ques.options"
					:key="option.indexId"
					class="answer-option"
					:class="{ active: selectedAnswers[idx] === index, disabled: !canAnswer }"
					@click="selectAnswer(idx, index)"
				>
					{{ option.name }}
				</view>
				
			</view>
			</scroll-view>
			<view
				class="submit-btn"
				:class="{ active: isAnswerReady, disabled: !isAnswerReady }"
				@click="submitAnswer"
			>
				{{ canAnswer ? "提交答案" : ("再观看" + answerCountdownText + "可答题") }}
			</view>
			</view>
		</view>
		
		<view class="answer-result-mask" v-if="showAnswerResultPopup" @click="closeAnswerResultPopup">
			<view class="answer-result-panel" @click.stop>
				<view class="result-title">{{ resultConfig.title }}</view>
				<view class="result-subtitle" v-if="answerResultType === 'success'">
					获得<text class="result-score">{{ awardScore }}</text>积分，自动到账
				</view>
				<view class="result-subtitle" v-else-if="answerResultType === 'completed'">
					<text v-if="awardScore > 0">已获得<text class="result-score">{{ awardScore }}</text>积分</text>
					<text v-else>{{ resultConfig.subtitle }}</text>
				</view>
				<view class="result-subtitle" v-else>{{ resultConfig.subtitle }}</view>
				<view class="result-chance">{{ resultConfig.chanceText }}</view>
				<view class="result-primary-btn" v-if="resultConfig.showPrimary" @click="goToIntegralMall">
					前往积分商城兑换
				</view>
				<view class="result-second-btn" @click="closeAnswerResultPopup">继续观看</view>
			</view>
			<view class="result-close" @click.stop="closeAnswerResultPopup">&#10005;</view>
		</view>

		<view class="share-mask" v-if="showSharePopup" @click="closeSharePopup">
			<view class="share-panel" @click.stop>
				<view class="share-card">
					<view class="share-item">
						<image class="share-avatar wechat" src="https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/class/weixin.png"></image>
						<text class="share-text">分享给微信好友</text>
						<button class="share" data-name="shareBtn" open-type="share">分享</button>
					</view>
					<!-- <view class="share-item">
						<image class="share-avatar moments" src="https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/class/pyq.png"></image>
						<text class="share-text">分享到朋友圈</text>
						<button class="share" data-name="shareBtn" open-type="share">分享</button>
					</view> -->
				</view>
				<view class="cancel-btn" @click="closeSharePopup">取消</view>
			</view>
		</view>

		<view class="popup-mask" v-if="showCatalog" @click="showCatalog = false">
			<view class="popup-panel" @click.stop>
				<view class="popup-head">
					<view class="left">
						<image class="dot" src="https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/class/list.png" mode="aspectFit"></image>
						<text class="section-title">视频标题</text>
					</view>
					<view class="close-btn" @click="showCatalog = false">
						<image src="https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/class/close.png" mode="aspectFit"></image>
					</view>
				</view>
				<view class="popup-divider"></view>
				<scroll-view class="popup-scroll" scroll-y>
					<view
						v-for="(item, index) in catalogList"
						:key="item.videoId"
						class="popup-item"
						:class="{ active: activeIndex == item.videoId }"
						@click="selectCourse(item)"
					>
						<view class="catalog-top">
							<view class="catalog-index-wrap">
								<!-- <text class="catalog-index">第{{ index + 1 }}讲</text> -->
								<image class="catalog-active-dot" v-if="activeIndex == item.videoId" src="https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/class/live.png" mode="aspectFit"/></image>
							</view>
							<text class="free-tag">限时免费</text>
						</view>
						<view class="popup-name" :class="{ active: activeIndex == item.videoId }">{{ item.title }}</view>
					</view>
				</scroll-view>
			</view>
		</view>
	</view>
</template>

<script>
import {
	getCourseDetail as fetchCourseDetail,
	addStudyCourse as addStudyCourseApi,
	getCourseVideoList,
	addCommentt,
	getCommentList,
	videoDetails,
	courseAnswer as submitCourseAnswerApi,
	courseAnswerStatus,
	claimCourseAnswerIntegral,
	getInternetTraffic
} from '@/api/class.js'
import dayjs from 'dayjs'
import { generateRandomString } from '@/utils/courseTool.js'
export default {
	computed: {
		/** 播放数：<10万 原样；≥10万且<100万 如 10.0w、11.3w；≥100万 100w+ */
		courseViewsDisplay() {
			const raw = this.courseInfo && this.courseInfo.views;
			const n = Number(raw);
			if (!Number.isFinite(n) || n < 0) {
				return "0";
			}
			if (n < 100000) {
				return String(Math.floor(n));
			}
			if (n < 1000000) {
				return (n / 10000).toFixed(1) + "w";
			}
			return "100w+";
		},
		poster() {
			const item = (this.catalogList || []).find((v) => v.videoId === this.activeIndex);
			return (item && item.imgUrl) || this.courseInfo.imgUrl;
		},
		/** 无有效视频地址，或当前小节无 watchDurationMinutes / 为 null / 非法 / 明确为 0 时，不展示答题浮层 */
		showAnswerEntry() {
			const url = (this.videoUrl && String(this.videoUrl).trim()) || "";
			if (!url) {
				return false;
			}
			const currentLesson =
				(this.catalogList || []).find((v) => v.videoId === this.activeIndex) ||
				(this.catalogList || [])[0] ||
				{};
			const raw = currentLesson.watchDurationMinutes;
			if (raw === undefined || raw === null) {
				return false;
			}
			const minutes = Number(raw);
			if (!Number.isFinite(minutes) || minutes === 0) {
				return false;
			}
			return true;
		},
		canAnswer() {
			return this.answerCountdown <= 0;
		},
		answerCountdownText() {
			const second = this.answerCountdown < 0 ? 0 : this.answerCountdown;
			const minuteNum = Math.floor(second / 60);
			const secondNum = second % 60;
			const ss = String(secondNum).padStart(2, "0");
			if (minuteNum > 0) {
				return minuteNum + ":" + ss;
			}
			return "00:" + ss;
		},
		answerShowCountdownLines() {
			if (this.answerStatus === 4 || this.hasAward) {
				return false;
			}
			// 仅 status===3 表示已达上限；勿用 attemptsLeft<=0：换课后接口若未返回剩余次数会沿用上一节 attemptsLeft=0，误隐藏倒计时
			if (this.answerStatus === 3) {
				return false;
			}
			return !this.canAnswer && this.answerStatus !== 2;
		},
		answerEntryTip() {
			if (this.answerStatus === 4 || this.hasAward) {
				if (this.awardScore > 0) {
					return "已得" + this.awardScore + "积分";
				}
				return "已完成本节答题";
			}
			if (this.answerStatus === 3) {
				return "未答对\n明天再来";
			}
			return "答题得奖励";
		},
		isAnswerReady() {
			if (!this.canAnswer) {
				return false;
			}
			const questionList = this.answerQuestion || [];
			if (questionList.length === 0) {
				return false;
			}
			const selectedCount = Object.keys(this.selectedAnswers || {}).length;
			return selectedCount === questionList.length;
		},
		resultConfig() {
			const configMap = {
				success: {
					title: "恭喜你，回答正确",
					subtitle: "",
					chanceText: "每节课拥有" + this.maxAttempts + "次答题机会",
					showPrimary: true
				},
				fail: {
					title: "很遗憾答错了",
					subtitle: "请继续努力哦",
					chanceText: "每节课拥有" + this.maxAttempts + "次答题机会",
					showPrimary: false
				},
				exhausted: {
					title: "答题次数已用完",
					subtitle: "下次开课再接再厉",
					chanceText: "每节课拥有" + this.maxAttempts + "次答题机会",
					showPrimary: false
				},
				completed: {
					title: "您已完成本节答题",
					subtitle: "奖励已发放，可在积分明细中查看",
					chanceText: "每节课拥有" + this.maxAttempts + "次答题机会",
					showPrimary: true
				}
			};
			return configMap[this.answerResultType] || configMap.fail;
		}
	},
	data() {
		return {
			statusBarHeight: uni.getSystemInfoSync().statusBarHeight + 'px',
			isShu: false,
			isFull: false,
			videoUrl: "",
			videoContext: null,
			playTime: 0,
			videoDuration: 0,
			bufferRate: 0,
			errorCount: 0,
			showCatalog: false,
			showSharePopup: false,
			showAnswerPopup: false,
			showAnswerResultPopup: false,
			activeIndex: 0,
			answerTimer: null,
			answerCountdown: 90,
			selectedAnswers: {},
			answerResultType: "success",
			maxAttempts: 3,
			attemptsLeft: 3,
			correctAnswer: "C",
			awardScore:0,
			hasAward: false,
			/** 答题状态：1未答题 2可答题 3已达上限 4已完成 */
			answerStatus: null,
			answerQuestion: [],
			courseInfo: {
				// title: "邹方斌讲《毛笔书法修心课》",
				// desc: "零基础名师教学零起步，邹方斌讲《毛笔书法修心课》在家也能轻松学书法。",
				// views: "4127946",
				// duration: "45:38",
				// cover: "https://picsum.photos/900/520"
			},
			catalogList: [
				// { id: 1, name: "毛笔书法修心课》在家也能学", free: true },
				// { id: 2, name: "毛笔书法修心课》在家也能轻松学", free: true },
				// { id: 3, name: "毛笔书法修心课》在家也能轻松学", free: false },
				// { id: 4, name: "书法艺术概论", free: true },
				// { id: 5, name: "运笔的基础知识", free: true },
				// { id: 6, name: "字形结构与章法", free: true }
			],
			catalogNum:0,//小节数量
			comments: [
				// {
				// 	id: 1,
				// 	name: "app用户32781",
				// 	time: "今天08:38",
				// 	content: "讲的真好，循序渐进，让小白也很容易能入门观看！",
				// 	avatar: "https://picsum.photos/80/80?1"
				// },
				// {
				// 	id: 2,
				// 	name: "app用户32781",
				// 	time: "2026-02-10 12:37",
				// 	content: "讲的通俗易懂，很好！",
				// 	avatar: "https://picsum.photos/80/80?2"
				// },
				// {
				// 	id: 3,
				// 	name: "app用户32781",
				// 	time: "2026-02-10 12:37",
				// 	content: "赞赞赞，我要好好学！",
				// 	avatar: "https://picsum.photos/80/80?3"
				// }
			],
			menuButtonInfo:{},
			courseId:null,
			videoId:null,
			// 当前课时：已上报过“开始播放”后，才在暂停/离开等时机更新进度
			studyStartReported: false,
			pendingSeekTime: 0,
			hasAppliedInitialStudyLog: false,
			commentContent: "",
			isSendingComment: false,
			commentPageNum: 1,
			commentPageSize: 10,
			commentHasMore: true,
			commentLoading: false,
			commentInitLoaded: false,
			sensitiveWords: ["加微信", "vx", "v信", "微信号", "手机号", "电话", "qq", "QQ", "赌博", "色情"],
			studyLog:{},
			videoInfo:{},
			/** course_auto 流量统计：与 pages_course/video.vue 对齐 */
			trafficCourseExtras: {},
			trafficUrlOption: {},
			trafficUuId: '',
			trafficInterval: null,
			/** 避免 getCourseDetail 与 getCourseVideoList 各调一次 initLessonVideo 导致答题状态接口重复请求 */
			_firstLessonBootstrapped: false,
			_catalogFetchDone: false,
			_detailFetchDone: false,
		};
	},
	onLoad(opt) {
		this.getMenuButtonInfo(); // 初始化获取胶囊信息
		if (opt.course) {
			try {
				this.trafficCourseExtras = JSON.parse(decodeURIComponent(opt.course))
			} catch (e) {
				this.trafficCourseExtras = {}
			}
		}
		if(opt.courseId){
			this.courseId=opt.courseId
			this._firstLessonBootstrapped = false;
			this._catalogFetchDone = false;
			this._detailFetchDone = false;
			this.getCourseDetail(opt.courseId);
			this.getCommentList(opt.courseId, true);
			this.getCourseVideoList(opt.courseId);
		}
		
	},
	//发送给朋友
	onShareAppMessage(res) {
		return {
			title:this.videoInfo.title,
			path: '/pages_index/courseDetail?courseId='+this.courseId,
			imageUrl: this.videoInfo.thumbnail //分享图标，路径可以是本地文件路径、代码包文件路径或者网络图片路径.支持PNG及JPG。显示图片长宽比是 5:4
		}
		
	},
	//分享到朋友圈
	onShareTimeline(res) {
		return {
			title: this.videoInfo.title,
			query:'courseId='+this.courseId,
			imageUrl: this.courseInfo.imgUrl //分享图标，路径可以是本地文件路径、代码包文件路径或者网络图片路径.支持PNG及JPG。显示图片长宽比是 5:4
		}
		
	},
	onReady() {
		this.$nextTick(() => {
			this.videoContext = uni.createVideoContext("video-content-box", this);
			this.tryPlayVideo();
		});
	},
	onHide() {
		this.flushStudyProgress();
		this.clearTrafficInterval();
	},
	onShow() {
		this.trafficUuId = generateRandomString(16)
		if (this.courseId && this.videoId) {
			this.syncTrafficUrlOption()
		}
	},
	onUnload() {
		this.flushStudyProgress();
		this.clearAnswerTimer();
		this.clearTrafficInterval();
	},
	methods: {
		// 获取胶囊按钮布局参数
		getMenuButtonInfo() {
			// 微信小程序API（Uniapp可直接用uni.getMenuButtonBoundingClientRect）
			const menuBtn = uni.getMenuButtonBoundingClientRect();
			const sHeight = uni.getSystemInfoSync().statusBarHeight;
			if (menuBtn) {
				const gapToStatusBar = menuBtn.top - sHeight;
				this.menuButtonInfo = {
					top: menuBtn.top + 'px', // 胶囊顶部距离
					height: menuBtn.height + 'px', // 胶囊高度
					centerY: (menuBtn.top + menuBtn.height / 2) + 'px', // 胶囊垂直居中Y坐标
					right: menuBtn.right + 'px' ,// 胶囊右侧距离
					gapToStatusBar:gapToStatusBar+'px'
				};
			}
		},
		getCourseDetail(courseId){
			fetchCourseDetail({courseId:courseId}).then(
				res => {
					if (res.code == 200) {
						this.courseInfo = res.data?res.data:{},
						this.studyLog = this.courseInfo.studyLog
						//this.videoUrl = res.data.studyLo
					} else {
						uni.showToast({
							icon: 'none',
							title: res.msg,
						});
					}
				},
				rej => {}
			).finally(() => {
				this._detailFetchDone = true;
				this.tryBootstrapFirstLesson();
			});
		},

		getCommentList(courseId, reset = false){
			const targetCourseId = courseId || this.courseId;
			if (!targetCourseId) {
				return;
			}
			if (this.commentLoading) {
				return;
			}
			if (!reset && !this.commentHasMore) {
				return;
			}
			if (reset) {
				this.commentPageNum = 1;
				this.commentHasMore = true;
				this.commentInitLoaded = false;
				this.comments = [];
			}
			const currentPageNum = this.commentPageNum;
			const param = {
				courseId: targetCourseId,
				pageNum: currentPageNum,
				pageSize: this.commentPageSize,
				sortType:2
			}
			this.commentLoading = true;
			getCommentList(param).then(
				res => {
					if (res.code == 200) {
						const list = Array.isArray(res.data)
							? res.data
							: (res.data && Array.isArray(res.data.list) ? res.data.list : []);
						const normalizedList = list.map((item, index) => this.normalizeCommentItem(item, ((currentPageNum - 1) * this.commentPageSize) + index));
						this.comments = reset ? normalizedList : (this.comments || []).concat(normalizedList);
						const total = Number(res.data && res.data.total);
						if (Number.isFinite(total) && total >= 0) {
							this.commentHasMore = this.comments.length < total;
						} else {
							this.commentHasMore = normalizedList.length >= this.commentPageSize;
						}
						if (normalizedList.length > 0) {
							this.commentPageNum = currentPageNum + 1;
						} else {
							this.commentHasMore = false;
						}
					} else {
						uni.showToast({
							icon: 'none',
							title: res.msg,
						});
					}
				},
				rej => {}
			).finally(() => {
				this.commentLoading = false;
				this.commentInitLoaded = true;
			});
		},
		loadMoreComments() {
			this.getCommentList(this.courseId, false);
		},
		normalizeCommentItem(item, index) {
			const avatar = item.avatar || item.avatarUrl || item.headImg || item.headImage || "https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/class/default-avatar.png";
			const name = item.name || item.nickName || item.nickname || item.userName || "匿名用户";
			const time = item.time || item.createTime || item.gmtCreate || "";
			const content = item.content || item.commentContent || item.comment || "";
			return {
				id: item.id || item.commentId || (Date.now() + "_" + index),
				avatar,
				name,
				time,
				content,
				selfOnly: !!item.selfOnly
			};
		},
		/** 进入页或切课后尝试自动播放（部分端需与 autoplay 配合） */
		tryPlayVideo() {
			if (!this.videoContext) {
				this.videoContext = uni.createVideoContext("video-content-box", this);
			}
			const ctx = this.videoContext;
			if (!ctx || !ctx.play) {
				return;
			}
			this.$nextTick(() => {
				setTimeout(() => {
					try {
						ctx.play();
					} catch (e) {
						console.warn("tryPlayVideo", e);
					}
				}, 100);
			});
		},
		/** 课程详情与目录均返回后再 init，保证 studyLog 与 catalog 同时可用且 courseAnswerStatus 只请求一次 */
		tryBootstrapFirstLesson() {
			if (!this.courseId || this._firstLessonBootstrapped) {
				return;
			}
			if (!this._catalogFetchDone || !this._detailFetchDone) {
				return;
			}
			if (!this.catalogList || this.catalogList.length === 0) {
				this._firstLessonBootstrapped = true;
				return;
			}
			this._firstLessonBootstrapped = true;
			if (!this.activeIndex) {
				this.activeIndex = this.catalogList[0].videoId;
			}
			this.studyStartReported = false;
			this.playTime = 0;
			// 须在 initLessonVideo 之后：后者会根据 studyLog 恢复 activeIndex，倒计时须对应当前高亮小节的 watchDurationMinutes
			this.initLessonVideo();
			this.resetAnswerCountdownByCurrentLesson();
			this.$nextTick(() => {
				this.videoContext = uni.createVideoContext("video-content-box", this);
				this.tryPlayVideo();
			});
		},
		initLessonVideo() {
			let item = this.catalogList.find(v => v.videoId === this.activeIndex);
			if (!this.hasAppliedInitialStudyLog) {
				const resumeInfo = this.getResumeInfoFromStudyLog();
				if (resumeInfo && resumeInfo.item) {
					item = resumeInfo.item;
					this.activeIndex = item.videoId;
					this.playTime = resumeInfo.seekTime;
					this.pendingSeekTime = resumeInfo.seekTime;
					this.hasAppliedInitialStudyLog = true;
				}
			}
			if (!item) {
				item = this.catalogList[0];
				this.activeIndex = item ? item.videoId : 0;
			}
			if (!item) {
				this.videoId = null;
				return;
			}
			this.videoInfo=item;
			this.videoId = item.videoId
			this.videoUrl=item.videoUrl
			this.awardScore = item.integralReward;
			this.selectedAnswers = {};
			this.hasAward = false;
			this.answerStatus = null;
			this.getVideoDetail(this.videoId)
			this.loadCourseAnswerStatus(this.videoId)
			this.syncTrafficUrlOption()
		},
		syncTrafficUrlOption() {
			const base = { ...(this.trafficCourseExtras || {}) }
			// #ifdef MP-WEIXIN
			try {
				base.appId = wx.getAccountInfoSync().miniProgram.appId
			} catch (e) {}
			// #endif
			base.courseId = this.courseId
			base.videoId = this.videoId
			base.companyId = 101
			this.trafficUrlOption = base
		},
		clearTrafficInterval() {
			if (this.trafficInterval != null) {
				clearInterval(this.trafficInterval)
				this.trafficInterval = null
			}
		},
		updateTrafficTime() {
			const that = this
			this.clearTrafficInterval()
			this.trafficInterval = setInterval(function () {
				that.getInternetTraffic()
			}, 60000)
		},
		getInternetTraffic() {
			if (!this.videoDuration) {
				return
			}
			const playVideoTime = Math.ceil((this.playTime / this.videoDuration) * 100)
			let buf = this.bufferRate
			if (buf == 0 || buf < playVideoTime) {
				buf = playVideoTime
			}
			if (buf == 0 || Number(Number(buf).toFixed(2)) == 0) {
				return
			}
			const param = {
				...this.trafficUrlOption,
				uuId: dayjs().format('YYYYMMDD') + this.trafficUuId,
				duration: this.playTime,
				bufferRate: Number(Number(buf).toFixed(2)),
			}
			if (!param.bufferRate) {
				return
			}
			getInternetTraffic(param)
		},
		applyAnswerStatusPayload(raw) {
			const d = raw && typeof raw === 'object' ? raw : {};
			const max = Number(d.maxAttempts);
			if (Number.isFinite(max) && max >= 0) {
				this.maxAttempts = max;
			}
			const st = Number(d.status);
			if (Number.isFinite(st)) {
				this.answerStatus = st;
			}
			let left = d.remainingAttempts;
			if (left === undefined || left === null) {
				left = d.remain;
			}
			if ((left === undefined || left === null) && d.usedAttempts != null && Number.isFinite(max)) {
				left = max - Number(d.usedAttempts);
			}
			if (Number.isFinite(Number(left))) {
				this.attemptsLeft = Math.max(0, Math.floor(Number(left)));
			} else if (st === 3 || st === 4) {
				this.attemptsLeft = 0;
			}
			const integral =
				d.integralReward ?? d.integral ?? d.awardIntegral ?? d.score ?? d.awardScore;
			if (integral !== undefined && integral !== null && integral !== '') {
				const n = Number(integral);
				if (Number.isFinite(n)) {
					this.awardScore = n;
				}
			}
			if (st === 4) {
				this.hasAward = true;
				this.answerCountdown = 0;
				this.clearAnswerTimer();
			} else if (st === 3) {
				this.answerCountdown = 0;
				this.clearAnswerTimer();
			} else if (st === 2) {
				this.answerCountdown = 0;
				this.clearAnswerTimer();
			}
		},
		loadCourseAnswerStatus(videoId) {
			if (!this.courseId) {
				return;
			}
			courseAnswerStatus({ courseId: this.courseId, videoId: videoId }).then(
				(res) => {
					if (res.code == 200 && res.data) {
						this.answerStatus = res.data.status
						this.applyAnswerStatusPayload(res.data);
					} else if (res.code != 200) {
						uni.showToast({
							icon: 'none',
							title: res.msg || '获取答题状态失败'
						});
					}
				},
				() => {}
			);
		},
		getResumeInfoFromStudyLog() {
			const log = this.studyLog || {};
			const logVideoId = Number(log.videoId);
			if (!logVideoId || !Array.isArray(this.catalogList) || this.catalogList.length === 0) {
				return null;
			}
			const item = this.catalogList.find(v => Number(v.videoId) === logVideoId);
			if (!item) {
				return null;
			}
			const seekTime = Math.max(0, Math.floor(Number(log.currentTimes) || 0));
			return {
				item,
				seekTime
			};
		},
		getCourseVideoList(courseId) {
			const param = {
				courseId: courseId,
				pageNum:1,
				pageSize:50,
			}
			getCourseVideoList(param).then(
				res => {
					if (res.code == 200) {
						this.catalogList = (res.data && res.data.list) ? res.data.list : [];
						this.catalogNum=res.data.total
						if (this.catalogList.length > 0) {
							// 首次进入优先走 studyLog 对应课时，否则回落第一节（真正 init 在 tryBootstrapFirstLesson）
							if (!this.activeIndex) {
								this.activeIndex = this.catalogList[0].videoId;
							}
						} else {
							this.videoId = null;
							this.videoUrl = "";
						}
					} else {
						uni.showToast({
							icon: 'none',
							title: res.msg,
						});
					}
				},
				rej => {}
			).finally(() => {
				this._catalogFetchDone = true;
				this.tryBootstrapFirstLesson();
			});
		},
		getVideoDetail(videoId) {
			videoDetails({videoId:videoId}).then(
				res => {
					if (res.code == 200) {
						this.answerQuestion= res.data.questionBankList || [],
							this.answerQuestion = this.answerQuestion.map(item => ({
								...item,
								options: JSON.parse(item.question),
								answer: ''
							}))
						
					} else {
						uni.showToast({
							icon: 'none',
							title: res.msg,
						});
					}
				},
				rej => {}
			);
		},
		onTimeUpdate(e) {
			const d = (e && e.detail) || {};
			this.playTime = Math.floor(d.currentTime || 0);
			if (d.duration) {
				this.videoDuration = d.duration;
			}
		},
		onVideoLoadedMetadata() {
			if (this.pendingSeekTime <= 0) {
				return;
			}
			if (!this.videoContext) {
				this.videoContext = uni.createVideoContext("video-content-box", this);
			}
			const seekTime = this.pendingSeekTime;
			this.pendingSeekTime = 0;
			this.$nextTick(() => {
				setTimeout(() => {
					try {
						this.videoContext.seek(seekTime);
						this.playTime = seekTime;
					} catch (e) {
						console.warn("onVideoLoadedMetadata seek failed", e);
					}
				}, 120);
			});
		},
		/** 开始播放时调用一次：建立观看记录 */
		reportStudyOnPlayStart() {
			if (!this.courseId) {
				return;
			}
			if (this.studyStartReported) {
				return;
			}
			this.studyStartReported = true;
			this.saveStudyProgress(this.playTime || 0);
		},
		/** 暂停/离开/结束等：再上报一次，更新已学进度 */
		flushStudyProgress() {
			if (!this.courseId) {
				return;
			}
			if (!this.studyStartReported) {
				return;
			}
			this.saveStudyProgress(this.playTime);
		},
		saveStudyProgress(playTime) {
			let user = uni.getStorageSync('userInfo') || {};
			// 兼容 userInfo 可能被存成 JSON 字符串或对象
			if (typeof user === "string") {
				try {
					user = JSON.parse(user);
				} catch (e) {
					user = {};
				}
			}
			const param = {
				courseId: this.courseId,
				duration: playTime,
				videoId: this.videoId,
				userId: user.userId || user.id || null
			}
			if (!param.userId) {
				console.warn("saveStudyProgress: userId is empty", user);
				return;
			}
			addStudyCourseApi(param).then(
				res => {
					if (res.code == 200) {
					} else {
						uni.showToast({
							icon: 'none',
							title: res.msg,
						});
					}
				},
				rej => {}
			);
		},
		getCurrentUser() {
			let user = uni.getStorageSync("userInfo") || {};
			if (typeof user === "string") {
				try {
					user = JSON.parse(user);
				} catch (e) {
					user = {};
				}
			}
			return user || {};
		},
		ensureLogin() {
			const user = this.getCurrentUser();
			const userId = user.userId;
			if (userId) {
				return user;
			}
			uni.showModal({
				title: "提示",
				content: "请先登录后再发表评论",
				confirmText: "去登录",
				success: (res) => {
					if (res.confirm) {
						uni.navigateTo({
							url: "/pages/auth/login"
						});
					}
				}
			});
			return null;
		},
		submitComment() {
			if (this.isSendingComment) {
				return;
			}
			const content = (this.commentContent || "").trim();
			if (!content) {
				uni.showToast({
					title: "请输入评论内容",
					icon: "none"
				});
				return;
			}
			if (content.length > 50) {
				uni.showToast({
					title: "评论最多50字",
					icon: "none"
				});
				return;
			}
			if (!this.courseId) {
				uni.showToast({
					title: "课程信息异常，请稍后重试",
					icon: "none"
				});
				return;
			}
			const user = this.ensureLogin();
			if (!user) {
				return;
			}
			if (this.hasSensitiveWord(content)) {
				const now = this.formatNowTime();
				const localComment = this.normalizeCommentItem({
					id: "local_" + Date.now(),
					name: user.nickName || user.nickname || user.userName || "我",
					time: now,
					content: content,
					avatar: user.avatar || user.avatarUrl || user.headImg || "https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/class/default-avatar.png",
					selfOnly: true
				}, 0);
				this.comments = [localComment].concat(this.comments || []);
				this.commentContent = "";
				uni.showToast({
					title: "含敏感词，评论仅自己可见",
					icon: "none"
				});
				return;
			}
			const userId = user.userId;
			this.isSendingComment = true;
			const param = {
				courseId: this.courseId,
				toUserId: userId,
				content: content,
				type:1,
			};
			addCommentt(param).then(
				(res) => {
					if (res.code == 200) {
						this.commentContent = "";
						uni.showToast({
							title: "评论成功",
							icon: "none"
						});
						this.getCommentList(this.courseId, true);
					} else {
						uni.showToast({
							icon: "none",
							title: res.msg || "评论失败"
						});
					}
				},
				() => {}
			).finally(() => {
				this.isSendingComment = false;
			});
		},
		hasSensitiveWord(content) {
			const text = (content || "").toLowerCase();
			return this.sensitiveWords.some((word) => text.indexOf(String(word).toLowerCase()) > -1);
		},
		formatNowTime() {
			const now = new Date();
			const year = now.getFullYear();
			const month = String(now.getMonth() + 1).padStart(2, "0");
			const day = String(now.getDate()).padStart(2, "0");
			const hour = String(now.getHours()).padStart(2, "0");
			const minute = String(now.getMinutes()).padStart(2, "0");
			return year + "-" + month + "-" + day + " " + hour + ":" + minute;
		},
		progressChange(e) {
			const d = (e && e.detail) || {};
			if (d.buffered != null) {
				this.bufferRate = d.buffered;
			}
		},
		videoErrorCallback(e) {
			this.errorCount += 1;
			console.error("courseDetail video error", e);
			if (this.errorCount > 3) {
				return;
			}
			uni.showToast({
				title: "视频加载失败，请稍后重试",
				icon: "none"
			});
		},
		getPlay() {
			this.errorCount = 0;
			this.reportStudyOnPlayStart();
			this.updateTrafficTime();
		},
		getPause() {
			this.flushStudyProgress();
		},
		getEnded() {
			if (this.videoDuration) {
				this.playTime = Math.floor(this.videoDuration);
			}
			if (!this.courseId) {
				return;
			}
			if (!this.studyStartReported) {
				this.studyStartReported = true;
			}
			this.saveStudyProgress(this.playTime);
			this.getInternetTraffic();
			// 当前小节播放结束后自动切换下一讲（已在上方保存进度，避免 selectCourse 内再次 flush 重复上报）
			const list = this.catalogList || [];
			const idx = list.findIndex((v) => v.videoId == this.activeIndex);
			if (idx >= 0 && idx < list.length - 1) {
				this.$nextTick(() => {
					this.selectCourse(list[idx + 1], { skipFlush: true });
				});
			}
		},
		fullscreenchange(e) {
			const d = (e && e.detail) || {};
			this.isFull = d.fullScreen;
		},
		getCurrentLessonWatchSeconds() {
			const currentLesson = this.catalogList.find(v => v.videoId === this.activeIndex) || this.catalogList[0] || {};
			const raw = currentLesson.watchDurationMinutes;
			const minutes = Number(raw);
			// 未配置或非法值：沿用默认 90 秒；明确为 0 表示不要求观看时长，不展示倒计时
			if (!raw||raw === null || raw === undefined || !Number.isFinite(minutes)) {
				return 0;
			}
			if (minutes === 0) {
				return 0;
			}
			return Math.floor(minutes * 60);
		},
		resetAnswerCountdownByCurrentLesson() {
			this.answerCountdown = this.getCurrentLessonWatchSeconds();
			this.startAnswerCountdown();
		},
		startAnswerCountdown() {
			this.clearAnswerTimer();
			if (this.answerCountdown <= 0) {
				return;
			}
			this.answerTimer = setInterval(() => {
				if (this.answerCountdown <= 0) {
					this.clearAnswerTimer();
					return;
				}
				this.answerCountdown -= 1;
			}, 1000);
		},
		clearAnswerTimer() {
			if (this.answerTimer) {
				clearInterval(this.answerTimer);
				this.answerTimer = null;
			}
		},
		openAnswerPopup() {
			const user = this.getCurrentUser();
			if (!user || !user.userId) {
				uni.showModal({
					title: '提示',
					content: '请先登录后再答题',
					confirmText: '去登录',
					success: (res) => {
						if (res.confirm) {
							uni.navigateTo({ url: '/pages/auth/login' });
						}
					}
				});
				return;
			}
			if (!this.courseId || !this.videoId) {
				uni.showToast({ title: '课程信息异常', icon: 'none' });
				return;
			}
			courseAnswerStatus({ courseId: this.courseId, videoId: this.videoId }).then(
				(res) => {
					if (res.code != 200 || !res.data) {
						uni.showToast({
							title: res.msg || '获取答题状态失败',
							icon: 'none'
						});
						return;
					}
					this.applyAnswerStatusPayload(res.data);
					const st = this.answerStatus;
					if (st === 3 ) {
						this.answerResultType = 'exhausted';
						this.showAnswerResultPopup = true;
						return;
					}
					if (st === 4) {
						this.answerResultType = 'success';
						this.showAnswerResultPopup = true;
						return;
					}
					if (!this.answerQuestion || this.answerQuestion.length === 0) {
						uni.showToast({ title: '暂无题目', icon: 'none' });
						return;
					}
					// if (st !== 2 && !this.canAnswer) {
					// 	uni.showToast({ title: '请继续观看课程后再答题', icon: 'none' });
					// 	return;
					// }
					this.selectedAnswers = {};
					this.showAnswerPopup = true;
				},
				() => {
					uni.showToast({ title: '网络异常，请稍后重试', icon: 'none' });
				}
			);
		},
		closeAnswerPopup() {
			this.showAnswerPopup = false;
		},
		closeAnswerResultPopup() {
			this.showAnswerResultPopup = false;
		},
		selectAnswer(questionIndex, optionIndex) {
			if (!this.canAnswer) {
				return;
			}
			this.$set(this.selectedAnswers, questionIndex, optionIndex);
		},
		submitAnswer() {
			if (!this.isAnswerReady) {
				return;
			}
			this.showAnswerPopup = false;
			const user = this.getCurrentUser();
			const questions = this.answerQuestion.map((obj, questionIndex) => {
				const { options, ...rest } = obj;
				const optionList = options || [];
				const selectedOptionIndex = this.selectedAnswers[questionIndex];
				const opt =
					selectedOptionIndex === undefined || selectedOptionIndex === null
						? null
						: optionList[selectedOptionIndex];
				return {
					...rest,
					answer: opt ? opt.name : ''
				};
			});
			const param = {
				courseId: this.courseId,
				videoId: this.videoId,
				duration: this.playTime,
				questions
			};
			if (user && user.userId) {
				param.userId = user.userId;
			}
			submitCourseAnswerApi(param).then(
				(res) => {
					this.selectedAnswers = {};
					if (res.code == 200) {
						const wrong =
							res.incorrectQuestions &&
							Array.isArray(res.incorrectQuestions) &&
							res.incorrectQuestions.length > 0;
						if (res.msg == '答题成功' && !wrong) {
							this.answerResultType = 'success';
							this.hasAward = true;
							this.loadCourseAnswerStatus(this.videoId);
							this.claimIntegralReward();
							this.showAnswerResultPopup = true;
							return;
						}
						if (wrong || res.remain !== undefined) {
							if (res.remain !== undefined && res.remain !== null) {
								this.attemptsLeft = Math.max(0, Number(res.remain));
							} else {
								this.attemptsLeft = Math.max(0, this.attemptsLeft - 1);
							}
							this.answerResultType =
								this.attemptsLeft > 0 ? 'fail' : 'exhausted';
							this.loadCourseAnswerStatus(this.videoId);
							this.showAnswerResultPopup = true;
							return;
						}
						this.answerResultType = 'exhausted';
						this.loadCourseAnswerStatus(this.videoId);
						this.showAnswerResultPopup = true;
					} else {
						uni.showToast({
							icon: 'none',
							title: res.msg || '提交失败'
						});
					}
				},
				() => {}
			);
		},
		claimIntegralReward() {
			const data = {
				courseId: this.courseId,
				videoId: this.videoId
			};
			claimCourseAnswerIntegral(data).then(
				(res) => {
					if (res.code == 200) {
						const earned =
							res.data &&
							(res.data.integral ??
								res.data.score ??
								res.data.integralReward);
						if (earned !== undefined && earned !== null && earned !== '') {
							const n = Number(earned);
							if (Number.isFinite(n)) {
								this.awardScore = n;
							}
						}
					} else {
						uni.showToast({
							icon: 'none',
							title: res.msg || '领取积分失败'
						});
					}
				},
				() => {}
			);
		},
		goToIntegralMall() {
			this.showAnswerResultPopup = false;
			uni.navigateTo({
				url: "/pages_user/user/integralGoodsList"
			});
		},
		goBack() {
			uni.navigateBack({
				delta: 1,
				fail: () => {
					uni.switchTab({
						url: "/pages/home/index"
					});
				}
			});
		},
		selectCourse(item, opts) {
			if (item.videoId == this.activeIndex) {
				this.showCatalog = false;
				return;
			}
			if (!opts || !opts.skipFlush) {
				this.flushStudyProgress();
			}
			this.activeIndex = item.videoId;
			this.videoInfo = item;
			this.resetAnswerCountdownByCurrentLesson();
			this.showCatalog = false;
			this.studyStartReported = false;
			this.playTime = 0;
			this.pendingSeekTime = 0;
			this.hasAppliedInitialStudyLog = true;
			this.initLessonVideo();
			this.$nextTick(() => {
				this.videoContext = uni.createVideoContext("video-content-box", this);
				this.tryPlayVideo();
			});
		},
		handleShare() {
			this.showSharePopup = true;
		},
		closeSharePopup() {
			this.showSharePopup = false;
		},
		onShareSelect(type) {
			this.showSharePopup = false;
			const shareText = type === "wechat" ? "微信好友" : "朋友圈";
			uni.showToast({
				title: "分享至" + shareText + "待接入",
				icon: "none"
			});
		}
	}
};
</script>

<style scoped lang="scss">
.page {
	background: #f6f6f6;
	height: 100vh;
}
.back-box{
	position: fixed;
	left:12px;
	z-index:9999
}
.page-scroll {
	height: calc(100vh - 184rpx);
	box-sizing: border-box;
	padding-top: calc(420rpx + 88rpx);
}

.video-wrap {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 20;
	width: 100%;
	// height: 420rpx;
}

.video-cover {
	width: 100%;
	height: 100%;
}

.video-mask {
	position: absolute;
	inset: 0;
	background: rgba(0, 0, 0, 0.2);
}

.top-left {
	position: absolute;
	left: 24rpx;
	top: 24rpx;
	color: #fff;
	font-size: 56rpx;
	z-index: 2;
}

.top-right {
	position: absolute;
	right: 24rpx;
	top: 24rpx;
	display: flex;
	gap: 12rpx;
	z-index: 2;
}

.dot-btn {
	min-width: 56rpx;
	height: 56rpx;
	padding: 0 18rpx;
	border-radius: 28rpx;
	background: rgba(0, 0, 0, 0.45);
	color: #fff;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 26rpx;
}

.video-control {
	position: absolute;
	bottom: 18rpx;
	left: 24rpx;
	right: 24rpx;
	z-index: 2;
	display: flex;
	align-items: center;
	color: #fff;
	font-size: 24rpx;
}

.play-icon {
	margin-right: 12rpx;
	font-size: 28rpx;
}

.time-text {
	min-width: 70rpx;
}

.progress-line {
	flex: 1;
	height: 4rpx;
	margin: 0 14rpx;
	background: rgba(255, 255, 255, 0.85);
}

.content {
	background: #fff;
	padding:30rpx 24rpx;
}

.course-title {
	font-family: PingFangSC, PingFang SC;
	font-weight: 600;
	font-size: 40rpx;
	color: rgba(0,0,0,0.85);
	line-height: 56rpx;
	text-align: justify;
}

.course-desc {
	margin-top: 20rpx;
	font-family: PingFangSC, PingFang SC;
	font-weight: 400;
	font-size: 32rpx;
	color: rgba(0,0,0,0.65);
	line-height: 44rpx;
	text-align: justify;
}

.course-views {
	margin-top: 20rpx;
	font-family: PingFangSC, PingFang SC;
	font-weight: 400;
	font-size: 32rpx;
	color: rgba(0,0,0,0.45);
	line-height: 44rpx;
	text-align: justify;
}

.section-head {
	margin-top: 14rpx;
	padding: 18rpx 24rpx 0;
	background: #fff;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

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

.dot {
	margin-right: 14rpx;
		width:32rpx;
		height: 32rpx;
}

.section-title {
	font-family: PingFangSC, PingFang SC;
	font-weight: 600;
	font-size: 36rpx;
	color: #222222;
	line-height: 50rpx;
}

.count {
	font-family: PingFangSC, PingFang SC;
	font-weight: 400;
	font-size: 32rpx;
	color: rgba(0,0,0,0.45);
    display: flex;
    align-items: center;
}

.catalog-scroll {
	padding: 24rpx;
	background: #fff;
	white-space: nowrap;
	box-sizing: border-box;
}

.catalog-row {
	display: inline-flex;
	gap: 24rpx;
}

.catalog-item {
	width: 280rpx;
	min-height: 192rpx;
	background: #FFF0F2;
	border-radius: 20rpx;
	background: #f2f3f6;
	padding:24rpx;
	box-sizing: border-box;
	position: relative;
}

.catalog-item.active {
	background: #ffeef1;
	border-color: #ffd7de;
}

.catalog-top {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.catalog-index-wrap {
	display: flex;
	align-items: center;
}

.catalog-index {
	font-family: PingFangSC, PingFang SC;
	font-weight: 600;
	font-size: 32rpx;
	color: #FF233C;
	line-height: 44rpx;
}

.catalog-active-dot {
	width: 32rpx;
	height: 32rpx;
	margin-left: 10rpx;
	border-radius: 50%;
	position: relative;
}

// .catalog-active-dot::after {
// 	content: "";
// 	position: absolute;
// 	left: 5rpx;
// 	top: 5rpx;
// 	width: 8rpx;
// 	height: 8rpx;
// 	border-radius: 50%;
// 	background: #fff;
// }

.free-tag {
	position: absolute;
	right: 0;
	top:0;
	padding:2rpx 10rpx;
	background: #ff2b49;
	border-radius: 0rpx 20rpx 0rpx 20rpx;
	font-family: PingFangSC, PingFang SC;
	font-weight: 400;
	font-size: 28rpx;
	color: #FFFFFF;
	line-height: 40rpx;
}

.catalog-name {
	margin-top: 12rpx;
	font-family: PingFangSC, PingFang SC;
	font-weight: 400;
	font-size: 32rpx;
	color: rgba(0,0,0,0.65);
	line-height: 44rpx;
	white-space: normal;
	word-break: break-all;
	overflow: hidden;
	text-overflow: ellipsis;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
}
.catalog-name.active {
	color: #FF233C;
}

.comment-wrap {
	margin-top: 20rpx;
	background: #fff;
	padding: 24rpx;
}

.comment-title {
	font-family: PingFangSC, PingFang SC;
	font-weight: 600;
	font-size: 36rpx;
	color: #222222;
	line-height: 50rpx;
	margin-bottom: 24rpx;
}

.comment-item {
	display: flex;
	padding-bottom: 24rpx;
}

.comment-empty {
	padding: 30rpx 0;
	text-align: center;
	font-size: 30rpx;
	color: #999;
}

.comment-load-status {
	padding: 20rpx 0 8rpx;
	text-align: center;
	font-size: 28rpx;
	color: #999;
}

.avatar {
	width: 90rpx;
	height: 90rpx;
	border-radius: 50%;
	margin-right: 12rpx;
}

.comment-main {
	flex: 1;
}

.name {
	font-family: PingFangSC, PingFang SC;
	font-weight: 600;
	font-size: 32rpx;
	color: #222222;
	line-height: 44rpx;
}

.self-only-tag {
	font-size: 26rpx;
	color: #ff3b57;
	margin-left: 8rpx;
	font-weight: 400;
}

.time {
	font-family: PingFangSC, PingFang SC;
	font-weight: 400;
	font-size: 28rpx;
	color: rgba(0,0,0,0.45);
	line-height: 40rpx;
	margin-top: 12rpx;
}

.text {
	font-family: PingFangSC, PingFang SC;
	font-weight: 400;
	font-size: 32rpx;
	color: #222222;
	line-height: 40rpx;
	margin-top: 12rpx;
}

.bottom-space {
	height: 40rpx;
}

.answer-entry {
	position: fixed;
	right: 34rpx;
	bottom: 320rpx;
	z-index: 28;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.gift-icon {
	width: 210rpx;
	height: 90rpx;
	margin-bottom: -10rpx;
}

.answer-tip {
	width: 210rpx;
	// height: 188rpx;
	background: linear-gradient( 180deg, #FFF9DC 0%, #FFDC97 100%);
	border-radius: 20rpx;
	//border: 2rpx solid transparent;
	//border-image: linear-gradient(180deg, rgba(255, 228, 105, 1), rgba(255, 178, 30, 1)) 2 2;
	font-family: PingFangSC, PingFang SC;
	font-weight: 600;
	font-size: 32rpx;
	color: #FF2E3F;
	line-height: 44rpx;
	padding: 20rpx 0;
	display: flex;
	flex-direction: column;
	align-items: center;
	text-align: center;
	box-sizing: border-box;
}

.answer-tip-line {
	display: block;
	width: 100%;
	word-break: keep-all;
	white-space: nowrap;
	line-height: 44rpx;
}

.answer-tip-line-first {
	margin-bottom: 4rpx;
}

.answer-tip-single {
	display: block;
	line-height: 44rpx;
}
.answer-tip-single2 {
	display:flex;
	align-items: baseline;
	font-family: PingFangSC, PingFang SC;
	font-weight: 400;
	font-size: 28rpx;
	color: #FF2E3F;
	.jifen{
		font-family: PingFangSC, PingFang SC;
		font-weight: 600;
		font-size: 56rpx;
		color: #FF2E3F;
	}
}
.answer-tip.done {
	border-color: #f2be3f;
	color: #c53533;
}

.answer-btn {
	margin-top: 8rpx;
	width: 150rpx;
	height: 60rpx;
	background: linear-gradient( 135deg, #FF515F 0%, #F72234 100%);
	border-radius: 30rpx;
	font-family: PingFangSC, PingFang SC;
	font-weight: 600;
	font-size: 32rpx;
	color: #FFF2C3;
	line-height: 60rpx;
	text-align: center;
}

.bottom-bar {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	background: #fff;
	// border-top: 1rpx solid #eee;
	display: flex;
	align-items: center;
	padding: 20rpx 24rpx 68rpx;
	box-sizing: border-box;
}

.input {
	flex: 1;
	height: 96rpx;
	background: #F5F5F5;
	border-radius: 48rpx;
	padding: 0 30rpx;
	font-family: PingFangSC, PingFang SC;
	font-weight: 400;
	font-size: 32rpx;
	//color: rgba(0,0,0,0.25);
	display: flex;
	align-items: center;
}

.send-btn {
	margin-left: 24rpx;
	margin-right: 24rpx;
	width: 160rpx;
	height: 96rpx;
	background: linear-gradient( 135deg, #FF5267 0%, #FF233C 100%);
	border-radius: 48rpx;
	color: #fff;
	font-family: PingFangSC, PingFang SC;
	font-weight: 600;
	font-size: 40rpx;
	color: #FFFFFF;
	display: flex;
	align-items: center;
	justify-content: center;
}

.send-btn.disabled {
	background: #ff9baa;
}

.comment-input {
	box-sizing: border-box;
}

.comment-input-placeholder {
	color: #bbb;
}

.share-btn {
	display: flex;
	flex-direction: column;
	align-items: center;
	font-family: PingFangSC, PingFang SC;
	font-weight: 600;
	font-size: 32rpx;
	color: #222222;
	line-height: 44rpx;
	text-align: center;
	image{
		width: 52rpx;
		height: 52rpx;
	}
}

.share-icon {
	color: #ff3b57;
	font-size: 36rpx;
	line-height: 1;
}

.share-mask {
	position: fixed;
	inset: 0;
	background: rgba(0, 0, 0, 0.45);
	z-index: 120;
	display: flex;
	align-items: flex-end;
}

.share-panel {
	width: 100%;
	padding: 20rpx 20rpx 28rpx;
	box-sizing: border-box;
	background: #F4F6F7;
	border-radius: 20rpx 20rpx 0rpx 0rpx;
}

.share-card {
	background: #fff;
	border-radius: 12rpx;
	padding: 40rpx;
	overflow: hidden;
}

.share-item {
	//height: 106rpx;
	display: flex;
	align-items: center;
	background: #fff;
	position: relative;
	// &:first-child{
	// 	margin-bottom: 40rpx;
	// }
	.share {
		display: inline-block;
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		opacity: 0;
	}
}

.share-avatar {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	margin-right: 20rpx;
}

.wechat {
	
}

.moments {
	
}

.share-text {
	font-family: PingFangSC, PingFang SC;
	font-weight: 400;
	font-size: 36rpx;
	color: rgba(0,0,0,0.85);
	line-height: 50rpx;
}

.cancel-btn {
	margin-top: 20rpx;
	height: 96rpx;
	background: #fff;
	border-radius: 48rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-family: PingFangSC, PingFang SC;
	font-weight: 400;
	font-size: 32rpx;
	color: rgba(0,0,0,0.85);
}

.answer-mask {
	position: fixed;
	inset: 0;
	background: rgba(0, 0, 0, 0.45);
	display: flex;
	align-items: flex-end;
	z-index: 130;
}

.answer-panel {
	width: 100%;
	background: #fff;
	border-radius: 24rpx 24rpx 0 0;
	padding: 20rpx 22rpx 30rpx;
	box-sizing: border-box;
}

.answer-head {
	display: flex;
	align-items: center;
	justify-content: space-between;
	.dot{
		width: 32rpx;
		height: 32rpx;
		margin-right: 10rpx;
	}
}

.answer-divider {
	margin-top: 26rpx;
	height: 1rpx;
	background: #D8D8D8;
}

.question-title {
	margin-top: 18rpx;
	font-size: 46rpx;
	font-weight: 600;
	color: #222;
	line-height: 60rpx;
}

.answer-option {
	margin-top: 18rpx;
	background: #f3f4f7;
	border-radius: 16rpx;
	padding: 22rpx 24rpx;
	font-size: 42rpx;
	color: #333;
	line-height: 48rpx;
}

.answer-option.active {
	background: #ffedf0;
	color: #ff2b49;
	font-weight: 600;
}

.answer-option.disabled {
	color: #4a4a4a;
}

.submit-btn {
	margin: 48rpx auto 0;
	width: 690rpx;
	max-width: 100%;
	height: 88rpx;
	border-radius: 44rpx;
	background: #c3c4c8;
	color: #fff;
	font-size: 40rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.submit-btn.active {
	background: #ff3b57;
}

.submit-btn.disabled {
	background: #c3c4c8;
}

.answer-result-mask {
	position: fixed;
	inset: 0;
	background: rgba(0, 0, 0, 0.45);
	display: flex;
	align-items: center;
	justify-content: center;
	flex-direction: column;
	z-index: 135;
}

.answer-result-panel {
	width: 660rpx;
	background: #fff;
	border-radius: 28rpx;
	padding:40rpx;
	box-sizing: border-box;
	text-align: center;
	display: flex;
	align-items: center;
	flex-direction: column;
}

.result-title {
	font-family: PingFangSC, PingFang SC;
	font-weight: 600;
	font-size: 40rpx;
	color: #000000;
	line-height: 56rpx;
	text-align: center;
}

.result-subtitle {
	margin-top: 40rpx;
	font-family: PingFangSC, PingFang SC;
	font-weight: 600;
	font-size: 36rpx;
	color: rgba(0,0,0,0.85);
	line-height: 50rpx;
	text-align: center;
}

.result-score {
	color: #ff2b49;
	font-size: 56rpx;
	font-weight: 600;
}

.result-chance {
	margin-top: 24rpx;
	font-family: PingFangSC, PingFang SC;
	font-weight: 400;
	font-size: 32rpx;
	color: rgba(0,0,0,0.65);
	line-height: 44rpx;
	text-align: center;
}

.result-primary-btn {
	margin-top: 40rpx;
	width: 390rpx;
	height: 84rpx;
	background: linear-gradient( 135deg, #FF5267 0%, #FF233C 100%);
	border-radius: 42rpx;
	font-family: PingFangSC, PingFang SC;
	font-weight: 500;
	font-size: 32rpx;
	color: #FFFFFF;
	display: flex;
	align-items: center;
	justify-content: center;
}

.result-second-btn {
	margin-top: 40rpx;
	width: 390rpx;
	height: 84rpx;
	border-radius: 42rpx;
	border: 2rpx solid #FF233C;
	font-family: PingFangSC, PingFang SC;
	font-weight: 600;
	font-size: 32rpx;
	color: #FF233C;
	display: flex;
	align-items: center;
	justify-content: center;
}

.result-close {
	margin-top: 30rpx;
	width: 60rpx;
	height: 60rpx;
	border-radius: 50%;
	border: 2rpx solid #fff;
	color: #fff;
	font-size: 34rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.popup-mask {
	position: fixed;
	inset: 0;
	background: rgba(0, 0, 0, 0.45);
	display: flex;
	align-items: flex-end;
	z-index: 99;
}

.popup-panel {
	width: 100%;
	height: 66vh;
	background: #fff;
	border-radius: 28rpx 28rpx 0 0;
	padding: 24rpx;
	box-sizing: border-box;
}
.popup-divider {
	margin-top: 26rpx;
	height: 1rpx;
	background: #D8D8D8;
}
.popup-head {
	display: flex;
	align-items: center;
	justify-content: space-between;
	.dot{
		width: 32rpx;
		height: 32rpx;
		margin-right: 10rpx;
	}
}

.close-btn {
	width: 60rpx;
	height: 60rpx;
	border-radius: 50%;
	background: #f3f3f3;
	color: #999;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 28rpx;
	image{
		width: 100%;
		height: 100%;
	}
}

.popup-scroll {
	height: calc(66vh - 160rpx);
	margin-top: 24rpx;
}

.popup-item {
	background: #f5f5f5;
	border-radius: 16rpx;
	padding: 16rpx;
	margin-bottom: 14rpx;
	position: relative;
}

.popup-item.active {
	background: #FFF0F2;
}

.popup-name {
	margin-top: 8rpx;
	font-family: PingFangSC, PingFang SC;
	font-weight: 400;
	font-size: 32rpx;
	color: rgba(0,0,0,0.65);
	line-height: 44rpx;
}
.popup-name.active {
	color: #FF233C;
}
</style>
