<template>
    <div class="book-detail-container">
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
            <el-skeleton :rows="8" animated />
        </div>
        
        <!-- 详情内容 -->
        <div v-else>
            <!-- 小说基本信息部分 -->
            <div class="book-info-wrapper">
                <div class="book-info">
                    <div class="book-cover">
                        <img :src="book.image && book.image.split(',')[0]" :alt="book.title || book.name">
                    </div>
                    <div class="book-details">
                        <h1 class="book-title">{{ book.title || book.name }}</h1>
                        <div class="book-meta">
                            <div class="meta-item">
                                <span class="label">作者：</span>
                                <span class="value">{{ book.author }}</span>
                            </div>
                            <div class="meta-item book-status-row">
                                <span class="status-badge">{{ book.status }}</span>
                                <span class="dot">·</span>
                                <span class="reading-tip">大家都在读</span>
                            </div>
                        </div>
                        <div class="book-user-info">
                            <div class="user-badges" style="display: flex;flex-direction: column;align-items: center;">
                                <img class="level-icon" src="@/assets/images/book/level.png" alt="我的等级" />
                                <span class="badge-label">我的等级</span>
                            </div>
                            <div class="user-medal">
                                <img class="medal-icon" :src="userInfo.levelIcon" alt="勋章" />
                            </div>
                            <div class="user-avatar-block">
                                <img class="user-avatar" :src="userInfo.avatar" alt="用户头像" />
                                <span class="user-name">{{ userInfo.name }}</span>
                                <span class="dot">·</span>
                                <span class="user-title">{{ userInfo.role }}</span>
                            </div>
                            <span class="user-intimacy">{{ userInfo.intimacy }} 累计亲密值</span>
                        </div>

                        <div class="action-buttons">
                            <div class="action-btn-group">
                                <el-button class="reward-btn" plain @click="showRewardDialog">互动打赏</el-button>
                            </div>
                            <div class="action-btn-group">
                                <el-button
                                  :class="['add-to-shelf-btn', isInShelf ? 'in-shelf' : '']"
                                  :type="isInShelf ? '' : 'primary'"
                                  @click="toggleShelf"
                                >{{ isInShelf ? '已加入书架' : '加入书架' }}</el-button>
                            </div>
                            <div class="action-btn-group">
                                <el-button class="read-btn" 
                                v-if="chapters.length > 0"
                                @click="goToChapter(readButtonInfo.chapterId)"
                                style="background:#0A2463;color:#fff;border:none;">
                                    <div class="read-btn-content">
                                        <div class="read-btn-text">{{ readButtonInfo.text }}</div>
                                        <!-- <div v-if="readButtonInfo.subtitle" class="read-btn-subtitle">{{ readButtonInfo.subtitle }}</div> -->
                                    </div>
                                </el-button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- 主体内容区域：左右分栏 -->
            <div class="book-main-content">
                <div class="main-left">
                    <!-- 推荐票/亲密值统计 -->
                    <BookStats 
                        :book-data="book" 
                        :book-id="bookId" 
                        @recommend-success="handleRecommendSuccess" 
                    />
                    <!-- 小说介绍 -->
                    <BookIntro :book-data="book" />
                    <!-- 目录 -->
                    <BookCatalog :book-id="bookId" :chapters="chapters" />
                    <!-- 评论 -->
                    <BookComments :book-id="bookId" />
                </div>
                <div class="main-right">
                    <!-- 读者亲密值榜单 -->
                    <IntimacyRanking :book-id="bookId" />
                </div>
            </div>
        </div>
        
        <!-- 互动打赏弹窗 -->
        <InteractiveReward 
            v-model:visible="rewardDialogVisible" 
            :book-id="bookId"
            @reward-success="handleRewardSuccess"
        />
    </div>
</template>

<script>
import { ref, reactive, onMounted, onBeforeUnmount, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useMainStore } from '@/store';
import BookCard from '@/components/common/BookCard.vue';
import BookStats from '@/components/book/BookStats.vue';
import BookIntro from '@/components/book/BookIntro.vue';
import BookCatalog from '@/components/book/BookCatalog.vue';
import BookComments from '@/components/book/BookComments.vue';
import IntimacyRanking from '@/components/ranking/IntimacyRanking.vue';
import InteractiveReward from '@/components/book/InteractiveReward.vue';
import { homeApi } from '@/api/modules.js';
import { bookshelfApi, achievementApi } from '@/api/bookshelf.js';
import { requireLogin } from '@/utils/auth.js';

