<template>
    <div class="book-comments-container">
        <div class="section-header">
            <h3 class="section-title">书评</h3>
            <div class="section-controls">
                <el-button type="primary" size="small" @click="handleWriteComment">
                    写书评
                </el-button>
            </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
            <el-skeleton :rows="5" animated>
                <template #template>
                    <div style="display: flex; margin-bottom: 20px;">
                        <el-skeleton-item variant="circle" style="width: 48px; height: 48px; margin-right: 16px;" />
                        <div style="flex: 1;">
                            <el-skeleton-item variant="text" style="width: 30%; margin-bottom: 8px;" />
                            <el-skeleton-item variant="text" style="width: 100%; margin-bottom: 8px;" />
                            <el-skeleton-item variant="text" style="width: 80%;" />
                        </div>
                    </div>
                </template>
            </el-skeleton>
        </div>

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

        <!-- 评论表单 -->
        <div class="comment-input" v-if="showCommentForm">
            <el-input 
                v-model="commentText" 
                type="textarea" 
                :rows="4" 
                placeholder="请输入您的书评..." 
                maxlength="500"
                show-word-limit 
            />
            <div class="comment-actions">
                <el-button @click="cancelComment">取消</el-button>
                <el-button 
                    type="primary" 
                    @click="submitComment" 
                    :disabled="!commentText.trim() || submitting"
                    :loading="submitting"
                >
                    提交
                </el-button>
            </div>
        </div>

        <!-- 评论列表 -->
        <div v-else-if="!loading" class="comments-list">
            <div v-for="(comment, index) in comments" :key="comment.id" class="comment-item">
                <div class="user-avatar">
                    <img :src="comment.hanHaiMember.headImage || defaultAvatar" :alt="comment.hanHaiMember.nickName">
                </div>
                <div class="comment-content">
                    <div class="comment-header">
                        <span class="username">{{ comment.hanHaiMember.nickName || '匿名用户' }}</span>
                        <span class="time">{{ formatTime(comment.createTime) }}</span>
                    </div>
                    <div class="comment-text">{{ comment.comment }}</div>
                    <div class="comment-footer">
                        <div class="comment-actions">
                            <span class="action-item" @click="toggleReplyForm(index)">
                                <el-icon>
                                    <Message />
                                </el-icon> 回复
                            </span>
                            <!-- <span class="action-item" @click="toggleLike(comment, index)">
                                <el-icon>
                                    <Star />
                                </el-icon> 
                                {{ comment.likeCount > 0 ? comment.likeCount : '点赞' }}
                            </span> -->
                        </div>
                    </div>
                    
                    <!-- 回复表单 -->
                    <div class="reply-form" v-if="activeReplyIndex === index">
                        <el-input 
                            v-model="replyText" 
                            type="textarea" 
                            :rows="2" 
                            placeholder="请输入回复内容..." 
                            maxlength="300" 
                            show-word-limit 
                        />
                        <div class="reply-actions">
                            <el-button size="small" @click="cancelReply">取消</el-button>
                            <el-button 
                                size="small" 
                                type="primary" 
                                @click="submitReply(comment.id, index)" 
                                :disabled="!replyText.trim() || replySubmitting"
                                :loading="replySubmitting"
                            >
                                回复
                            </el-button>
                        </div>
                    </div>
                    
                    <!-- 回复列表 -->
                    <div class="replies-list" v-if="comment.children && comment.children.length > 0">
                        <div v-for="(reply, replyIndex) in comment.children" :key="reply.id || replyIndex" class="reply-item">
                            <div class="user-avatar">
                                <img :src="reply.hanHaiMember.headImage || defaultAvatar" :alt="reply.hanHaiMember.nickName">
                            </div>
                            <div class="reply-content">
                                <div class="reply-header">
                                    <span class="username">{{ reply.hanHaiMember.nickName || '匿名用户' }}</span>
                                    <span class="time">{{ formatTime(reply.createTime) }}</span>
                                </div>
                                <div class="reply-text">{{ reply.comment }}</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 分页 -->
        <div class="comments-footer" v-if="!loading && !error && totalComments > 0">
            <el-pagination 
                v-model:currentPage="currentPage" 
                :page-size="pageSize" 
                layout="prev, pager, next"
                :total="totalComments" 
                @current-change="handlePageChange" 
            />
        </div>

        <!-- 无评论状态 -->
        <div class="no-comments" v-if="!loading && !error && comments.length === 0">
            <el-empty description="暂无书评，快来发表第一条书评吧！" />
        </div>
    </div>
</template>

