<template>
    <div class="chapter-container">
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
            <el-skeleton :rows="10" animated>
                <template #template>
                    <div style="max-width: 1100px; margin: 0 auto; padding: 30px 20px;">
                        <el-skeleton-item variant="text" style="width: 40%; margin-bottom: 30px;" />
                        <el-skeleton-item variant="text" style="width: 100%; margin-bottom: 20px;" />
                        <el-skeleton-item variant="text" style="width: 100%; margin-bottom: 20px;" />
                        <el-skeleton-item variant="text" style="width: 90%; margin-bottom: 20px;" />
                        <el-skeleton-item variant="text" style="width: 100%; margin-bottom: 20px;" />
                        <el-skeleton-item variant="text" style="width: 95%; margin-bottom: 20px;" />
                        <el-skeleton-item variant="text" style="width: 100%; margin-bottom: 20px;" />
                        <el-skeleton-item variant="text" style="width: 85%; margin-bottom: 20px;" />
                        <el-skeleton-item variant="text" style="width: 100%; margin-bottom: 20px;" />
                        <el-skeleton-item variant="text" style="width: 80%;" />
                    </div>
                </template>
            </el-skeleton>
        </div>

        <!-- 错误状态 -->
        <div v-else-if="error" class="error-container">
            <el-empty description="加载失败">
                <el-button type="primary" @click="fetchChapterDetail">重新加载</el-button>
            </el-empty>
        </div>

        <!-- 章节内容 -->
        <div v-else-if="chapter" class="chapter-content">
            <div class="chapter-title-container" @click="goToBookDetail">
                <el-icon size="20px">
                    <ArrowLeft />
                </el-icon>
                <h1 class="chapter-title">{{ chapter.title }}</h1>
            </div>

            <div 
                class="chapter-text"
                @contextmenu.prevent
                @selectstart.prevent
                @dragstart.prevent
            >
                <!-- 付费章节只显示部分内容 -->
                <div v-if="isPay && chapter.paragraphs && chapter.paragraphs.length" class="paragraph-content">
                    <p v-for="(paragraph, index) in chapter.paragraphs.slice(0, 3)" :key="index" class="paragraph">
                        {{ paragraph }}
                    </p>
                    <div class="pay-content-mask">
                        <div class="mask-content">
                            <div class="mask-icon">
                                <el-icon size="48px" color="#ff9800">
                                    <Lock />
                                </el-icon>
                            </div>
                            <div class="mask-text">
                                <p class="mask-title">这是付费章节</p>
                                <p class="mask-desc">订阅后可阅读完整内容</p>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- 免费章节显示全部内容 -->
                <div v-else-if="!isPay && chapter.paragraphs && chapter.paragraphs.length" class="paragraph-content">
                    <p v-for="(paragraph, index) in chapter.paragraphs" :key="index" class="paragraph">
                        {{ paragraph }}
                    </p>
                </div>
                <!-- 兼容原有的富文本内容 -->
                <div v-else-if="typeof chapter.details === 'string'" v-html="chapter.details" class="rich-content"></div>
            </div>
        </div>

        <!-- 章节菜单 -->
        <div v-if="!loading && !error" class="chapter-menu">
            <div 
                class="chapter-menu-item" 
                :class="{ disabled: !prevChapter }"
                @click="goToPrevChapter"
            >
                <el-icon size="20px">
                    <ArrowUp />
                </el-icon>
                <span>上一章</span>
            </div>
            <div 
                class="chapter-menu-item"
                :class="{ disabled: !nextChapter }"
                @click="goToNextChapter"
            >
                <el-icon size="20px">
                    <ArrowDown />
                </el-icon>
                <span>下一章</span>
            </div>
            <div class="chapter-menu-item" @click="toggleBookshelf">
                <el-icon size="20px">
                    <Reading />
                </el-icon>
                <span>{{ isInBookshelf ? '移出书架' : '加书架' }}</span>
            </div>
            <div class="chapter-menu-item" @click="goToChapterList">
                <el-icon size="20px">
                    <Grid />
                </el-icon>
                <span>目录</span>
            </div>
            <div class="chapter-menu-item" @click="toggleThemeMode">
                <el-icon size="20px">
                    <MoonNight />
                </el-icon>
                <span>{{ isDarkMode ? '日间' : '夜间' }}</span>
            </div>
        </div>

        <!-- 无数据状态 -->
        <div v-else-if="!loading && !error" class="no-data">
            <el-empty description="章节不存在" />
        </div>

        <!-- 目录弹窗 -->
        <CatalogDialog 
            v-model="catalogDialogVisible"
            :chapters="chapterList"
            :current-chapter-id="chapterId"
            @chapter-select="handleChapterSelect"
        />

        <!-- 订阅弹窗 -->
        <SubscriptionPopup
            v-model="subscriptionVisible"
            :chapter-list="chapterList"
            :current-chapter="currentChapterInfo"
            :current-index="currentChapterIndex"
            :book-id="bookId"
            :is-dark-mode="isDarkMode"
            @subscribe="handleSubscribe"
            @batch-subscribe="handleBatchSubscribe"
            @video-unlock="handleVideoUnlock"
        />
    </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { ArrowLeft, ArrowRight, ZoomIn, ZoomOut, MoonNight, ArrowUp, ArrowDown, Reading, Grid, Lock } from '@element-plus/icons-vue';
