<template>
	<zzx-navbar :scrollable="true" :back="true" title="详情"></zzx-navbar>
	<view class="detail-header">
		<image class="header-bg" :src="courseDetailInfo?.cover" mode="">
		</image>
		<view class="back-icon" :style="{ paddingTop: (statusBarHeight + 10) + 'px' }" @click="RouterUtils.back()">
			<zzx-icon name="back"></zzx-icon>
		</view>
		<view :style="{ height: (statusBarHeight + 70) + 'px' }"></view>
		<scroll-view class="header-swiper content" scroll-x="true" :show-scrollbar="false">
			<view class="swiper-inner">
				<block v-if="courseDetailInfo?.video">
					<video v-for="(item, index) in videoList" :key="index" :src="item"></video>
				</block>
				<image @click="_previewImage(bannerList, item)" v-for="(item, index) in bannerList" :key="index"
					:src="item" mode=""></image>
			</view>
		</scroll-view>
	</view>
	<view :style="{ height: (statusBarHeight + 34) + 'px' }"></view>
	<view class="header-info">
		<view class="c-price-info">
			<view class="price-info">
				<view class="new-price">￥{{ courseDetailInfo?.sellingPrice.toFixed(2) }}</view>
				<view class="old-price" v-if="courseDetailInfo?.originalPrice">￥{{
					courseDetailInfo?.originalPrice.toFixed(2) }}</view>
			</view>
			<view class="sales">年售{{ courseDetailInfo?.sales }}</view>
		</view>
		<view class="c-name">
			{{ courseDetailInfo?.name }}
		</view>
		<view class="c-detail-info">
			<view class="c-time">课时：{{ courseDetailInfo?.startTime }}-{{ courseDetailInfo?.endTime }}</view>
			<view class="c-address" @click="openMap">
				<view class="">上课地点：{{ courseDetailInfo?.address }} | {{ courseDetailInfo?.km.toFixed(2) }} km</view>
				<zzx-icon name="ashRight" size="10"></zzx-icon>
			</view>
			<view class="c-instructor">
				<view class="c-instructor-title">授课教练：</view>
				<view class="c-instructor-name">
					<image :src="courseDetailInfo?.instructorAvatar" mode=""></image>
					<view class="">{{ courseDetailInfo?.instructorName }}</view>
				</view>
			</view>
		</view>
		<view class="c-line"></view>
		<view class="c-rules">限制：每人限购{{courseDetailInfo?.limitNum}}张</view>
	</view>
	<view class="content">
		<uv-sticky offset-top="70">
			<view class="detail-select">
				<view :class="sel_index === index ? 'select-text' : 'notsel-text'" v-for="(item, index) in selectList"
					:key="index" @click="sel_tab(index)">
					<text>{{ item }}</text>
				</view>
			</view>
		</uv-sticky>
		<view class="c-tabbar">
			<view class="c-tabbar-detail" id="detail">
				<rich-text :nodes="courseDetailInfo?.details"></rich-text>
			</view>
			<view class="c-notice" id="notice">
				<view class="title">购买须知</view>
				<view class="tips-text">
					<view class="text">
						<rich-text :nodes="courseDetailInfo?.reminder"></rich-text>
					</view>
					<!-- <view class="more">
						<text>查看更多</text>
						<zzx-icon name="more" size="10"></zzx-icon>
					</view> -->
				</view>
			</view>
			<view class="c-schedule" id="schedule">
				<view class="title">课程表</view>
				<view class="list-card">
					<view class="card-title">总共{{ courseDetailInfo?.courseDetail?.length }}节</view>
					<view class="schedule-list" v-for="item in courseDetailInfo?.courseDetail" :key="item.id">
						<view class="time">
							<text>{{ item.startTime }}-{{ item.endTime }}</text>
						</view>
						<view class="name">{{ item?.name }}</view>
					</view>
					<!-- <view class="more">
						<text>查看更多</text>
						<zzx-icon name="more" size="10"></zzx-icon>
					</view> -->
				</view>
			</view>
			<view class="appraise-card" id="appraise">
				<view class="appraise-title">
					<view class="title">评价</view>
					<view class="comments">
						<view class="a-star">
							<zzx-icon name="star" size="10"></zzx-icon>
							<text>{{ appraiseList.averageScore }}</text>
						</view>
						<view class="a-text">| {{ appraiseList.scoreNum }}人评论</view>
					</view>
				</view>
				<view class="appraise-info" v-for="item in appraiseList.records" :key="item.id">
					<view class="a-user-info">
						<view class="info">
							<image :src="item.avatar" mode=""></image>
							<view class="name">{{ item.username }}</view>
						</view>
						<view class="time">{{ DateUtils.formatDateToMMDD(item.createTime) }}</view>
					</view>
					<view class="a-score">
						<text>{{ item.score.toFixed(1) }}</text>
						<uni-rate :readonly="true" size="16" :value="item.score" />
					</view>
					<view class="a-content">
						{{ item.evaluateContent }}
					</view>
					<scroll-view class="scroll-view_H" scroll-x="true" :show-scrollbar="false">
						<view class="scroll-view-item_H uni-bg-red" v-for="(img, idx) in item.images.split(',')"
							:key="idx">
							<image @click="_previewImage(item.images.split(','), img)" :src="img" mode=""></image>
						</view>
					</scroll-view>
				</view>
				<view class="not-data" v-if="!appraiseList?.records?.length">暂无评价数据</view>
			</view>
		</view>
	</view>
	<view style="height: 160rpx;"></view>
	<view class="c-bottom">
		<view class="c-share">
			<zzx-icon name="share"></zzx-icon>
			<view class="">分享</view>
			<button class="g-share-btn" open-type="share"></button>
		</view>
		<view class="c-buy-btn">
			<view class="buy" v-if="type == 3" @click="toOrderPage(0)">
				<view class="buy-text">抢购</view>
				<view class="buy-price">
					<text>￥{{ courseDetailInfo?.sellingPrice }}</text>
					<text>省10</text>
				</view>
			</view>
			<block v-else>
				<view class="buy" @click="toOrderPage(0)">
					<view class="buy-text">直接购买</view>
					<view class="buy-price">
						<text>￥{{ courseDetailInfo?.sellingPrice }}</text>
						<text v-if="courseDetailInfo?.originalPrice">省{{ (courseDetailInfo?.originalPrice -
							courseDetailInfo?.sellingPrice) }}</text>
					</view>
				</view>
				<view class="gratis" @click="toOrderPage(1)" v-if="courseDetailInfo?.hasDiscount">
					<view class="gratis-tips">只能试听第一节，请按课表上课，超时作废</view>
					免费试听
				</view>
			</block>
		</view>
	</view>