<script>
import { defineComponent, ref, computed, onMounted, watch } from 'vue';
import { Message, Star } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { commentApi } from '@/api/user.js';

export default defineComponent({
    name: 'BookComments',
    components: {
        Message,
        Star
    },
    props: {
        bookId: {
            type: String,
            required: true
        }
    },
    setup(props) {
        // 响应式数据
        const loading = ref(true);
        const error = ref(false);
        const comments = ref([]);
        const defaultAvatar = ref('@/assets/images/center/headImage.png');
        
        // 评论表单相关
        const showCommentForm = ref(false);
        const commentText = ref('');
        const submitting = ref(false);
        
        // 分页相关
        const currentPage = ref(1);
        const pageSize = ref(10);
        const totalComments = ref(0);
        
        // 回复相关状态
        const activeReplyIndex = ref(null);
        const replyText = ref('');
        const replySubmitting = ref(false);

        // 检查登录状态
        const isLoggedIn = computed(() => {
            return !!localStorage.getItem('token');
        });

        // 时间格式化
        const formatTime = (timeStr) => {
            if (!timeStr) return '';
            const date = new Date(timeStr);
            return date.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit'
            });
        };

        // 获取评论列表
        const fetchComments = async () => {
            try {
                loading.value = true;
                error.value = false;

                const response = await commentApi.getCommentList({
                    bookId: props.bookId,
                    pageNo: currentPage.value,
                    pageSize: pageSize.value
                });

                if (response && response.success) {
                    const result = response.result;
                    if (result && result.records) {
                        comments.value = result.records;
                        totalComments.value = result.total || 0;
                    } else {
                        comments.value = [];
                        totalComments.value = 0;
                    }
                } else {
                    throw new Error(response?.message || '获取评论失败');
                }
            } catch (err) {
                console.error('获取评论失败:', err);
                error.value = true;
                ElMessage.error(err.message || '获取评论失败');
            } finally {
                loading.value = false;
            }
        };

        // 处理写评论按钮点击
        const handleWriteComment = () => {
            if (!isLoggedIn.value) {
                ElMessage.warning('请先登录后再发表评论');
                return;
            }
            showCommentForm.value = true;
        };

        // 取消评论
        const cancelComment = () => {
            showCommentForm.value = false;
            commentText.value = '';
        };

        // 提交评论
        const submitComment = async () => {
            if (!commentText.value.trim()) {
                ElMessage.warning('请输入评论内容');
                return;
            }

            if (!isLoggedIn.value) {
                ElMessage.warning('请先登录后再发表评论');
                return;
            }

            try {
                submitting.value = true;

                const response = await commentApi.saveComment({
                    bookId: props.bookId,
                    content: commentText.value.trim()
                });

                if (response && response.success) {
                    ElMessage.success('评论发表成功！');
                    commentText.value = '';
                    showCommentForm.value = false;
                    
                    // 重新加载第一页评论
                    currentPage.value = 1;
                    await fetchComments();
                } else {
                    throw new Error(response?.message || '发表评论失败');
                }
            } catch (err) {
                console.error('发表评论失败:', err);
                ElMessage.error(err.message || '发表评论失败');
            } finally {
                submitting.value = false;
            }
        };

        // 切换回复表单的显示状态
        const toggleReplyForm = (index) => {
            if (!isLoggedIn.value) {
                ElMessage.warning('请先登录后再回复评论');
                return;
            }

            if (activeReplyIndex.value === index) {
                activeReplyIndex.value = null;
            } else {
                activeReplyIndex.value = index;
                replyText.value = '';
            }
        };

        // 取消回复
        const cancelReply = () => {
            activeReplyIndex.value = null;
            replyText.value = '';
        };

        // 提交回复
        const submitReply = async (commentId, index) => {
            if (!replyText.value.trim()) {
                ElMessage.warning('请输入回复内容');
                return;
            }

            if (!isLoggedIn.value) {
                ElMessage.warning('请先登录后再回复评论');
                return;
            }

            try {
                replySubmitting.value = true;

                const response = await commentApi.replyComment({
                    commentId: commentId,
                    content: replyText.value.trim()
                });

                if (response && response.success) {
                    ElMessage.success('回复成功！');
                    
                    // 重置状态
                    replyText.value = '';
                    activeReplyIndex.value = null;
                    
                    // 重新加载评论列表以显示最新回复
                    await fetchComments();
                } else {
                    throw new Error(response?.message || '回复失败');
                }
            } catch (err) {
                console.error('回复失败:', err);
                ElMessage.error(err.message || '回复失败');
            } finally {
                replySubmitting.value = false;
            }
        };

        // 点赞功能（如果有对应API的话）
        const toggleLike = async (comment, index) => {
            if (!isLoggedIn.value) {
                ElMessage.warning('请先登录后再点赞');
                return;
            }
            
            // 目前API中没有点赞接口，这里只做UI反馈
            ElMessage.info('点赞功能暂未开放');
        };

        // 分页处理
        const handlePageChange = async (page) => {
            currentPage.value = page;
            await fetchComments();
        };

        // 监听bookId变化
        watch(() => props.bookId, (newBookId) => {
            if (newBookId) {
                currentPage.value = 1;
                fetchComments();
            }
        }, { immediate: true });

        return {
            loading,
            error,
            comments,
            defaultAvatar,
            showCommentForm,
            commentText,
            submitting,
            currentPage,
            pageSize,
            totalComments,
            activeReplyIndex,
            replyText,
            replySubmitting,
            isLoggedIn,
            formatTime,
            fetchComments,
            handleWriteComment,
            cancelComment,
            submitComment,
            toggleReplyForm,
            cancelReply,
            submitReply,
            toggleLike,
            handlePageChange
        };
    }
});
</script>