import { homeApi } from '@/api/home.js';
import { bookshelfApi } from '@/api/bookshelf.js';
import CatalogDialog from '@/components/book/CatalogDialog.vue';
import SubscriptionPopup from '@/components/book/SubscriptionPopup.vue';
import { toggleTheme, getThemeMode, setThemeMode } from '@/utils/theme.js';

export default {
    name: 'ChapterDetail',
    components: {
        ArrowLeft,
        ArrowRight,
        ZoomIn,
        ZoomOut,
        MoonNight,
        ArrowUp,
        ArrowDown,
        Reading,
        Grid,
        Lock,
        CatalogDialog,
        SubscriptionPopup
    },
    setup() {
        const route = useRoute();
        const router = useRouter();
        const bookId = computed(() => route.params.id);
        const chapterId = computed(() => route.params.chapterId);

        // 响应式数据
        const loading = ref(true);
        const error = ref(false);
        const chapter = ref(null);
        const chapterList = ref([]);
        const bookDetail = ref(null);
        const isInBookshelf = ref(false);
        const fontSize = ref(18);
        const isDarkMode = ref(getThemeMode());
        const catalogDialogVisible = ref(false);
        const subscriptionVisible = ref(false);
        const isPay = ref(false);

        // 计算上一章和下一章
        const currentChapterIndex = computed(() => {
            if (!chapterList.value.length || !chapterId.value) return -1;
            return chapterList.value.findIndex(ch => ch.id === chapterId.value);
        });

        const prevChapter = computed(() => {
            const index = currentChapterIndex.value;
            return index > 0 ? chapterList.value[index - 1] : null;
        });

        const nextChapter = computed(() => {
            const index = currentChapterIndex.value;
            return index >= 0 && index < chapterList.value.length - 1 ? chapterList.value[index + 1] : null;
        });

        // 当前章节信息
        const currentChapterInfo = computed(() => {
            return chapterList.value.find(ch => ch.id === chapterId.value) || {};
        });

        // 获取书籍详情
        const getBookDetail = async () => {
            try {
                const response = await homeApi.getBookDetail({ id: bookId.value });
                if (response && response.success) {
                    bookDetail.value = response.result;
                } else {
                    throw new Error(response?.message || '获取书籍详情失败');
                }
            } catch (err) {
                console.error('获取书籍详情失败:', err);
                ElMessage.error(err.message || '获取书籍详情失败');
            }
        };

        // 获取章节详情
        const getBookCatalogDetail = async () => {
            try {
                if (!chapterId.value) {
                    throw new Error('章节ID不存在');
                }

                // 只有登录后才检查是否已购买
                const token = localStorage.getItem('token');
                if (token) {
                    try {
                        const payResponse = await homeApi.getMyShopNovel({
                            bookId: bookId.value,
                            novelId: chapterId.value,
                        });
                        // payResponse为true表示已购买，为false表示未购买
                        isPay.value = !payResponse.result;
                    } catch (err) {
                        console.error('检查付费状态失败:', err);
                        isPay.value = true; // 默认需要付费
                    }
                }

                // 获取章节详情
                const response = await homeApi.getBookCatalogDetail(chapterId.value);
                if (response && response.success) {
                    chapter.value = response.result;
                    
                    // 处理章节内容格式 - 参考readnovels.vue的处理方式
                    if (chapter.value.details) {
                        // 按换行符分割成段落数组
                        chapter.value.paragraphs = chapter.value.details.split('\n')
                    }

                    // 如果章节标记为付费章节，设置付费状态
                    if (chapter.value.isPay != 'Y') {
                        isPay.value = false;
                    }
                } else {
                    throw new Error(response?.message || '获取章节详情失败');
                }

                // 更新阅读进度到书架
                await updateReadProgress();

                // 更新订阅弹窗状态
                updateSubscriptionStatus();

            } catch (err) {
                console.error('获取章节详情失败:', err);
                throw err;
            }
        };

        // 获取章节列表
        const getBookCatalogList = async () => {
            try {
                const response = await homeApi.getBookCatalogList({
                    bookId: bookId.value,
                    pageNo: 1,
                    pageSize: 9999999,
                    reverse: 0
                });

                if (response && response.success && response.result) {
                    chapterList.value = response.result.records || [];
                }
            } catch (err) {
                console.error('获取章节列表失败:', err);
            }
        };

        // 更新阅读进度到书架 - 参考readnovels.vue的实现
        const updateReadProgress = async () => {
            try {
                const token = localStorage.getItem('token');
                if (!token || !bookId.value || !chapterId.value || !bookDetail.value) return;

                const response = await bookshelfApi.saveOrUpdateReadBook({
                    shopId: bookId.value,        // 书籍id
                    novelId: chapterId.value,    // 章节id
                    name: bookDetail.value.name,
                    image: bookDetail.value.image
                });
            } catch (err) {
                console.error('更新阅读进度失败:', err);
            }
        };

        // 主要的数据获取函数
        const fetchChapterDetail = async () => {
            try {
                loading.value = true;
                error.value = false;

                // 先获取书籍详情
                await getBookDetail();
                
                // 获取章节详情
                await getBookCatalogDetail();

                // 获取书籍目录列表（用于上下章节导航）
                await getBookCatalogList();

                // 确保内容加载完成后滚动到顶部
                await nextTick();
                window.scrollTo({ top: 0, behavior: 'smooth' });

            } catch (err) {
                console.error('获取章节详情失败:', err);
                error.value = true;
                ElMessage.error(err.message || '获取章节详情失败');
            } finally {
                loading.value = false;
            }
        };

        // 切换书架状态
        const toggleBookshelf = async () => {
            try {
                const token = localStorage.getItem('token');
                if (!token) {
                    ElMessage.warning('请先登录');
                    return;
                }

                if (isInBookshelf.value) {
                    // 移出书架
                    await bookshelfApi.removeReadBook(bookId.value);
                    isInBookshelf.value = false;
                    ElMessage.success('已移出书架');
                } else {
                    // 添加到书架 - 使用saveOrUpdateReadBook
                    await bookshelfApi.saveOrUpdateReadBook({
                        shopId: bookId.value,
                        novelId: chapterId.value,
                        name: bookDetail.value?.name || '',
                        image: bookDetail.value?.image || ''
                    });
                    isInBookshelf.value = true;
                    ElMessage.success('已添加到书架');
                }
            } catch (err) {
                console.error('操作书架失败:', err);
                ElMessage.error('操作失败，请重试');
            }
        };

        // 导航到上一章
        const goToPrevChapter = () => {
            if (prevChapter.value) {
                router.push(`/book/${bookId.value}/chapter/${prevChapter.value.id}`);
            }
        };

        // 导航到下一章
        const goToNextChapter = () => {
            if (nextChapter.value) {
                router.push(`/book/${bookId.value}/chapter/${nextChapter.value.id}`);
            }
        };

        // 返回
        const goToBookDetail = () => {
            router.back(-1);
        };

        // 跳转到章节列表（目录）
        const goToChapterList = () => {
            catalogDialogVisible.value = true;
        };

        // 处理章节选择
        const handleChapterSelect = (selectedChapterId) => {
            if (selectedChapterId !== chapterId.value) {
                router.push(`/book/${bookId.value}/chapter/${selectedChapterId}`);
            }
        };

        // 调整字体大小
        const toggleFontSize = (change) => {
            const newSize = fontSize.value + change;
            if (newSize >= 14 && newSize <= 24) {
                fontSize.value = newSize;
                document.documentElement.style.setProperty('--reading-font-size', `${fontSize.value}px`);
            }
        };

        // 切换暗黑模式
        const toggleThemeMode = () => {
            isDarkMode.value = !isDarkMode.value;
            setThemeMode(isDarkMode.value);
        };

        // 更新订阅弹窗状态
        const updateSubscriptionStatus = () => {
            if (isPay.value) {
                subscriptionVisible.value = true;
            } else {
                subscriptionVisible.value = false;
            }
        };

        // 处理订阅
        const handleSubscribe = async () => {
            try {
                await homeApi.buyNovel({
                    bookId: bookId.value,
                    novelId: chapterId.value,
                });
                
                isPay.value = false;
                updateSubscriptionStatus();
                ElMessage.success('订阅成功');
                
                // 重新获取章节详情
                await getBookCatalogDetail();
            } catch (err) {
                console.error('订阅失败:', err);
                ElMessage.error('订阅失败，请重试');
            }
        };

        // 处理批量订阅
        const handleBatchSubscribe = async (batchCount) => {
            try {
                // 获取从当前章节开始的连续章节ID
                const chapterIds = [];
                const startIndex = currentChapterIndex.value;
                
                for (let i = 0; i < batchCount && (startIndex + i) < chapterList.value.length; i++) {
                    const chapter = chapterList.value[startIndex + i];
                    // 使用pay字段判断是否已购买，isPay为'Y'且pay为false表示需要购买
                    if (chapter.isPay === 'Y' && !chapter.pay) {
                        chapterIds.push(chapter.id);
                    }
                }
                
                if (chapterIds.length === 0) {
                    ElMessage.warning('没有需要购买的章节');
                    return;
                }
                
                // 调用批量订阅接口
                await homeApi.buyNovel({
                    bookId: bookId.value,
                    novelId: chapterIds.join(',')
                });
                
                ElMessage.success(`成功订阅${chapterIds.length}章`);
                
                // 刷新章节列表状态
                await getBookCatalogList();
                isPay.value = false;
                updateSubscriptionStatus();
                
            } catch (error) {
                console.error('批量订阅失败:', error);
                ElMessage.error('订阅失败，请重试');
            }
        };

        // 处理视频解锁
        const handleVideoUnlock = async () => {
            try {
                ElMessage.info('暂未开放');
                // 这里可以添加视频解锁的逻辑
                // await homeApi.openBookCatalog({
                //     bookId: bookId.value,
                //     catalogId: chapterId.value
                // });
                
                // isPay.value = false;
                // updateSubscriptionStatus();
                
            } catch (error) {
                console.error('视频解锁失败:', error);
                ElMessage.error('解锁失败，请重试');
            }
        };

        // 监听路由变化
        watch([bookId, chapterId], () => {
            if (bookId.value && chapterId.value) {
                // 切换章节时立即滚动到顶部
                window.scrollTo({ top: 0, behavior: 'instant' });
                fetchChapterDetail();
            }
        }, { immediate: true });

        onMounted(() => {
            // 设置初始字体大小
            document.documentElement.style.setProperty('--reading-font-size', `${fontSize.value}px`);

            // 滚动到顶部
            window.scrollTo(0, 0);
        });

        return {
            loading,
            error,
            chapter,
            prevChapter,
            nextChapter,
            isInBookshelf,
            isDarkMode,
            subscriptionVisible,
            isPay,
            currentChapterInfo,
            currentChapterIndex,
            fetchChapterDetail,
            goToPrevChapter,
            goToNextChapter,
            goToBookDetail,
            goToChapterList,
            toggleBookshelf,
            toggleFontSize,
            toggleThemeMode,
            catalogDialogVisible,
            handleChapterSelect,
            handleSubscribe,
            handleBatchSubscribe,
            handleVideoUnlock,
            chapterList,
            chapterId,
        };
    }
};
</script>


