<template>
	<swiper class="main-swiper" :vertical="true" :current="currentIndex" @change="handleSwiperChange" :duration="300">
		<swiper-item v-for="(_, outerIndex) in 7" :key="outerIndex">
			<view class="page-container home-page">
				<template v-if="loadedPages[outerIndex]">
					<image v-show="shouldShowContent(outerIndex)" class="bg-image"
						:src="`/static/images/chapter4/detail${outerIndex+1}/cover-bg.png`" mode="" :lazy-load="true">
					</image>

					<view v-show="shouldShowContent(outerIndex)" class="content-layer">
						<swiper class="image-swiper" circular :indicator-dots="false"
							@change="(e) => handleImageSwiperChange(e, outerIndex)" :autoplay="false"
							:current="innerSwiperIndices[outerIndex]" :key="`inner-swiper-${outerIndex}`">
							<swiper-item v-for="index in 7" :key="index">
								<view class="swiper-item-container">
									<view class="image-wrapper" :class="{'selected-image': selectedImages[outerIndex] === index-1 && userSelected[outerIndex],
										 'image-wrapper-full': [0, 3, 5, 6].includes(outerIndex),
										'image-wrapper-compact': [1, 2, 4].includes(outerIndex)
										}" @click="selectImage(outerIndex, index-1)">
										<image
											:src="`/static/images/chapter4/detail${outerIndex+1}/swiper-img${index}.png`"
											class="swiper-image" mode="aspectFit" :lazy-load="true" />
									</view>
								</view>
							</swiper-item>
						</swiper>

						<!-- 自定义指示器 -->
						<view class="indicator-container">
							<view v-for="index in 7" :key="index" class="indicator-dot"
								:class="{ 'active': innerSwiperIndices[outerIndex] === index - 1 }"
								@click="() => changeSlide(index - 1, outerIndex)"></view>
						</view>
					</view>

					<view v-show="shouldShowContent(outerIndex)" class="content-layer2">
						<!-- 点击确认找一找相似度 按钮 -->
						<image @click="findSimilarity(outerIndex)" class="find-btn" src="/static/find-btn.png"
							:lazy-load="true" mode=""></image>
						<view class="problem-description">
							<view class="proportion-txt" :class="{
                'proportion-txt-position': outerIndex === 0,
                'proportion-txt-position2': outerIndex === 1,
                'proportion-txt-position3': outerIndex === 2,
                'proportion-txt-position4': outerIndex === 3,
                'proportion-txt-position5': outerIndex === 4,
                'proportion-txt-position6': outerIndex === 5,
                'proportion-txt-position7': outerIndex === 6
              }">
								{{ percentages[outerIndex]}}
							</view>
							<image class="description-txt"
								:class="{'description-txt6': outerIndex === 5,'description-txt7': outerIndex === 6}"
								:src="`/static/images/chapter4/detail${outerIndex+1}/cover-txt.png`" :lazy-load="true"
								mode=""></image>
						</view>
					</view>

					<view v-show="shouldShowContent(outerIndex)" class="arrow-content">
						<image class="arrow-down" src="/static/arrow-icon-black.png" :lazy-load="true" mode=""></image>
					</view>
				</template>
			</view>
		</swiper-item>

		<swiper-item>
			<view class="page-container home-page">
				<template v-if="loadedPages[7]">
					<image v-show="shouldShowContent(7)" class="bg-image"
						src="/static/images/chapter4/harvestReport/cover-bg.png" :lazy-load="true" mode=""></image>
					<view v-show="shouldShowContent(7)" class="harvestReport-layer">
						<view class="grid-cover img-shadow">
							<image class="grid-cover-bg" src="/static/images/chapter4/harvestReport/cover-grid.png"
								:lazy-load="true" mode=""></image>
							<view class="report-text-overlay" v-if="canAccessFinalReport">
								<view class="report-title">您的气味收获</view>
								<view class="report-content">
									<view v-for="(item, index) in selectedResults" :key="index" class="result-item">
										{{ item }}
									</view>
								</view>
							</view>
						</view>

						<image @click="ShareMoments" class="chapter4-btn" src="/static/images/chapter4/share-img.png"
							:lazy-load="true" mode=""></image>
					</view>
					<image @click="goBack" class="back-icon" src="/static/back.png" mode=""></image>
				</template>
			</view>
		</swiper-item>
	</swiper>
	<MusicControl />
	<ShareGuide v-model="showShareGuide" :text="['点击右上角...', '选择分享到朋友圈']" @close="onShareGuideClose" />