export default {
    name: 'BookDetail',
    components: {
        BookCard,
        BookStats,
        BookIntro,
        BookCatalog,
        BookComments,
        IntimacyRanking,
        InteractiveReward
    },
    setup() {
        const route = useRoute();
        const router = useRouter();
        const store = useMainStore();
        const bookId = route.params.id;

        // 响应式数据
        const loading = ref(false);
        const book = ref({});
        const recommendedBooks = ref([]);
        const chapters = ref([]);
        const isInShelf = ref(false);
        const readingRecord = ref(null); // 阅读记录
        const rewardDialogVisible = ref(false);
        const userAchievement = ref({}); // 用户成就信息

        // 获取用户成就信息
        const fetchUserAchievement = async () => {
            if (!store.isAuthenticated) {
                userAchievement.value = {};
                return;
            }

            try {
                const response = await achievementApi.getAchievementByBookId(bookId);
                // 新的API返回结构：response.result 包含完整的成就信息
                userAchievement.value = response?.result || {};
            } catch (error) {
                console.error('获取用户成就失败:', error);
                userAchievement.value = {};
            }
        };

        // 计算属性：用户信息（优先使用真实用户信息，回退到默认值）
        const userInfo = computed(() => {
            const user = store.user;
            const achievement = userAchievement.value;
            
            return {
                avatar: user?.headImage || achievement?.hanHaiMember?.headImage || '@/assets/images/center/headImage.png',
                name: user?.nickName || achievement?.hanHaiMember?.nickName || '小巴',
                intimacy: achievement?.num || 0,
                role: achievement?.commonBookAchievement?.title || achievement?.commonBookAchievement?.oldName || '我的等级',
                levelIcon: achievement?.icon || '@/assets/images/book/level.png'
            };
        });

        // 计算属性：阅读按钮文字和章节信息
        const readButtonInfo = computed(() => {
            if (!store.isAuthenticated) {
                return {
                    text: '点击阅读',
                    subtitle: '',
                    chapterId: chapters.value[0]?.id || null
                };
            }

            if (readingRecord.value && readingRecord.value.id) {
                // 找到对应的章节信息
                const currentChapter = chapters.value.find(ch => ch.id === readingRecord.value.id);
                return {
                    text: '继续阅读',
                    subtitle: currentChapter ? currentChapter.title : '继续上次阅读',
                    chapterId: readingRecord.value.id
                };
            }

            return {
                text: '开始阅读',
                subtitle: chapters.value[0]?.title || '',
                chapterId: chapters.value[0]?.id || null
            };
        });

        // 获取书籍详情
        const fetchBookDetail = async () => {
            loading.value = true;
            try {
                const response = await homeApi.getBookDetail({ id: bookId });
                if (response.success) {
                    const bookData = response.result;
                    // 处理状态显示
                    const statusText = bookData.status === 1 ? '已完结' : '连载中';
                    
                    book.value = {
                        ...bookData,
                        cover: bookData.image || bookData.cover,
                        title: bookData.name || bookData.title,
                        description: bookData.details || bookData.description,
                        status: statusText
                    };
                }
            } catch (error) {
                console.error('获取书籍详情失败:', error);
            } finally {
                loading.value = false;
            }
        };

        // 获取章节目录
        const fetchChapters = async () => {
            try {
                const response = await homeApi.getBookCatalogList({
                    bookId: bookId,
                    pageNo: 1,
                    pageSize: 100000, // 获取所有章节
                });
                
                if (response.success && response.result) {
                    // 处理章节数据格式
                    const catalogData = response.result.records || response.result || [];
                    chapters.value = catalogData
                }
            } catch (error) {
                console.error('获取章节目录失败:', error);
                chapters.value = [];
            }
        };

        // 检查书是否在书架中
        const checkBookInShelf = async () => {
            if (!store.isAuthenticated) {
                isInShelf.value = false;
                return;
            }

            try {
                const response = await bookshelfApi.isAddBook(bookId);
                isInShelf.value = !!response.result;
            } catch (error) {
                console.error('检查书架状态失败:', error);
                isInShelf.value = false;
            }
        };

        // 获取阅读记录
        const fetchReadingRecord = async () => {
            if (!store.isAuthenticated) {
                readingRecord.value = null;
                return;
            }

            try {
                const response = await bookshelfApi.getReadChapterByBookId(bookId);
                readingRecord.value = response.result || null;
            } catch (error) {
                console.error('获取阅读记录失败:', error);
                readingRecord.value = null;
            }
        };

        const activeTab = ref('intro');
        const currentPage = ref(1);
        const commentText = ref('');

        const handlePageChange = (page) => {
            currentPage.value = page;
            // 实际应用中这里应该加载对应页的数据
        };

        // 创建一个清理函数
        const cleanup = () => {
            // 清理所有响应式数据
            Object.keys(book).forEach(key => {
                if (typeof book[key] === 'object') {
                    book[key] = null;
                }
            });
            activeTab.value = 'intro';
            currentPage.value = 1;
            commentText.value = '';
            isInShelf.value = false;
            readingRecord.value = null;
            rewardDialogVisible.value = false;
            userAchievement.value = {};
        };

        // 在组件销毁前清理
        onBeforeUnmount(() => {
            cleanup();
        });

        // 智能阅读功能
        const goToChapter = (chapterId) => {
            requireLogin(() => {
                if (!chapterId) {
                    ElMessage.warning('暂无章节可阅读');
                    return;
                }
                
                cleanup();
                router.push({
                    name: 'ChapterDetail',
                    params: {
                        id: bookId,
                        chapterId: chapterId
                    }
                });
            });
        };

        // 切换书架状态
        const toggleShelf = () => {
            requireLogin(async () => {
                try {
                    if (isInShelf.value) {
                        // 从书架移除
                        await bookshelfApi.deleteBookshelfByBookId(bookId);
                        isInShelf.value = false;
                        ElMessage.success('已从书架移除');
                    } else {
                        // 添加到书架
                        const firstChapter = chapters.value[0];
                        const params = {
                            shopId: bookId,
                            name: book.value.title || book.value.name,
                            image: book.value.cover || book.value.image,
                            novelId: firstChapter?.id || null
                        };
                        
                        await bookshelfApi.addReadBook(params);
                        isInShelf.value = true;
                        ElMessage.success('已加入书架');
                        
                        // 重新获取阅读记录
                        await fetchReadingRecord();
                    }
                } catch (error) {
                    console.error('书架操作失败:', error);
                    ElMessage.error('操作失败，请稍后重试');
                }
            });
        };

        // 显示互动打赏弹窗
        const showRewardDialog = () => {
            requireLogin(() => {
                rewardDialogVisible.value = true;
            });
        };

        // 处理打赏成功
        const handleRewardSuccess = (items) => {
            console.log('打赏成功，打赏项目:', items);
            ElMessage.success('打赏成功！');
            
            // 重新获取书籍详情和用户成就信息
            fetchBookDetail();
            if (store.isAuthenticated) {
                fetchUserAchievement();
            }
        };

        // 处理投推荐票成功
        const handleRecommendSuccess = () => {
            console.log('投推荐票成功');
            
            // 重新获取书籍详情和用户成就信息
            fetchBookDetail();
            if (store.isAuthenticated) {
                fetchUserAchievement();
            }
        };

        // 跳转到写书评页面
        const goToWriteReview = () => {
            requireLogin(() => {
                // 这里可以跳转到书评编写页面
                // router.push(`/book/${bookId}/review/write`);
                ElMessage.info('书评功能开发中...');
            });
        };

        // 查看亲密值排行榜详情
        const viewIntimacyRanking = () => {
            // 可以在这里打开排行榜详情弹窗或跳转到详情页面
            ElMessage.info('亲密值排行榜详情功能开发中...');
        };

        onMounted(() => {
            // 并行加载书籍详情和章节目录
            Promise.all([
                fetchBookDetail(),
                fetchChapters()
            ]).then(() => {
                // 书籍和章节信息加载完成后，检查用户相关状态
                if (store.isAuthenticated) {
                    Promise.all([
                        checkBookInShelf(),
                        fetchReadingRecord(),
                        fetchUserAchievement()
                    ]);
                }
            });
        });

        return {
            loading,
            book,
            bookId,
            recommendedBooks,
            chapters,
            activeTab,
            currentPage,
            commentText,
            handlePageChange,
            goToChapter,
            isInShelf,
            toggleShelf,
            rewardDialogVisible,
            showRewardDialog,
            handleRewardSuccess,
            handleRecommendSuccess,
            goToWriteReview,
            viewIntimacyRanking,
            cleanup,
            readingRecord,
            readButtonInfo,
            userInfo,
            userAchievement
        };
    }
};
</script>

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