<style lang="scss" scoped>
.book-comments-container {
    background-color: #fff;
    border-radius: 6px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
    padding: 15px;
    margin-bottom: 3px;

    .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
        padding-bottom: 12px;
        border-bottom: 1px solid #eee;

        .section-title {
            font-size: 18px;
            font-weight: bold;
            color: #333;
            margin: 0;
            position: relative;
            padding-left: 12px;

            &::before {
                content: '';
                position: absolute;
                left: 0;
                top: 4px;
                height: 18px;
                width: 4px;
                background-color: #0A2463;
                border-radius: 2px;
            }
        }
    }

    .comment-input {
        margin-bottom: 24px;

        .comment-actions {
            display: flex;
            justify-content: flex-end;
            margin-top: 12px;
            gap: 10px;
        }
    }

    .comments-list {
        .comment-item {
            display: flex;
            padding: 16px 0;
            border-bottom: 1px solid #eee;

            &:last-child {
                border-bottom: none;
            }

            .user-avatar {
                width: 48px;
                height: 48px;
                border-radius: 50%;
                overflow: hidden;
                margin-right: 16px;

                img {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                }
            }

            .comment-content {
                flex: 1;
                min-width: 0;

                .comment-header {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    margin-bottom: 8px;

                    .username {
                        font-size: 16px;
                        font-weight: 500;
                        color: #333;
                    }

                    .time {
                        font-size: 14px;
                        color: #999;
                    }
                }

                .comment-text {
                    font-size: 15px;
                    line-height: 1.6;
                    color: #333;
                    margin-bottom: 12px;
                    word-break: break-word;
                }

                .comment-footer {
                    .comment-actions {
                        display: flex;
                        gap: 16px;

                        .action-item {
                            display: flex;
                            align-items: center;
                            gap: 4px;
                            font-size: 14px;
                            color: #666;
                            cursor: pointer;

                            &:hover {
                                color: #0A2463;
                            }
                        }
                    }
                }
                
                // 回复表单样式
                .reply-form {
                    margin-top: 12px;
                    padding: 12px;
                    background-color: #f9f9f9;
                    border-radius: 4px;
                    
                    .reply-actions {
                        display: flex;
                        justify-content: flex-end;
                        margin-top: 8px;
                        gap: 8px;
                    }
                }
                
                // 回复列表样式
                .replies-list {
                    margin-top: 16px;
                    padding-left: 12px;
                    border-left: 2px solid #eee;
                    
                    .reply-item {
                        display: flex;
                        padding: 12px 0;
                        
                        .user-avatar {
                            width: 36px;
                            height: 36px;
                            margin-right: 12px;
                        }
                        
                        .reply-content {
                            flex: 1;
                            
                            .reply-header {
                                display: flex;
                                justify-content: space-between;
                                align-items: center;
                                margin-bottom: 6px;
                                
                                .username {
                                    font-size: 14px;
                                    font-weight: 500;
                                }
                                
                                .time {
                                    font-size: 12px;
                                    color: #999;
                                }
                            }
                            
                            .reply-text {
                                font-size: 14px;
                                line-height: 1.5;
                                color: #333;
                            }
                        }
                    }
                }
            }
        }
    }

    .comments-footer {
        display: flex;
        justify-content: center;
        padding-top: 20px;
    }

    .no-comments {
        padding: 30px 0;
    }

    .loading-container,
    .error-container {
        padding: 30px 20px;
        text-align: center;
    }

    .loading-container {
        .el-skeleton {
            text-align: left;
        }
    }
}
</style>