</template>

<script lang="ts" setup>
import { ref, onMounted, getCurrentInstance, nextTick } from 'vue';
import { RouterUtils, _previewImage, TipsUtils } from '@/utils/util';
import { http } from '@/utils/http'
import zzxNavbar from '@/components/zzx-navbar/zzx-navbar.vue';
import { onLoad, onPageScroll, onShareAppMessage } from '@dcloudio/uni-app';
import { useCacheStore } from '@/stores/cache'
const statusBarHeight = ref(0);
const sectionTops = ref<number[]>([]);
const isScrollingByTab = ref(false);
const scrollTimer = ref<any>(null);
const sel_index = ref(0);
const selectList = ref(['详情', '须知', '课表', '评价']);
const instance = getCurrentInstance();
const cache = useCacheStore()
const type = ref()
onLoad((option) => {
	console.log(option);
	courseId.value = option.id
	type.value = option.type
	appraiseFormData.value.siteId = option.id
	if (option.type == 'sharecourse') {
		cache.set('COURSE_ID', courseDetailInfo.value.id)
	}
})

onShareAppMessage((res) => {
	if (res.from === 'button') {// 来自页面内分享按钮
		console.log(res.target)
	}
	return {
		title: `邀请您报名《${courseDetailInfo.value.name}》`,
		path: `/pages/index/courseDetail/index?id=${courseDetailInfo.value.id}&type=sharecourse`,
		imageUrl: courseDetailInfo.value.cover,

	}
})

onMounted(() => {
	get_navheight()
	nextTick(() => {
		setTimeout(() => getSectionsTop(), 300);
	});
	get_courseInfo()
	getFindByOrderPage()
})

const openMap = () => {
	uni.openLocation({
		latitude: courseDetailInfo.value.latitude,
		longitude: courseDetailInfo.value.longitude,
		name: courseDetailInfo.value.name,
		address: courseDetailInfo.value.address,
		success: function () {
			console.log('success');
		}
	});
}

