<template>
	<view>
    <swiper class="main-swiper" :vertical="true" :current="currentIndex" @change="handleSwiperChange" :duration="300">
        <swiper-item v-for="(_, outerIndex) in (questionsList.length || 7)" :key="outerIndex">
            <view class="page-container home-page">
                <template v-if="loadedPages[outerIndex]">
                    <image v-show="shouldShowContent(outerIndex)" class="bg-image"
                           :src="`https://static.ticket.sz-trip.com/epicSoul/image/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="(option, index) in getQuestionOptions(outerIndex)" :key="option.id">
                                <view class="swiper-item-container">
                                    <view class="image-wrapper" :class="{'selected-image': selectedImages[outerIndex] === index && userSelected[outerIndex],
                                            'image-wrapper-full': [0, 3, 5, 6].includes(outerIndex),
                                            'image-wrapper-compact': [1, 2, 4].includes(outerIndex)
                                        }" @click="selectImage(outerIndex, index)">
                                        <image :src="option.image" class="swiper-image" mode="aspectFit"
                                               :lazy-load="true" />
                                    </view>
                                </view>
                            </swiper-item>
                        </swiper>

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

                    <view v-show="shouldShowContent(outerIndex)" class="content-layer2">
                        <!-- 点击确认找一找相似度 按钮 -->
                        <image @click="findSimilarity(outerIndex)" class="find-btn" src="https://static.ticket.sz-trip.com/epicSoul/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="`https://static.ticket.sz-trip.com/epicSoul/image/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="https://static.ticket.sz-trip.com/epicSoul/image/chapter3/botIcon.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="https://static.ticket.sz-trip.com/epicSoul/image/chapter4/harvestReport/cover-bgs.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="https://static.ticket.sz-trip.com/epicSoul/image/chapter4/harvestReport/cover-grid.png"
                                   :lazy-load="true" mode="widthFix" :show-menu-by-longpress="true"></image> -->
							<image class="grid-cover-bg" src="https://static.ticket.sz-trip.com/epicSoul/image/chapter4/harvestReport/qrcode.png"
							       :lazy-load="true" mode="widthFix" :show-menu-by-longpress="true"></image>
                            <view class="report-text-overlay" v-if="canAccessFinalReport">
                                <view class="report-content">
                                    <view v-for="(item, index) in finalReportTexts" :key="index" class="result-item">
                                        {{ item }}
                                    </view>
                                </view>
                            </view>
                        </view>

                        <!-- <image @click="ShareMoments" class="chapter4-btn" src="https://static.ticket.sz-trip.com/epicSoul/image/chapter4/share-img.png"
                               :lazy-load="true" mode=""></image> -->
                    </view>
                    <image @click="goBack" class="back-icon" src="https://static.ticket.sz-trip.com/epicSoul/back.png" mode=""></image>
                </template>
            </view>
        </swiper-item>
    </swiper>
    <MusicControl />
    <ShareGuide @close="onShareGuideClose" />
	<NavMenu :nav-index="0" @jump-to-page="handleJumpToPage" />
	</view>
</template>

<script>
import NavMenu from '../components/NavMenu.vue';
import {
    getQuestionnaireList,
    getQuestionnaireDetail,
    getStatistics,
    sendAnswer
} from '@/static/js/common';
import ShareGuide from '@/components/ShareGuide.vue';
import MusicControl from '@/components/MusicControl.vue';

export default {
    components: {
        ShareGuide,
		MusicControl,
		NavMenu
    },
    data() {
        return {
            showShareGuide: false,
            currentIndex: 0,
            questionnaireId: null,
            questionsList: [],
            innerSwiperIndices: {
                0: 0,
                1: 0,
                2: 0,
                3: 0,
                4: 0,
                5: 0,
                6: 0,
            },
            selectedImages: {
                0: null,
                1: null,
                2: null,
                3: null,
                4: null,
                5: null,
                6: null
            },
            userSelected: {
                0: false,
                1: false,
                2: false,
                3: false,
                4: false,
                5: false,
                6: false
            },
            percentages: {
                0: '',
                1: '',
                2: '',
                3: '',
                4: '',
                5: '',
                6: ''
            },
            similarityCompleted: {
                0: false,
                1: false,
                2: false,
                3: false,
                4: false,
                5: false,
                6: false
            },
            loadedPages: {
                0: false,
                1: false,
                2: false,
                3: false,
                4: false,
                5: false,
                6: false,
                7: false
            },
            reportTextTemplates: [
                "你喜欢的，{percentage}的ta一样也喜欢。",
                "原来,有{percentage}的人,选择和你做知已。",
                "这个世界上的{percentage},喜欢你的激情果敢。",
                "{percentage}的你，温暖、温柔又闪光。",
                "好在,有{percentage}的人,能读懂你的理想。",
                "{percentage}的一群人,和你很合拍。",
                "{percentage}气味相投的你们，总会如期相遇。"
            ],
            preloadBuffer: 1,
            moduleTips: [
                '请选择最有味道的歌曲',
                '请选择最有味道的人物',
                '请选择最有味道的食物',
                '请选择最有味道的句子',
                '请选择最有味道的风景',
                '请选择最有味道的动漫',
                '请选择最有味道的情感'
            ]
        };
    },
    computed: {
        finalReportTexts() {
            const texts = [];
            for (let i = 0; i < 7; i++) {
                if (this.similarityCompleted[i]) {
                    const percentValue = this.percentages[i].replace('%', '');
                    const text = this.reportTextTemplates[i].replace('{percentage}', percentValue + '%');
                    texts.push(text);
                }
            }
            return texts;
        },
        canAccessFinalReport() {
            for (let i = 0; i < 7; i++) {
                if (!this.similarityCompleted[i]) {
                    return false;
                }
            }
            return true;
        }
    },
    watch: {
        currentIndex(newIndex) {
            for (let i = Math.max(0, newIndex - this.preloadBuffer); i <= Math.min(7, newIndex + this.preloadBuffer); i++) {
                this.loadedPages[i] = true;
            }
        }
    },
    created() {
		this.Post({}, "/api/user/userInfo").then((res) => {});
        this.currentIndex = 0;
        for (let i = 0; i <= Math.min(this.preloadBuffer, 7); i++) {
            this.loadedPages[i] = true;
        }
        this.loadQuestionnaireList();
    },
    methods: {
        getQuestionOptions(moduleIndex) {
            if (!this.questionsList || this.questionsList.length <= moduleIndex) {
                return [];
            }
            return this.questionsList[moduleIndex]?.options || [];
        },
        getOptionId(moduleIndex, optionIndex) {
            const options = this.getQuestionOptions(moduleIndex);
            return options[optionIndex]?.id;
        },
        getUserId() {
            const userInfoFromStorage = uni.getStorageSync('userInfo');
            if (userInfoFromStorage) {
                const userInfo = JSON.parse(userInfoFromStorage);
                if (userInfo.id) {
                    return userInfo.id;
                }
            }
            return this.$store.state.user.userInfo.id;
        },
        shouldShowContent(index) {
            return Math.abs(index - this.currentIndex) <= this.preloadBuffer;
        },
        selectImage(moduleIndex, imageIndex) {
            this.selectedImages[moduleIndex] = imageIndex;
            this.userSelected[moduleIndex] = true;
            this.innerSwiperIndices[moduleIndex] = imageIndex;
        },
        findSimilarity(moduleIndex) {
            if (this.selectedImages[moduleIndex] === null || !this.userSelected[moduleIndex]) {
                this.selectedImages[moduleIndex] = this.innerSwiperIndices[moduleIndex];
                this.userSelected[moduleIndex] = true;
                uni.showToast({
                    title: '已选择当前图片',
                    icon: 'none'
                });
            }
            const questionId = this.questionsList[moduleIndex]?.id;
            const optionId = this.getOptionId(moduleIndex, this.selectedImages[moduleIndex]);
            if (questionId && optionId && this.questionnaireId) {
                const userId = this.getUserId();
                sendAnswer({
                    questionnaire_id: this.questionnaireId,
                    question_id: questionId,
                    option_id: optionId,
                    openid: userId
                }).catch(error => {
                    console.error('提交答案失败:', error);
                });
            }
            this.fetchSimilarityData(moduleIndex);
        },
        fetchSimilarityData(moduleIndex) {
            uni.showLoading({
                title: '计算相似度中...'
            });
            const questionId = this.questionsList[moduleIndex]?.id;
            const optionId = this.getOptionId(moduleIndex, this.selectedImages[moduleIndex]);
            if (!questionId || !optionId) {
                this.percentages[moduleIndex] = `${Math.floor(Math.random() * 41) + 60}%`;
                this.similarityCompleted[moduleIndex] = true;
                uni.hideLoading();
                return;
            }
            getStatistics({
                question_id: questionId
            }).then(result => {
                if (result.code === 1 && result.data && result.data.options) {
                    const selectedOption = result.data.options.find(option => option.id === optionId);
                    if (selectedOption && selectedOption.percentage !== undefined) {
                        this.percentages[moduleIndex] = `${selectedOption.percentage}%`;
                    } else {
                        this.percentages[moduleIndex] = `${Math.floor(Math.random() * 41) + 60}%`;
                    }
                } else {
                    this.percentages[moduleIndex] = `${Math.floor(Math.random() * 41) + 60}%`;
                }
                this.similarityCompleted[moduleIndex] = true;
                uni.hideLoading();
            }).catch(error => {
                this.percentages[moduleIndex] = `${Math.floor(Math.random() * 41) + 60}%`;
                this.similarityCompleted[moduleIndex] = true;
                uni.hideLoading();
            });
        },
        ShareMoments() {
            uni.showShareMenu({
                withShareTicket: true,
                menus: ['shareAppMessage', 'shareTimeline']
            });
            this.showShareGuide = true;
        },
        onShareGuideClose() {
            console.log('分享引导已关闭');
        },
        goBack() {
            if (this.goBack.isNavigating) return;
            this.goBack.isNavigating = true;
            const app = getApp();
            app.globalData.mainSliderIndex = 5;
            uni.redirectTo({
                url: '/xxdf/home/home',
                complete: () => {
                    setTimeout(() => {
                        this.goBack.isNavigating = false;
                    }, 500);
                }
            });
        },
        handleSwiperChange(e) {
            const newIndex = e.detail.current;
            if (newIndex === 7) {
                if (!this.canAccessFinalReport) {
                    let firstIncompleteIndex = 0;
                    for (let i = 0; i < 7; i++) {
                        if (!this.similarityCompleted[i]) {
                            firstIncompleteIndex = i;
                            break;
                        }
                    }
                    uni.showToast({
                        title: `${this.moduleTips[firstIncompleteIndex]}并点击确认按钮`,
                        icon: 'none',
                        duration: 2500
                    });
                    setTimeout(() => {
                        this.currentIndex = firstIncompleteIndex;
                    }, 1000);
                    return;
                }
            }
            this.currentIndex = newIndex;
        },
        handleImageSwiperChange(e, outerIndex) {
            this.innerSwiperIndices[outerIndex] = e.detail.current;
            if (!this.userSelected[outerIndex]) {
                this.selectedImages[outerIndex] = e.detail.current;
            }
        },
        changeSlide(index, outerIndex) {
            this.innerSwiperIndices[outerIndex] = index;
            this.selectedImages[outerIndex] = index;
            this.userSelected[outerIndex] = true;
        },
        loadQuestionnaireList() {
            getQuestionnaireList().then(res => {
                if (res.code === 1 && res.data.list.length > 0) {
                    this.questionnaireId = res.data.list[0].id;
                    this.loadQuestionnaireDetail();
                } else {
                    uni.showToast({
                        title: '未获取到问卷',
                        icon: 'none'
                    });
                }
            }).catch(error => {
                console.error('加载问卷列表失败:', error);
                uni.showToast({
                    title: '加载问卷失败',
                    icon: 'none'
                });
            });
        },
        loadQuestionnaireDetail() {
            if (!this.questionnaireId) return;
            getQuestionnaireDetail({
                id: this.questionnaireId
            }).then(res => {
                if (res.code === 1 && res.data) {
                    this.questionsList = res.data.questions || [];
                } else {
                    uni.showToast({
                        title: '未获取到问卷详情',
                        icon: 'none'
                    });
                }
            }).catch(error => {
                console.error('加载问卷详情失败:', error);
                uni.showToast({
                    title: '加载问卷详情失败',
                    icon: 'none'
                });
            });
        },
        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'
            };
        }
    }
};
</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: 30rpx;
    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: 95rpx;
    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: 57%;
    flex-direction: column;
    align-items: center;
}

.grid-cover {
    width: 85%;
}

.grid-cover-bg {
    position: fixed;
    width: 180rpx;
    bottom: 238px;
    left: 135rpx;
	z-index: 999;
}

.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;
	padding: 0rpx 40rpx 40rpx 40rpx;
	box-sizing: border-box;
	z-index: 8;
	text-indent: 40rpx;
}

.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>