<style lang="scss">
// 全局暗黑模式样式
:root {
    --reading-font-size: 18px;
    --reading-background: #f8f8f8;
    --reading-text-color: #333;
    --reading-border-color: #eee;
}

.dark-theme {
    --reading-background: #252525;
    --reading-text-color: #ccc;
    --reading-border-color: #333;

    .chapter-container {
        background-color: var(--reading-background) !important;

        .chapter-header {
            background-color: #202020 !important;
            color: #ddd !important;
            border-bottom-color: #333 !important;
        }

        .chapter-content {
            background-color: var(--reading-background) !important;
            color: var(--reading-text-color) !important;

            .chapter-title {
                color: #eee !important;
            }

            .paragraph {
                color: var(--reading-text-color) !important;
            }

            .pay-content-mask {
                background: linear-gradient(180deg, rgba(26, 26, 26, 0) 0%, rgba(26, 26, 26, 0.9) 50%, rgba(26, 26, 26, 1) 100%) !important;

                .mask-text {
                    .mask-title {
                        color: #ff9800 !important;
                    }

                    .mask-desc {
                        color: #999 !important;
                    }
                }
            }
        }

        .el-button {
            background-color: #333 !important;
            border-color: #555 !important;
            color: #ddd !important;

            &.is-plain {
                background: transparent !important;
            }

            &.el-button--primary {
                background-color: var(--el-color-primary) !important;
                border-color: var(--el-color-primary) !important;
                color: #fff !important;
            }
        }
    }
}
</style>

