<template>
    <div class="messages">
        <!-- 页面标题和一键清空 -->
        <div class="header">
            <h1 class="title">
                <el-icon class="title-icon"><Message /></el-icon>
                我的消息
            </h1>
            <el-button 
                type="primary" 
                size="small"
                @click="clearAllMessages"
                :disabled="messages.length === 0"
            >
                一键清空
            </el-button>
        </div>

        <!-- Tab切换 -->
        <div class="tabs-container">
            <el-tabs v-model="activeTab" @tab-click="handleTabClick">
                <el-tab-pane label="我的评论" name="myComments"></el-tab-pane>
                <el-tab-pane label="回复我的" name="replyToMe"></el-tab-pane>
            </el-tabs>
        </div>

        <!-- 消息列表 -->
        <div class="messages-list">
            <!-- 我的评论 -->
            <template v-if="activeTab === 'myComments'">
                <div 
                    v-for="message in myComments" 
                    :key="message.id"
                    class="message-item"
                >
                    <!-- 用户信息 -->
                    <div class="user-info">
                        <el-avatar :size="40" :src="message.hanHaiMember?.headImage" />
                        <div class="user-details">
                            <div class="user-name">{{ message.hanHaiMember?.nickName }}</div>
                            <div class="source-info">
                                来自《{{ message.commonShop?.name }}》
                                <span class="time">{{ message.createTime }}</span>
                            </div>
                        </div>
                    </div>

                    <!-- 评论内容 -->
                    <div class="comment-content">
                        {{ message.comment }}
                    </div>

                    <!-- 删除按钮 -->
                    <div class="action-buttons">
                        <el-button 
                            type="text" 
                            size="small"
                            @click="deleteComment(message.id)"
                            class="reply-btn"
                        >
                            删除
                        </el-button>
                    </div>
                </div>
            </template>

            <!-- 回复我的 -->
            <template v-if="activeTab === 'replyToMe'">
                <!-- 未读评论 -->
                <div v-if="unreadComments.length > 0" class="comment-section">
                    <h3 class="section-title">未读评论·{{ unreadComments.length }}</h3>
                    <div 
                        v-for="message in unreadComments" 
                        :key="message.id"
                        class="message-item"
                    >
                        <!-- 用户信息 -->
                        <div class="user-info">
                            <el-avatar :size="40" :src="message.hanHaiMember?.headImage" />
                            <div class="user-details">
                                <div class="user-name">{{ message.hanHaiMember?.nickName }}</div>
                                <div class="source-info">
                                    来自《{{ message.commonShop?.name }}》
                                    <span class="time">{{ message.createTime }}</span>
                                </div>
                            </div>
                        </div>

                        <!-- 评论内容 -->
                        <div class="comment-content">
                            {{ message.comment }}
                        </div>

                        <!-- 回复按钮 -->
                        <div class="action-buttons">
                            <el-button 
                                type="text" 
                                size="small"
                                @click="toggleReply(message.id)"
                                class="reply-btn"
                            >
                                回复
                            </el-button>
                        </div>

                        <!-- 回复框 -->
                        <div v-if="message.showReply" class="reply-section">
                            <el-input
                                v-model="message.replyContent"
                                type="textarea"
                                :rows="3"
                                placeholder="请输入回复内容..."
                                class="reply-input"
                            />
                            <div class="reply-actions">
                                <el-button 
                                    size="small" 
                                    @click="cancelReply(message.id)"
                                >
                                    取消
                                </el-button>
                                <el-button 
                                    type="primary" 
                                    size="small"
                                    @click="submitReply(message.id)"
                                    :disabled="!message.replyContent?.trim()"
                                >
                                    发送
                                </el-button>
                            </div>
                        </div>

                        <!-- 已有回复 -->
                        <div v-if="message.children && message.children.length > 0" class="existing-replies">
                            <div class="replies-title">回复 ({{ message.children.length }})</div>
                            <div 
                                v-for="reply in message.children" 
                                :key="reply.id"
                                class="existing-reply"
                            >
                                <div class="reply-user">
                                    <el-avatar :size="24" :src="reply.hanHaiMember?.headImage" />
                                    <span class="reply-username">{{ reply.hanHaiMember?.nickName }}</span>
                                    <span class="reply-time">{{ reply.createTime }}</span>
                                </div>
                                <div class="reply-content">{{ reply.comment }}</div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 历史评论 -->
                <div class="comment-section history-section">
                    <h3 class="section-title">历史评论</h3>
                    <div 
                        v-for="message in replyToMeComments" 
                        :key="message.id"
                        class="message-item"
                    >
                        <!-- 用户信息 -->
                        <div class="user-info">
                            <el-avatar :size="40" :src="message.hanHaiMember?.headImage" />
                            <div class="user-details">
                                <div class="user-name">{{ message.hanHaiMember?.nickName }}</div>
                                <div class="source-info">
                                    来自《{{ message.commonShop?.name }}》
                                    <span class="time">{{ message.createTime }}</span>
                                </div>
                            </div>
                        </div>

                        <!-- 评论内容 -->
                        <div class="comment-content">
                            {{ message.comment }}
                        </div>

                        <!-- 回复按钮 -->
                        <div class="action-buttons">
                            <el-button 
                                type="text" 
                                size="small"
                                @click="toggleReply(message.id)"
                                class="reply-btn"
                            >
                                回复
                            </el-button>
                        </div>

                        <!-- 回复框 -->
                        <div v-if="message.showReply" class="reply-section">
                            <el-input
                                v-model="message.replyContent"
                                type="textarea"
                                :rows="3"
                                placeholder="请输入回复内容..."
                                class="reply-input"
                            />
                            <div class="reply-actions">
                                <el-button 
                                    size="small" 
                                    @click="cancelReply(message.id)"
                                >
                                    取消
                                </el-button>
                                <el-button 
                                    type="primary" 
                                    size="small"
                                    @click="submitReply(message.id)"
                                    :disabled="!message.replyContent?.trim()"
                                >
                                    发送
                                </el-button>
                            </div>
                        </div>

                        <!-- 已有回复 -->
                        <div v-if="message.children && message.children.length > 0" class="existing-replies">
                            <div class="replies-title">回复 ({{ message.children.length }})</div>
                            <div 
                                v-for="reply in message.children" 
                                :key="reply.id"
                                class="existing-reply"
                            >
                                <div class="reply-user">
                                    <el-avatar :size="24" :src="reply.hanHaiMember?.headImage" />
                                    <span class="reply-username">{{ reply.hanHaiMember?.nickName }}</span>
                                    <span class="reply-time">{{ reply.createTime }}</span>
                                </div>
                                <div class="reply-content">{{ reply.comment }}</div>
                            </div>
                        </div>
                    </div>
                </div>
            </template>

            <!-- 空状态 -->
            <div v-if="(activeTab === 'myComments' && myComments.length === 0) || 
                     (activeTab === 'replyToMe' && unreadComments.length === 0 && replyToMeComments.length === 0)" 
                 class="empty-state">
                <el-icon class="empty-icon"><Message /></el-icon>
                <p>暂无消息</p>
            </div>
        </div>

        <!-- 分页器 -->
        <div v-if="total > pageSize" class="pagination">
            <el-pagination
                v-model:current-page="currentPage"
                :page-size="pageSize"
                :total="total"
                layout="prev, pager, next"
                @current-change="handlePageChange"
            />
        </div>
    </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useMainStore } from '@/store';