</template>

<script setup>
	import {
		ref,
		reactive,
		computed,
		onMounted,
		watch
	} from 'vue';

	import {
		onShow,
		onHide,
		onShareAppMessage,
		onShareTimeline
	} from '@dcloudio/uni-app';
	import ShareGuide from '@/components/ShareGuide.vue';
	// import {
	// 	request
	// } from '@/utils/request';
	const showShareGuide = ref(false);
	const currentIndex = ref(0);

	// 为每个外部轮播项维护独立的内部轮播索引
	const innerSwiperIndices = reactive({
		0: 0,
		1: 0,
		2: 0,
		3: 0,
		4: 0,
		5: 0,
		6: 0,
	});

	// 记录每个模块的选中图片索引
	const selectedImages = reactive({
		0: null,
		1: null,
		2: null,
		3: null,
		4: null,
		5: null,
		6: null
	});
	//选择状态跟随
	const userSelected = reactive({
		0: false,
		1: false,
		2: false,
		3: false,
		4: false,
		5: false,
		6: false
	});
	// 存储每个模块的百分比数据
	const percentages = reactive({
		0: '',
		1: '',
		2: '',
		3: '',
		4: '',
		5: '',
		6: ''
	});

	// 记录哪些模块已经请求过数据
	const requestedData = reactive({
		0: false,
		1: false,
		2: false,
		3: false,
		4: false,
		5: false,
		6: false
	});
	//记录哪些模块已经完成了相似度计算
	const similarityCompleted = reactive({
		0: false,
		1: false,
		2: false,
		3: false,
		4: false,
		5: false,
		6: false
	});
	// 记录哪些页面已经加载过
	const loadedPages = reactive({
		0: false,
		1: false,
		2: false,
		3: false,
		4: false,
		5: false,
		6: false,
		7: false
	});

	// 加载预缓冲区大小
	const preloadBuffer = 1;

	// 决定是否应该显示特定页面的内容
	const shouldShowContent = (index) => {
		return Math.abs(index - currentIndex.value) <= preloadBuffer;
	};

	// 选择图片
	const selectImage = (moduleIndex, imageIndex) => {
		// 更新选中状态
		selectedImages[moduleIndex] = imageIndex;
		// 标记为用户主动选择
		userSelected[moduleIndex] = true;
		// 同步更新swiper索引
		innerSwiperIndices[moduleIndex] = imageIndex;

		console.log(`选中模块${moduleIndex + 1}的图片${imageIndex + 1}`);
	};

	// 查找相似度
	const findSimilarity = async (moduleIndex) => {
		// 如果没有选中图片或没有明确选择，标记当前显示的为选中
		if (selectedImages[moduleIndex] === null || !userSelected[moduleIndex]) {
			selectedImages[moduleIndex] = innerSwiperIndices[moduleIndex];
			userSelected[moduleIndex] = true;

			uni.showToast({
				title: '已选择当前图片',
				icon: 'none'
			});
		}
		fetchSimilarityData(moduleIndex);
	};
	const fetchSimilarityData = async (moduleIndex) => {
		uni.showLoading({
			title: '计算相似度中...'
		});

		try {
			const imageIndex = selectedImages[moduleIndex];

			// 调用API获取百分比数据
			const result = await fetchPercentage(moduleIndex + 1, imageIndex + 1);

			// 更新百分比显示
			percentages[moduleIndex] = result.percentage;

			// 标记该模块已完成相似度计算
			similarityCompleted[moduleIndex] = true;

			// 标记该模块已请求过数据
			requestedData[moduleIndex] = true;

			uni.hideLoading();

			uni.showToast({
				title: '计算完成',
				icon: 'success'
			});
		} catch (error) {
			console.error('获取相似度失败:', error);
			uni.hideLoading();
			uni.showToast({
				title: '获取数据失败',
				icon: 'none'
			});
		}
	};
	// 接口请求函数
	const fetchPercentage = async (moduleId, imageId) => {
		try {
			// 模拟API请求
			// const res = await request({
			//   url: '/api/similarity',
			//   method: 'POST',
			//   data: {
			//     moduleId,
			//     imageId
			//   }
			// });

			// 模拟API响应
			return new Promise((resolve) => {
				setTimeout(() => {
					// 生成随机百分比，实际项目中应该使用API返回的数据
					const percentage = Math.floor(Math.random() * 41) + 60 + '%';
					resolve({
						success: true,
						percentage,
						moduleId,
						imageId
					});
				}, 800);
			});
		} catch (error) {
			console.error('API请求失败:', error);
			throw error;
		}
	};

	// 分享到朋友圈
	const ShareMoments = () => {
		uni.showShareMenu({
			withShareTicket: true,
			menus: ['shareAppMessage', 'shareTimeline']
		});

		showShareGuide.value = true;
	};

	const onShareGuideClose = () => {
		console.log('分享引导已关闭');
	};

	const goBack = () => {
		// 添加防抖
		if (goBack.isNavigating) return;
		goBack.isNavigating = true;

		const app = getApp();
		app.globalData.mainSliderIndex = 5;
		uni.redirectTo({
			url: '/pages/home/home',
			complete: () => {
				// 延迟重置防抖标记
				setTimeout(() => {
					goBack.isNavigating = false;
				}, 500);
			}
		});
	};
	goBack.isNavigating = false;

	// 监听currentIndex变化，更新已加载页面状态
	watch(currentIndex, (newIndex) => {
		// 标记当前页面和前后buffer页为已加载
		for (let i = Math.max(0, newIndex - preloadBuffer); i <= Math.min(7, newIndex + preloadBuffer); i++) {
			loadedPages[i] = true;
		}
	}, {
		immediate: true
	});

	const handleSwiperChange = (e) => {
		const newIndex = e.detail.current;
		if (newIndex === 7) {
			// 检查是否所有模块都完成了相似度计算
			if (!canAccessFinalReport.value) {
				// 找到第一个未完成相似度计算的模块
				let firstIncompleteIndex = 0;
				for (let i = 0; i < 7; i++) {
					if (!similarityCompleted[i]) {
						firstIncompleteIndex = i;
						break;
					}
				}

				// 显示提示
				uni.showToast({
					title: `${moduleTips[firstIncompleteIndex]}并点击确认按钮`,
					icon: 'none',
					duration: 2500
				});

				// 跳转到未完成的模块
				setTimeout(() => {
					currentIndex.value = firstIncompleteIndex;
				}, 1000);

				return;
			}
		}

		// 正常情况下更新索引
		currentIndex.value = newIndex;
	};

	const handleImageSwiperChange = (e, outerIndex) => {
		// 只更新内层swiper索引，不更新选中状态
		innerSwiperIndices[outerIndex] = e.detail.current;

		// 如果没有明确选择过，则选中状态也跟随更新
		// 如果之前已经选择过，则保持用户的选择
		if (!userSelected[outerIndex]) {
			selectedImages[outerIndex] = e.detail.current;
		}
	};

	const changeSlide = (index, outerIndex) => {
		innerSwiperIndices[outerIndex] = index;
		// 更新选中状态并标记为用户选择
		selectedImages[outerIndex] = index;
		userSelected[outerIndex] = true;
	};

	const getCurrentInnerIndex = (outerIndex) => {
		return innerSwiperIndices[outerIndex || currentIndex.value];
	};
	// 检查是否可以访问最终报告页
	const canAccessFinalReport = computed(() => {
		// 检查所有模块是否都已选择
		f
		for (let i = 0; i < 7; i++) {
			if (!similarityCompleted[i]) {
				return false;
			}
		}
		return true;
	});
	// 模块提示文本
	const moduleTips = [
		'请选择最有味道的歌曲',
		'请选择最有味道的人物',
		'请选择最有味道的食物',
		'请选择最有味道的句子',
		'请选择最有味道的风景',
		'请选择最有味道的动漫',
		'请选择最有味道的情感'
	];
	const flavorTexts = {
		// 歌曲文案
		0: [
			"音符在舌尖跳跃，这首歌如同陈年佳酿",
		],
		// 人物文案
		1: [
			"如墨般浓郁的性格，似茶般清冽的灵魂",
		],
		// 食物文案
		2: [
			"舌尖上的东方，是一场穿越时空的对话",
		],
		// 句子文案
		3: [
			"文字如酒，越品越醇，越读越深",
		],
		// 风景文案
		4: [
			"山水间藏着天地的密语，云雾里是岁月的轻叹",
		],
		// 动漫文案
		5: [
			"二次元中的东方灵魂，是跨越文化的共鸣",
		],
		// 情感文案
		6: [
			"情感如茶，或浓或淡，皆有韵味",
		]
	};

	// 获取风味百分比描述
	const getFlavorDescription = (percentage) => {
		const value = parseInt(percentage);
		return;
	};

	// 修改后的selectedResults方法
	const selectedResults = computed(() => {
		const results = [];

		for (let i = 0; i < 7; i++) {
			if (userSelected[i]) {
				// 从对应模块的文案库中随机选择一条
				const textOptions = flavorTexts[i];
				const randomIndex = Math.floor(Math.random() * textOptions.length);
				const text = textOptions[randomIndex];
				results.push(`${text}`);
			}
		}

		return results;
	});
	// 页面加载完成后预加载第一页
	onMounted(() => {
		// 设置当前页为0，确保第一页和相邻页面的内容被加载
		currentIndex.value = 0;

		// 初始化标记第一页和相邻页为已加载
		for (let i = 0; i <= Math.min(preloadBuffer, 7); i++) {
			loadedPages[i] = true;
		}
	});

	// 微信分享配置
	// #ifdef MP-WEIXIN
	onShareAppMessage(() => {
		return {
			title: '细嗅东方｜「Epic Soul」阅读体 issue02',
			mpId: 'wx8954209bb3ad489e',
			path: '/pages/chapter4/cover',
			imageUrl: '/static/share-img.jpg'
		}
	});

	onShareTimeline(() => {
		return {
			title: '细嗅东方｜「Epic Soul」阅读体 issue02',
			query: '',
			imageUrl: '/static/share-img.jpg'
		}
	});
	// #endif