.book-detail-container {
    width: 100%;
    background-color: #f5f5f5;
}

.loading-container {
    padding: 40px 20px;
    max-width: 1200px;
    margin: 0 auto;
}

// 小说基本信息部分
.book-info-wrapper {
    background-color: #fff;
    padding: 30px 0;
    border-bottom: 1px solid #eee;

    .book-info {
        display: flex;
        max-width: 1200px;
        margin: 0 auto;
        padding: 0 20px;

        .book-cover {
            width: 165px;
            height: 220px;
            margin-right: 30px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);

            img {
                width: 100%;
                height: 100%;
                object-fit: cover;
                border-radius: 6px;
            }
        }

        .book-details {
            flex: 1;

            .book-title {
                font-size: 24px;
                font-weight: bold;
                margin: 0 0 15px 0;
                color: #333;
            }

            .book-meta {
                margin-bottom: 8px;
                .book-status-row {
                    display: flex;
                    align-items: center;
                    font-size: 15px;
                    margin-top: 10px;
                    .status-badge {
                        background: #eaffea;
                        color: #52c41a;
                        border-radius: 6px;
                        padding: 2px 12px;
                        font-size: 15px;
                        font-weight: 500;
                        margin-right: 8px;
                    }
                    .dot {
                        color: #d1d1d1;
                        margin: 0 8px;
                        font-size: 18px;
                    }
                    .reading-tip {
                        color: #bdbdbd;
                        font-size: 15px;
                    }
                }
            }
            .book-user-info {
                display: flex;
                align-items: center;
                margin-bottom: 18px;
                .user-badges {
                    display: flex;
                    align-items: center;
                    margin-right: 18px;
                    .level-icon {
                        width: 36px;
                        height: 36px;
                    }
                    .badge-label {
                        color: #b88a4a;
                        font-size: 14px;
                        margin-left: 4px;
                    }
                }
                .user-medal {
                    margin-right: 18px;
                    .medal-icon {
                        width: 44px;
                        height: 44px;
                    }
                }
                .user-avatar-block {
                    display: flex;
                    align-items: center;
                    margin-right: 18px;
                    .user-avatar {
                        width: 36px;
                        height: 36px;
                        border-radius: 50%;
                        margin-right: 8px;
                    }
                    .user-name {
                        color: #222;
                        font-size: 16px;
                        font-weight: 500;
                        margin-right: 4px;
                    }
                    .dot {
                        color: #d1d1d1;
                        margin: 0 8px;
                        font-size: 18px;
                    }
                    .user-title {
                        background: #ede6ff;
                        color: #a97cff;
                        border-radius: 8px;
                        padding: 2px 10px;
                        font-size: 15px;
                        margin-left: 2px;
                    }
                }
                .user-intimacy {
                    color: #bdbdbd;
                    font-size: 15px;
                }
            }

            .action-buttons {
                display: flex;
                gap: 24px;
                margin-top: 10px;
                .action-btn-group {
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    .el-button {
                        width: 140px;
                        height: 40px;
                        font-size: 16px;
                        border-radius: 4px;
                        margin: 0;
                        font-weight: 500;
                    }
                    .diamond-icon {
                        width: 28px;
                        height: 18px;
                        margin-top: 4px;
                    }
                    .reward-btn {
                        color: #0A2463;
                        border: 1.5px solid #0A2463;
                        background: #fff;
                    }
                    .add-to-shelf-btn {
                        background: #FF7C6A;
                        color: #fff;
                        border: none;
                    }
                    .add-to-shelf-btn.in-shelf {
                        background: #fff;
                        color: #FF7C6A;
                        border: 1.5px solid #FF7C6A;
                    }
                    .read-btn {
                        background: #0A2463;
                        color: #fff;
                        border: none;
                        height: auto;
                        min-height: 40px;
                        padding: 8px 16px;
                        
                        .read-btn-content {
                            display: flex;
                            flex-direction: column;
                            align-items: center;
                            line-height: 1.2;
                            
                            .read-btn-text {
                                font-size: 16px;
                                font-weight: 500;
                            }
                            
                            .read-btn-subtitle {
                                font-size: 12px;
                                opacity: 0.8;
                                margin-top: 2px;
                                max-width: 120px;
                                overflow: hidden;
                                text-overflow: ellipsis;
                                white-space: nowrap;
                            }
                        }
                    }
                }
            }
        }
    }
}

.book-main-content {
    display: flex;
    gap: 3px;
    margin-top: 20px;
    .main-left {
        flex: 1.8;
        min-width: 0;
        display: flex;
        flex-direction: column;
        gap: 3px;
    }
    .main-right {
        flex: 1;
        min-width: 220px;
        max-width: 280px;
    }
}
</style>