import { useRoute } from 'vue-router';
import { Message } from '@element-plus/icons-vue';
import { commentApi } from '@/api/user.js';

export default {
    name: 'Messages',
    components: {
        Message
    },
    setup() {
        const store = useMainStore();
        const route = useRoute();
        const currentPage = ref(1);
        const pageSize = ref(10);
        const total = ref(0);

        // Tab切换相关
        // 根据路由查询参数决定初始tab，默认是replyToMe
        const activeTab = ref(route.query.tab || 'replyToMe');
        
        // 各类评论数据
        const myComments = ref([]); // 我的评论
        const replyToMeComments = ref([]); // 回复我的评论（历史）
        const unreadComments = ref([]); // 未读评论

        // 兼容旧代码的数据
        const messages = computed(() => {
            return activeTab.value === 'myComments' ? myComments.value : replyToMeComments.value;
        });

        // 获取我的评论列表
        const getMyCommentList = async () => {
            try {
                const res = await commentApi.getMyCommentList({
                    type: 'Y',
                    pageNo: currentPage.value,
                    pageSize: pageSize.value
                });
                if (res.result && res.result.records) {
                    myComments.value = res.result.records.map(item => ({
                        ...item,
                        showReply: false,
                        replyContent: ''
                    }));
                    total.value = res.result.total || 0;
                }
            } catch (error) {
                console.error('获取我的评论失败:', error);
                ElMessage.error('获取我的评论失败');
            }
        };

        // 获取回复我的评论列表（历史）
        const getReplyToMeList = async () => {
            try {
                const res = await commentApi.getMyReplyCommentList({
                    type: 'Y',
                    pageNo: currentPage.value,
                    pageSize: pageSize.value
                });
                if (res.result && res.result.records) {
                    replyToMeComments.value = res.result.records.map(item => ({
                        ...item,
                        showReply: false,
                        replyContent: ''
                    }));
                    total.value = res.result.total || 0;
                }
            } catch (error) {
                console.error('获取回复我的评论失败:', error);
                ElMessage.error('获取回复我的评论失败');
            }
        };

        // 获取未读评论列表
        const getUnreadCommentList = async () => {
            try {
                const res = await commentApi.getMyReplyCommentList({
                    type: 'N',
                    pageNo: 1,
                    pageSize: 100000
                });
                if (res.result && res.result.records) {
                    unreadComments.value = res.result.records.map(item => ({
                        ...item,
                        showReply: false,
                        replyContent: ''
                    }));

                    // 标记为已读
                    unreadComments.value.forEach(comment => {
                        updateCommentRead(comment.id);
                    });
                }
            } catch (error) {
                console.error('获取未读评论失败:', error);
                ElMessage.error('获取未读评论失败');
            }
        };

        // 更新评论已读状态
        const updateCommentRead = async (commentId) => {
            try {
                await commentApi.updateCommentRead(commentId);
            } catch (error) {
                console.error('更新评论已读状态失败:', error);
            }
        };

        // Tab切换处理
        const handleTabClick = (tab) => {
            activeTab.value = tab.props.name;
            currentPage.value = 1;
            loadData();
        };

        // 根据当前tab加载数据
        const loadData = () => {
            if (activeTab.value === 'myComments') {
                getMyCommentList();
            } else if (activeTab.value === 'replyToMe') {
                getUnreadCommentList();
                getReplyToMeList();
            }
        };

        // 删除评论
        const deleteComment = async (commentId) => {
            try {
                await ElMessageBox.confirm(
                    '确认删除该评论吗？',
                    '确认删除',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }
                );

                await commentApi.deleteComment(commentId);
                ElMessage.success('删除成功');
                loadData(); // 重新加载数据
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('删除评论失败:', error);
                    ElMessage.error('删除失败，请重试');
                }
            }
        };

        // 显示回复框
        const toggleReply = (messageId) => {
            const allMessages = [...unreadComments.value, ...replyToMeComments.value];
            const message = allMessages.find(m => m.id === messageId);
            if (message) {
                // 关闭其他回复框
                allMessages.forEach(m => {
                    if (m.id !== messageId) {
                        m.showReply = false;
                        m.replyContent = '';
                    }
                });
                message.showReply = !message.showReply;
                if (!message.showReply) {
                    message.replyContent = '';
                }
            }
        };

        // 取消回复
        const cancelReply = (messageId) => {
            const allMessages = [...unreadComments.value, ...replyToMeComments.value];
            const message = allMessages.find(m => m.id === messageId);
            if (message) {
                message.showReply = false;
                message.replyContent = '';
            }
        };

        // 提交回复
        const submitReply = async (messageId) => {
            const allMessages = [...unreadComments.value, ...replyToMeComments.value];
            const message = allMessages.find(m => m.id === messageId);
            if (message && message.replyContent?.trim()) {
                try {
                    const res = await commentApi.replyComment({
                        commentId: messageId,
                        content: message.replyContent.trim()
                    });
                    
                    // 创建新的回复对象
                    const newReply = {
                        id: res.result?.id || Date.now(), // 如果API返回了ID，使用API的ID，否则使用时间戳
                        comment: message.replyContent.trim(),
                        createTime: new Date().toLocaleString(),
                        hanHaiMember: {
                            headImage: store.userInfo?.headImage || '',
                            nickName: store.userInfo?.nickName || '我'
                        }
                    };
                    
                    // 初始化children数组（如果不存在）
                    if (!message.children) {
                        message.children = [];
                    }
                    
                    // 添加新回复到children数组
                    message.children.push(newReply);
                    
                    message.showReply = false;
                    message.replyContent = '';
                    
                    ElMessage.success('回复成功！');
                } catch (error) {
                    console.error('回复失败:', error);
                    ElMessage.error('回复失败，请重试');
                }
            }
        };

        // 一键清空
        const clearAllMessages = async () => {
            try {
                await ElMessageBox.confirm(
                    '确定要清空所有消息吗？此操作不可恢复',
                    '确认清空',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }
                );

                // 这里应该调用对应的API
                if (activeTab.value === 'myComments') {
                    myComments.value = [];
                } else {
                    unreadComments.value = [];
                    replyToMeComments.value = [];
                }
                total.value = 0;
                currentPage.value = 1;
                
                ElMessage.success('消息已全部清空');
            } catch {
                // 用户取消
            }
        };

        // 页码变化
        const handlePageChange = (page) => {
            currentPage.value = page;
            loadData();
        };

        onMounted(async () => {
            console.log('消息页面已加载');
            // 清空未读消息数量
            if (store.clearUnreadMessages) {
                await store.clearUnreadMessages();
            }
            // 初始化加载数据
            loadData();
        });

        return {
            // 响应式数据
            activeTab,
            myComments,
            replyToMeComments,
            unreadComments,
            messages,
            currentPage,
            pageSize,
            total,
            // 方法
            handleTabClick,
            deleteComment,
            toggleReply,
            cancelReply,
            submitReply,
            clearAllMessages,
            handlePageChange,
            loadData
        };
    }
};
</script>