// 获取所有模块的位置信息
const getSectionsTop = () => {
	const ids = ['detail', 'notice', 'schedule', 'appraise'];
	const query = uni.createSelectorQuery().in(instance.proxy);
	ids.forEach(id => {
		query.select(`#${id}`).boundingClientRect();
	});
	query.exec((rects) => {
		// 计算各模块相对于页面顶部的距离
		sectionTops.value = rects.map((rect: any) => rect.top - 130);
	})
};

//滚动事件
onPageScroll((e) => {
	if (isScrollingByTab.value) return;
	if (scrollTimer.value) return;
	scrollTimer.value = setTimeout(() => {
		updateActiveTab(e.scrollTop);
		scrollTimer.value = null;
	}, 100);
});
// 根据滚动位置更新激活的Tab
const updateActiveTab = (scrollTop: number) => {
	const offset = 130;
	const scrollPosition = scrollTop + offset;
	let activeIndex = 0;
	for (let i = 0; i < sectionTops.value.length; i++) {
		if (scrollPosition >= sectionTops.value[i]) {
			activeIndex = i;
		} else {
			break; // 模块位置已排序，可提前结束
		}
	}
	if (sel_index.value !== activeIndex) {
		sel_index.value = activeIndex;
	}
};
const get_navheight = () => {
	const systemInfo = uni.getSystemInfoSync();
	statusBarHeight.value = systemInfo.statusBarHeight || 0;
}
const sel_tab = async (i: number) => {
	isScrollingByTab.value = true; // 标记为Tab点击触发的滚动
	sel_index.value = i;
	const ids = ['detail', 'notice', 'schedule', 'appraise'];
	const id = ids[i];
	await scrollToTop();
	await nextTick();
	const query = uni.createSelectorQuery().in(instance.proxy);
	query.select(`#${id}`).boundingClientRect(data => {
		if (!data) return;
		uni.pageScrollTo({
			scrollTop: data.top - 130,
			duration: 500,
			complete: () => {
				setTimeout(() => {
					isScrollingByTab.value = false;
				}, 300);
			}
		});
	}).exec();
}

const scrollToTop = () => {
	return new Promise(resolve => {
		uni.pageScrollTo({
			scrollTop: 0,
			duration: 0,
			success: resolve
		});
	});
}

const toOrderPage = (buyType: number) => {
	RouterUtils.to_page(`/pages/index/gymPay/index?courseId=${courseId.value}&type=${type.value}&orderType=2&buyType=${buyType}`)
}

// 获取评价
const appraiseFormData = ref({
	coursesId: null,
	pageNo: 1,
	pageSize: 10
})
const appraiseList = ref([])
const getFindByOrderPage = () => {
	http.get('/my/evaluate/findByOrderPage', { data: appraiseFormData.value, loading: true }).then((res) => {
		if (appraiseFormData.value.pageNo == 1) {
			appraiseList.value = res.result
		} else {
			appraiseList.value = [...appraiseList.value, ...res.result]
		}
	})
}

const courseId = ref()
const courseDetailInfo = ref()
const bannerList = ref([])
const videoList = ref([])
const get_courseInfo = () => {
	http.get('/detail/getCourseInfo', { data: { id: courseId.value || '22222', latitude: cache.get('LAT'), longitude: cache.get('LON') }, loading: true }).then((res) => {
		if (res.result && res.result.details) {
			res.result.details = fixImgStyle(res.result.details);
		}
		const startIndex = res.result.backgroundImage ? res.result.backgroundImage.indexOf('"') + 1 : 0;
		const endIndex = res.result.backgroundImage ? res.result.backgroundImage.lastIndexOf('') : 0;
		bannerList.value = res.result.backgroundImage ? res.result.backgroundImage.slice(startIndex, endIndex).split(',') : [];
		let videoIndex = res.result.video ? res.result.video.indexOf('"') + 1 : 0;
		let videoEndIndex = res.result.video ? res.result.video.lastIndexOf('') : 0;
		videoList.value = res.result.video ? res.result.video.slice(videoIndex, videoEndIndex).split(',') : [];
		courseDetailInfo.value = res.result
	})
}

const fixImgStyle = (html: string) => {
	if (!html) return html;
	return html.replace(/<img/gi, '<img style="max-width:100%;height:auto;display:block;"');
};
</script>