<style lang="scss" scoped>
@use '@/assets/styles/variables.scss' as vars;

.chapter-container {
    min-height: 100vh;
    display: flex;
    flex-direction: column;
}


.chapter-content {
    flex: 1;
    width: 1100px;
    padding: 30px 20px 50px;
    background-color: #F3EFE6;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
    /* 防止内容复制 */
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;

    .chapter-title-container {
        display: flex;
        align-items: center;
        margin-bottom: 30px;
        padding-bottom: 10px;
        border-bottom: 1px solid #e9e4d8;
        cursor: pointer;

        .chapter-title {
            display: flex;
            align-items: center;
            text-align: left;
            font-size: 24px;
            color: #333;
            margin-left: 10px;
            /* 禁止选中标题 */
            user-select: none;
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
        }

    }


    .chapter-text {
        line-height: 1.8;
        /* 禁止选中文字 */
        user-select: none;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;

        .paragraph-content {
            width: 100%;

                    .paragraph {
            text-indent: 2em;
            margin-bottom: 30px;
            line-height: 1.8;
            font-size: var(--reading-font-size);
            color: #333;
            word-wrap: break-word;
            word-break: normal;
            white-space: normal;
            transition: color 0.3s ease;
            /* 禁止选中文字 */
            user-select: none;
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
        }

        .pay-content-mask {
            position: relative;
            margin-top: 40px;
            padding: 60px 20px;
            background: linear-gradient(180deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 50%, rgba(255, 255, 255, 1) 100%);
            border-radius: 8px;
            text-align: center;

            .mask-content {
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                gap: 20px;

                .mask-icon {
                    margin-bottom: 10px;
                }

                .mask-text {
                    .mask-title {
                        font-size: 18px;
                        font-weight: bold;
                        color: #ff9800;
                        margin: 0 0 8px 0;
                    }

                    .mask-desc {
                        font-size: 14px;
                        color: #666;
                        margin: 0;
                    }
                }
            }
        }
        }

        .paragraph {
            margin-bottom: 20px;
            font-size: var(--reading-font-size);
            color: var(--reading-text-color);
            text-indent: 2em;
            /* 禁止选中文字 */
            user-select: none;
            -webkit-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
        }
    }
}