</script>


<style scoped>
	.main-swiper {
		width: 100%;
		height: 100vh;
	}

	.page-container {
		height: 100vh;
	}

	.home-page {
		position: relative;
		overflow: hidden;
	}

	.swiper-item-container {
		width: 100%;
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 10rpx;
		box-sizing: border-box;
	}

	.image-swiper {
		width: 100%;
		height: 500rpx;
		margin-bottom: 20rpx;
	}

	.image-wrapper {
		position: relative;
		box-sizing: border-box;
		transition: all 0.3s;
		height: 100%;
	}

	.image-wrapper-full {
		width: 80%;
	}

	.image-wrapper-compact {
		width: 100%;
	}

	.selected-image {
		border: 4rpx solid #f0ad4e;
		box-shadow: 0 0 10rpx rgba(240, 173, 78, 0.6);
		background-color: rgba(240, 173, 78, 0.1);
	}

	.swiper-image {
		max-width: 100%;
		max-height: 100%;
		display: block;
		object-fit: contain;
	}

	.bg-image {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 1;
	}

	/* 内容层样式 */
	.content-layer {
		position: relative;
		z-index: 2;
		width: 100%;
		display: flex;
		align-items: center;
		flex-direction: column;
		margin-top: 20%;
		box-sizing: border-box;
		/* 添加此行 */
		padding: 0;
		/* 确保没有内边距 */
	}

	.content-layer2 {
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 2;
		position: relative;
		flex-direction: column;
	}

	.find-btn {
		width: 300rpx;
		height: 50rpx;
		margin-top: 10rpx;
	}

	.problem-description {
		height: 100%;
		display: flex;
		align-items: center;
		position: relative;
		margin-top: 150rpx;
	}

	.proportion-txt {
		font-size: 48rpx;
		color: #0f944f;
	}

	.proportion-txt-position {
		position: absolute;
		bottom: 0;
		left: 0;
	}

	.proportion-txt-position2 {
		position: absolute;
		right: 120rpx;
		top: 0;
		line-height: 1;
	}

	.proportion-txt-position3 {
		position: absolute;
		right: 20rpx;
		top: 0;
		line-height: 1;
	}

	.proportion-txt-position4 {
		position: absolute;
		left: 0;
		top: 0;
		line-height: 1;
	}

	.proportion-txt-position5 {
		position: absolute;
		right: 120rpx;
		top: 0;
		line-height: 1;
	}

	.description-txt {
		width: 400rpx;
		height: 120rpx;
	}

	.description-txt6 {
		width: 460rpx !important;
		height: 50rpx !important;
	}

	.description-txt7 {
		width: 460rpx !important;
		height: 120rpx !important;
	}

	.proportion-txt-position6 {
		position: absolute;
		left: 0;
		top: 0;
		line-height: 1;
		font-size: 38rpx !important;
	}

	.proportion-txt-position7 {
		position: absolute;
		left: 0;
		top: 0;
		line-height: 1;
	}

	.image-swiper {
		width: 100%;
		height: 500rpx;
	}

	.swiper-image {
		width: 100%;
		height: 100%;
		object-fit: contain;
	}

	.back-icon {
		width: 48rpx;
		height: 48rpx;
		position: absolute;
		left: 40rpx;
		top: 40rpx;
		z-index: 10;
	}

	.indicator-container {
		display: flex;
		justify-content: center;
		align-items: center;
		margin: 50rpx;
	}

	.indicator-dot {
		width: 14rpx;
		height: 14rpx;
		border-radius: 50%;
		background-color: rgba(255, 255, 255, 0.5);
		margin: 0 8rpx;
		transition: all 0.3s;
	}

	.indicator-dot.active {
		background-color: #ffffff;
		transform: scale(1.2);
	}

	.harvestReport-layer {
		position: relative;
		z-index: 2;
		display: flex;
		margin-top: 42%;
		flex-direction: column;
		align-items: center;
		height: 100%;
	}

	.grid-cover {
		width: 85%;
		height: 60%;
	}

	.grid-cover-bg {
		width: 100%;
		height: 100%;
	}

	.chapter4-btn {
		width: 280rpx;
		height: 60rpx;
		margin-top: 60rpx;
	}

	.img-shadow {
		box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2),
			0 6px 20px 0 rgba(0, 0, 0, 0.19);
		transition: box-shadow 0.3s ease;
	}

	.arrow-content {
		width: 100%;
		position: absolute;
		bottom: 10%;
		left: 50%;
		transform: translate(-50%, 0);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 2;
	}

	.arrow-down {
		width: 200rpx;
		height: 40rpx;
		animation: bounce 1.5s infinite;
	}

	@keyframes bounce {

		0%,
		20%,
		50%,
		80%,
		100% {
			transform: translateY(0);
		}

		40% {
			transform: translateY(-20rpx);
		}

		60% {
			transform: translateY(-10rpx);
		}
	}

	.report-text-overlay {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		padding: 40rpx;
		box-sizing: border-box;
		z-index: 8;
		text-align: center;
	}

	.report-title {
		font-size: 48rpx;
		color: #f0ad4e;
		font-weight: bold;
		margin-bottom: 40rpx;
		text-shadow: 0 0 10rpx rgba(0, 0, 0, 0.3);
		animation: fade-in 1.5s ease-out;
	}

	.report-content {
		width: 100%;
	}

	.result-item {
		font-size: 28rpx;
		color: #333333;
		line-height: 1.8;
		margin-bottom: 20rpx;
		text-shadow: 0 0 8rpx rgba(0, 0, 0, 0.5);
		opacity: 0;
		animation: slide-in 0.5s ease-out forwards;
	}

	.result-item:nth-child(1) {
		animation-delay: 0.2s;
	}

	.result-item:nth-child(2) {
		animation-delay: 0.4s;
	}

	.result-item:nth-child(3) {
		animation-delay: 0.6s;
	}

	.result-item:nth-child(4) {
		animation-delay: 0.8s;
	}

	.result-item:nth-child(5) {
		animation-delay: 1.0s;
	}

	.result-item:nth-child(6) {
		animation-delay: 1.2s;
	}

	.result-item:nth-child(7) {
		animation-delay: 1.4s;
	}

	@keyframes fade-in {
		from {
			opacity: 0;
			transform: translateY(-20rpx);
		}

		to {
			opacity: 1;
			transform: translateY(0);
		}
	}

	@keyframes slide-in {
		from {
			opacity: 0;
			transform: translateX(-30rpx);
		}

		to {
			opacity: 1;
			transform: translateX(0);
		}
	}

	.grid-cover {
		position: relative;
		height: 60%;
		z-index: 7;
	}
</style>