<style lang="less" scoped>
.detail-header {
	position: relative;

	.header-bg {
		position: absolute;
		width: 100%;
		height: 432rpx;
		z-index: -100;
	}

	.back-icon {
		position: absolute;
		left: 20rpx;
		z-index: 9999;
	}

	.header-swiper {
		position: absolute;
		width: 740rpx;
		white-space: nowrap;
		overflow: hidden;

		/* 隐藏滚动条 */
		/deep/ ::-webkit-scrollbar {
			display: none;
			width: 0 !important;
			height: 0 !important;
			background: transparent;
		}

		.swiper-inner {
			display: inline-flex;
			align-items: center;
			gap: 14rpx;
			height: 100%;

			&>video,
			&>image {
				width: 220rpx;
				height: 126rpx;
				border-radius: 16rpx;
				flex-shrink: 0;
			}
		}
	}
}

.header-info {
	padding: 20rpx;
	background: #FFFFFF;
	border-radius: 16rpx 16rpx 0rpx 0rpx;

	.c-price-info {
		display: flex;
		align-items: center;
		justify-content: space-between;

		.price-info {
			display: flex;
			align-items: center;
			gap: 20rpx;

			.new-price {
				font-weight: 800;
				font-size: 48rpx;
				color: #FB5B5B;
			}

			.old-price {
				font-size: 24rpx;
				color: #AAAAAA;
				text-decoration: line-through;
			}
		}

		.sales {
			font-size: 24rpx;
			color: #AAAAAA;
		}
	}

	.c-name {
		margin-top: 44rpx;
		font-weight: 800;
		font-size: 32rpx;
		color: #222222;
	}

	.c-detail-info {
		font-size: 24rpx;
		color: #AAAAAA;

		.c-time {
			margin-top: 20rpx;
		}

		.c-address {
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-top: 20rpx;
		}

		.c-instructor {
			margin-top: 20rpx;
			display: flex;
			align-items: center;
			gap: 20rpx;
			font-size: 24rpx;
			color: #AAAAAA;

			.c-instructor-title {}

			.c-instructor-name {
				text-align: center;

				&>image {
					width: 60rpx;
					height: 60rpx;
					border-radius: 50%;
				}
			}
		}
	}

	.c-line {
		border: 1rpx solid #F0F0F0;
		margin-top: 20rpx;
	}

	.c-rules {
		margin-top: 20rpx;
		font-size: 24rpx;
		color: #222222;
	}
}

.detail-select {
	display: flex;
	align-items: center;
	gap: 60rpx;
	margin-top: 20rpx;
	height: 80rpx;
	background-color: #F6F6F6;

	.select-text,
	.notsel-text {
		position: relative;
		transition: all 0.3s ease;
	}

	.select-text {
		font-weight: 800;
		font-size: 32rpx;
		color: #222222;
		position: relative;
	}

	.notsel-text {
		font-size: 32rpx;
		color: #AAAAAA;
	}

	.select-text::after {
		position: absolute;
		content: '';
		width: 40rpx;
		height: 20rpx;
		background-color: #C8FF0C;
		border-radius: 4rpx;
		left: 050%;
		transform: translateX(-50%);
		bottom: -16rpx;
		transition: all 0.3s ease;
		opacity: 1;
	}

	.notsel-text::after {
		content: '';
		position: absolute;
		left: 50%;
		bottom: -16rpx;
		width: 0;
		height: 20rpx;
		background-color: #C8FF0C;
		border-radius: 4rpx;
		transform: translateX(-50%);
		opacity: 0;
		transition: all 0.3s ease;
	}
}