.chapter-menu {
    position: fixed;
    bottom: 20%;
    left: 50%;
    transform: translateX(550px);
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 20px;
    padding: 0 20px;
    gap: 10px;

    .chapter-menu-item {
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        border-radius: 10px;
        background-color: #F3EFE6;
        cursor: pointer;
        height: 80px;
        width: 80px;
        font-size: 14px;
        gap: 5px;
    }
    
}


.reading-settings {
    position: fixed;
    bottom: 30px;
    right: 30px;
    z-index: 10;

    .settings-buttons {
        display: flex;
        flex-direction: column;
        gap: 10px;

        .el-button {
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
        }
    }
}

// 加载和错误状态样式
.loading-container,
.error-container,
.no-data {
    padding: 60px 20px;
    text-align: center;
    min-height: 300px;
    display: flex;
    align-items: center;
    justify-content: center;
}

// 富文本内容样式
.rich-content {
    line-height: 1.8;
    font-size: var(--reading-font-size);
    color: var(--reading-text-color);
    /* 禁止选中文字 */
    user-select: none;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;

    :deep(p) {
        margin-bottom: 20px;
        text-indent: 2em;
        /* 禁止选中文字 */
        user-select: none;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
    }

    :deep(br) {
        line-height: 1.8;
    }

    :deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
        margin: 20px 0 15px 0;
        color: #333;
        text-indent: 0;
        /* 禁止选中文字 */
        user-select: none;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
    }

    :deep(img) {
        max-width: 100%;
        height: auto;
        margin: 15px 0;
        /* 禁止选中图片 */
        user-select: none;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        pointer-events: none;
    }
}

// 菜单禁用状态
.chapter-menu-item.disabled {
    opacity: 0.5;
    cursor: not-allowed;
    pointer-events: none;
}

// 响应式调整
@media screen and (max-width: vars.$md) {
    .chapter-content {
        padding: 20px 15px 40px;
    }

    .chapter-menu {
        transform: translateX(0);
        position: fixed;
        bottom: 20px;
        left: 50%;
        transform: translateX(-50%);
        flex-direction: row;
        gap: 15px;
        width: auto;

        .chapter-menu-item {
            width: 60px;
            height: 60px;
            font-size: 12px;
        }
    }

    .loading-container,
    .error-container,
    .no-data {
        padding: 40px 15px;
        min-height: 200px;
    }
}
</style>