<style lang="scss" scoped>
.messages {
    padding: 24px;
    max-width: 1200px;
    margin: 0 auto;

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

        .title {
            display: flex;
            align-items: center;
            font-size: 24px;
            font-weight: 600;
            color: #0A2463;
            margin: 0;

            .title-icon {
                margin-right: 8px;
                font-size: 28px;
            }
        }

        .el-button {
            background-color: #0A2463;
            border-color: #0A2463;

            &:hover {
                background-color: #083354;
                border-color: #083354;
            }
        }
    }

    .tabs-container {
        margin-bottom: 24px;

        :deep(.el-tabs__header) {
            margin: 0;
        }

        :deep(.el-tabs__nav-wrap::after) {
            display: none;
        }

        :deep(.el-tabs__item) {
            font-size: 16px;
            font-weight: 500;
            padding: 0 20px;
        }

        :deep(.el-tabs__item.is-active) {
            color: #0A2463;
            font-weight: 600;
        }

        :deep(.el-tabs__active-bar) {
            background-color: #0A2463;
        }
    }

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

        .section-title {
            font-size: 16px;
            font-weight: 600;
            color: #303133;
            margin-bottom: 16px;
            padding-left: 8px;
            border-left: 4px solid #0A2463;
        }

        &.history-section {
            margin-top: 32px;
            padding-top: 24px;
            border-top: 1px solid #f0f0f0;
        }
    }

    .messages-list {
        .message-item {
            background: #fff;
            border: 1px solid #ebeef5;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 16px;
            transition: box-shadow 0.3s ease;

            &:hover {
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            }

            .user-info {
                display: flex;
                align-items: center;
                margin-bottom: 12px;

                .user-details {
                    margin-left: 12px;

                    .user-name {
                        font-size: 16px;
                        font-weight: 600;
                        color: #303133;
                        margin-bottom: 4px;
                    }

                    .source-info {
                        font-size: 14px;
                        color: #909399;

                        .time {
                            margin-left: 8px;
                        }
                    }
                }
            }

            .comment-content {
                color: #606266;
                line-height: 1.6;
                margin-bottom: 16px;
                font-size: 15px;
            }

            .action-buttons {
                text-align: right;

                .reply-btn {
                    color: #0A2463;
                    font-size: 14px;

                    &:hover {
                        color: #083354;
                    }
                }
            }

            .reply-section {
                margin-top: 16px;
                padding-top: 16px;
                border-top: 1px solid #f0f0f0;

                .reply-input {
                    margin-bottom: 12px;
                }

                .reply-actions {
                    text-align: right;

                    .el-button + .el-button {
                        margin-left: 8px;
                    }

                    .el-button--primary {
                        background-color: #0A2463;
                        border-color: #0A2463;

                        &:hover {
                            background-color: #083354;
                            border-color: #083354;
                        }
                    }
                }
            }

            .existing-replies {
                margin-top: 16px;

                .replies-title {
                    font-size: 14px;
                    font-weight: 600;
                    color: #0A2463;
                    margin-bottom: 12px;
                }

                .existing-reply {
                    padding: 12px;
                    background: #f8f9fa;
                    border-left: 4px solid #0A2463;
                    border-radius: 0 4px 4px 0;
                    margin-bottom: 8px;

                    &:last-child {
                        margin-bottom: 0;
                    }

                    .reply-user {
                        display: flex;
                        align-items: center;
                        margin-bottom: 8px;

                        .reply-username {
                            font-size: 14px;
                            font-weight: 600;
                            color: #303133;
                            margin-left: 8px;
                        }

                        .reply-time {
                            font-size: 12px;
                            color: #909399;
                            margin-left: 8px;
                        }
                    }

                    .reply-content {
                        color: #606266;
                        font-size: 14px;
                        line-height: 1.6;
                    }
                }
            }
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #909399;

            .empty-icon {
                font-size: 64px;
                margin-bottom: 16px;
                color: #dcdfe6;
            }

            p {
                font-size: 16px;
                margin: 0;
            }
        }
    }

    .pagination {
        display: flex;
        justify-content: center;
        margin-top: 32px;
    }
}

// 响应式设计
@media (max-width: 768px) {
    .messages {
        padding: 16px;

        .header {
            flex-direction: column;
            align-items: flex-start;
            gap: 12px;

            .title {
                font-size: 20px;
            }
        }

        .messages-list {
            .message-item {
                padding: 16px;

                .user-info {
                    .user-details {
                        .user-name {
                            font-size: 15px;
                        }

                        .source-info {
                            font-size: 13px;
                        }
                    }
                }

                .comment-content {
                    font-size: 14px;
                }
            }
        }
    }
}
</style> 