.c-tabbar {
	margin-top: 10rpx;

	.c-tabbar-detail {
		background: #FFFFFF;
		border-radius: 32rpx;
		padding: 20rpx;
		font-size: 24rpx;
		color: #222222;
	}

	.c-notice {
		margin-top: 20rpx;

		.title {
			font-weight: bold;
			font-size: 32rpx;
			color: #222222;
		}

		.tips-text {
			margin-top: 20rpx;
			background: #FFFFFF;
			border-radius: 32rpx;
			padding: 20rpx;

			.text {
				font-size: 24rpx;
				color: #222222;

				&>view {
					margin-top: 20rpx;
				}
			}

			.more {
				margin-top: 20rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				gap: 20rpx;
				font-size: 24rpx;
				color: #AAAAAA;
			}
		}
	}

	.c-schedule {
		.title {
			font-weight: bold;
			font-size: 32rpx;
			color: #222222;
		}

		.list-card {
			margin-top: 20rpx;
			background: #FFFFFF;
			border-radius: 32rpx;
			padding: 20rpx;
			font-size: 24rpx;
			color: #222222;

			.card-title {}

			.schedule-list {
				margin-top: 20rpx;

				.time {
					border-left: 8rpx solid #D3FD76;

					&>text {
						margin-left: 20rpx;
					}
				}

				.name {
					margin-left: 20rpx;
					margin-top: 20rpx;
				}
			}

			.more {
				margin-top: 20rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				gap: 20rpx;
				font-size: 24rpx;
				color: #AAAAAA;
			}
		}
	}

	.appraise-card {
		padding: 20rpx;
		background: #FFFFFF;
		border-radius: 32rpx;
		margin-top: 20rpx;

		.appraise-title {
			display: flex;
			align-items: center;
			justify-content: space-between;

			.title {
				font-weight: 800;
				font-size: 32rpx;
				color: #222222;
			}

			.comments {
				display: flex;
				align-items: center;
				gap: 16rpx;

				.a-star {
					font-size: 24rpx;
					color: #FDD143;
				}

				.a-text {
					font-size: 24rpx;
					color: #AAAAAA;
				}
			}
		}

		.appraise-info {
			margin-top: 20rpx;

			.a-user-info {
				display: flex;
				align-items: center;
				justify-content: space-between;

				.info {
					display: flex;
					align-items: center;
					gap: 20rpx;

					&>image {
						width: 60rpx;
						height: 60rpx;
						border-radius: 50%;
					}

					.name {
						font-weight: bold;
						font-size: 24rpx;
						color: #222222;
					}
				}

				.time {
					font-size: 24rpx;
					color: #AAAAAA;
				}
			}

			.a-score {
				font-size: 24rpx;
				color: #AAAAAA;
				display: flex;
				align-items: center;
				gap: 20rpx;
				margin-top: 20rpx;
			}

			.a-content {
				margin-top: 20rpx;
				font-size: 28rpx;
				color: #222222;
			}

			.scroll-view_H {
				white-space: nowrap;
				width: 100%;
				height: 220rpx;
				margin-top: 20rpx;
				border-bottom: 1rpx solid #F0F0F0;

				.scroll-view-item_H {
					display: inline-block;
					text-align: center;
					margin-right: 14rpx;

					&>image {
						width: 202rpx;
						height: 200rpx;
						background: #D8D8D8;
						border-radius: 32rpx;
					}
				}
			}
		}
	}
}

.c-bottom {
	display: flex;
	align-items: center;
	justify-content: space-between;
	position: fixed;
	bottom: 0;
	width: 95%;
	padding: 20rpx;
	background: #fff;
	box-shadow: 0rpx -6rpx 12rpx 2rpx rgba(0, 0, 0, 0.09);
	border-radius: 32rpx 32rpx 0rpx 0rpx;

	.c-share {
		font-weight: bold;
		font-size: 28rpx;
		color: #222222;
		text-align: center;
		position: relative;

		.g-share-btn {
			position: absolute;
			width: 80rpx;
			height: 90rpx;
			top: -12rpx;
			opacity: 0;
		}
	}

	.c-buy-btn {
		display: flex;
		align-items: center;
		gap: 16rpx;

		.buy {
			width: 226rpx;
			height: 100rpx;
			background: #222222;
			border-radius: 60rpx;
			text-align: center;

			.buy-text {
				margin-top: 8rpx;
				font-weight: bold;
				font-size: 32rpx;
				color: #D3FD76;
			}

			.buy-price {
				color: #D3FD76;

				&>text:first-child {
					font-weight: bold;
					font-size: 28rpx;
				}

				&>text:last-child {
					margin-left: 6rpx;
					font-size: 22rpx;
				}
			}
		}

		.gratis {
			width: 226rpx;
			height: 100rpx;
			background: #D3FD76;
			border-radius: 60rpx;
			font-weight: bold;
			font-size: 32rpx;
			color: #222222;
			text-align: center;
			line-height: 100rpx;
			position: relative;

			.gratis-tips {
				position: absolute;
				width: 552rpx;
				height: 80rpx;
				font-size: 28rpx;
				color: #FFFFFF;
				background: rgba(0, 0, 0, 0.6);
				border-radius: 8rpx;
				line-height: 80rpx;
				right: 20rpx;
				bottom: 110rpx;
			}
		}
	}
}
</style>