<template>
    <div class="chat-message-container">
        <!-- 头部信息 -->
        <header class="chat-header">
            <div class="header-content">
                <div class="header-title">{{ chatRoom?.workcaseId || '' }} 对话详情</div>
                <div class="header-subtitle">
                    <span>客户：{{ chatRoom?.guestName || '未知' }}</span>
                    <span class="separator">　</span>
                    <span>聊天室：{{ chatRoom?.roomName || '未知' }}</span>
                </div>
            </div>
        </header>

        <!-- Tab 切换 -->
        <div class="tabs-container">
            <div class="tabs-wrapper">
                <button 
                    class="tab-button"
                    :class="{ active: activeTab === 'record' }"
                    @click="activeTab = 'record'"
                >
                    对话记录
                </button>
                <button 
                    class="tab-button"
                    :class="{ active: activeTab === 'summary' }"
                    @click="activeTab = 'summary'"
                >
                    对话纪要
                </button>
            </div>
        </div>

        <!-- 内容区域 -->
        <main class="chat-main">
            <!-- 对话记录 -->
            <div v-if="activeTab === 'record'" class="messages-container" ref="messagesContainerRef" @scroll="handleScroll">
                <!-- 加载更多提示 -->
                <div v-if="loadingMore" class="loading-more">
                    <span>加载中...</span>
                </div>
                <div v-else-if="!hasMore && messages.length > 0" class="no-more">
                    <span>没有更多消息了</span>
                </div>

                <div class="messages-list">
                    <div v-for="message in messages" :key="message.messageId" 
                         class="message-item"
                         :class="message.senderType === 'guest' ? 'message-right' : 'message-left'"
                    >
                        <!-- 客服/AI消息（左侧） -->
                        <template v-if="message.senderType !== 'guest'">
                            <div class="avatar avatar-ai">{{ getAvatarText(message) }}</div>
                            <div class="message-content">
                                <div class="message-meta">{{ message.senderName || '小电' }} {{ formatTime(message.sendTime) }}</div>
                                <div class="message-bubble message-bubble-left">
                                    {{ message.content }}
                                </div>
                            </div>
                        </template>

                        <!-- 客户消息（右侧） -->
                        <template v-else>
                            <div class="message-content">
                                <div class="message-meta message-meta-right">{{ message.senderName || '客户' }} {{ formatTime(message.sendTime) }}</div>
                                <div class="message-bubble message-bubble-right">
                                    {{ message.content }}
                                </div>
                            </div>
                            <div class="avatar avatar-guest">{{ getAvatarText(message) }}</div>
                        </template>
                    </div>

                    <!-- 空状态 -->
                    <div v-if="messages.length === 0 && !loading" class="empty-state">
                        <div class="empty-text">暂无对话记录</div>
                    </div>
                </div>
            </div>

            <!-- 对话纪要 -->
            <div v-else class="summary-container">
                <!-- 加载状态 -->
                <div v-if="loadingSummary" class="summary-loading">
                    <div class="loading-spinner"></div>
                    <span>正在生成对话总结...</span>
                </div>

                <!-- 总结内容 -->
                <div v-else-if="summaryData" class="summary-content">
                    <div class="summary-header">
                        <h3>对话总结</h3>
                        <button class="regenerate-btn" @click="generateSummary">重新生成</button>
                    </div>

                    <div v-if="summaryData.question" class="summary-section">
                        <div class="summary-title">核心问题</div>
                        <div class="summary-text">
                            {{ summaryData.question }}
                        </div>
                    </div>

                    <div v-if="summaryData.needs && summaryData.needs.length > 0" class="summary-section">
                        <div class="summary-title">核心诉求</div>
                        <ul class="summary-list">
                            <li v-for="(need, index) in summaryData.needs" :key="index">{{ need }}</li>
                        </ul>
                    </div>

                    <div v-if="summaryData.answer" class="summary-section">
                        <div class="summary-title">解决方案</div>
                        <div class="summary-text">
                            {{ summaryData.answer }}
                        </div>
                    </div>

                    <div class="summary-meta">
                        <span v-if="summaryData.messageCount">
                            基于 {{ summaryData.messageCount }} 条消息生成
                        </span>
                        <span v-if="summaryData.summaryTime">
                            生成时间：{{ summaryData.summaryTime }}
                        </span>
                    </div>
                </div>

                <!-- 空状态 -->
                <div v-else class="summary-empty">
                    <div class="empty-icon">📝</div>
                    <div class="empty-text">暂无对话总结</div>
                    <button class="generate-btn" @click="generateSummary">生成总结</button>
                </div>
            </div>
        </main>
    </div>
</template>
<script setup lang="ts">
import { ref, onMounted, watch, computed, nextTick } from 'vue'
import type { ChatRoomVO, ChatRoomMessageVO, ChatRoomSummaryResponse } from '@/types/workcase/chatRoom'
import { workcaseChatAPI } from '@/api/workcase/workcaseChat'
import { ElMessage } from 'element-plus'

interface Props {
    chatRoom?: ChatRoomVO
    roomId?: string
}

const props = withDefaults(defineProps<Props>(), {
    chatRoom: undefined,
    roomId: ''
})

const activeTab = ref<'record' | 'summary'>('record')
const messages = ref<ChatRoomMessageVO[]>([])
const loading = ref(false)
const loadingMore = ref(false)
const summaryData = ref<ChatRoomSummaryResponse | null>(null)
const loadingSummary = ref(false)

// 分页相关
const currentPage = ref(1)
const pageSize = 20
const total = ref(0)
const hasMore = computed(() => messages.value.length < total.value)

// 滚动容器引用
const messagesContainerRef = ref<HTMLElement | null>(null)

// 计算目标 roomId
const targetRoomId = computed(() => props.roomId || props.chatRoom?.roomId || '')

// 格式化时间
const formatTime = (timeStr?: string) => {
    if (!timeStr) return ''
    try {
        const date = new Date(timeStr)
        return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' })
    } catch {
        return timeStr
    }
}

// 获取头像文本
const getAvatarText = (message: ChatRoomMessageVO) => {
    if (message.senderType === 'guest') {
        return message.senderName?.charAt(0) || '客'
    }
    return message.senderName?.charAt(0) || '电'
}

// 加载消息数据（首次加载，获取最新消息）
const loadMessages = async () => {
    if (!targetRoomId.value) return

    loading.value = true
    currentPage.value = 1
    try {
        const res = await workcaseChatAPI.getChatMessagePage({
            filter: { roomId: targetRoomId.value },
            pageParam: { page: 1, pageSize }
        })
        
        if (res.success && res.dataList) {
            // 后端降序返回（最新在前），需要反转显示（最新在下）
            messages.value = [...res.dataList].reverse()
            total.value = res.total || 0
            
            // 滚动到底部
            await nextTick()
            scrollToBottom()
        }
    } catch (error) {
        console.error('加载消息失败:', error)
    } finally {
        loading.value = false
    }
}

// 加载更多历史消息（滚动到顶部时触发）
const loadMoreMessages = async () => {
    if (!targetRoomId.value || loadingMore.value || !hasMore.value) return

    loadingMore.value = true
    const container = messagesContainerRef.value
    const oldScrollHeight = container?.scrollHeight || 0
    
    try {
        currentPage.value++
        const res = await workcaseChatAPI.getChatMessagePage({
            filter: { roomId: targetRoomId.value },
            pageParam: { page: currentPage.value, pageSize }
        })
        
        if (res.success && res.dataList && res.dataList.length > 0) {
            // 后端降序返回，反转后插入到消息列表前面
            const olderMessages = [...res.dataList].reverse()
            messages.value = [...olderMessages, ...messages.value]
            
            // 保持滚动位置（新内容加载后保持原来的可视区域）
            await nextTick()
            if (container) {
                const newScrollHeight = container.scrollHeight
                container.scrollTop = newScrollHeight - oldScrollHeight
            }
        }
    } catch (error) {
        console.error('加载更多消息失败:', error)
        currentPage.value-- // 回退页码
    } finally {
        loadingMore.value = false
    }
}

// 滚动到底部
const scrollToBottom = () => {
    const container = messagesContainerRef.value
    if (container) {
        container.scrollTop = container.scrollHeight
    }
}

// 处理滚动事件
const handleScroll = () => {
    const container = messagesContainerRef.value
    if (!container) return
    
    // 滚动到顶部附近时加载更多（距离顶部50px以内）
    if (container.scrollTop < 50 && hasMore.value && !loadingMore.value) {
        loadMoreMessages()
    }
}

// 查询最新的对话总结
const loadLatestSummary = async () => {
    if (!targetRoomId.value) {
        return
    }

    loadingSummary.value = true
    summaryData.value = null

    try {
        const res = await workcaseChatAPI.getLatestSummary(targetRoomId.value)

        if (res.success && res.data) {
            summaryData.value = res.data
        } else {
            // 查询失败，表示还没有总结
            summaryData.value = null
        }
    } catch (error) {
        console.error('查询总结失败:', error)
        summaryData.value = null
    } finally {
        loadingSummary.value = false
    }
}

// 生成对话纪要（调用后端AI接口）
const generateSummary = async () => {
    if (!targetRoomId.value) {
        ElMessage.warning('无效的聊天室ID')
        return
    }

    loadingSummary.value = true
    summaryData.value = null

    try {
        const res = await workcaseChatAPI.summaryChatRoom({
            roomId: targetRoomId.value,
            includeSystemMessages: false,
            includeMeetingMessages: false
        })

        if (res.success && res.data) {
            summaryData.value = res.data
            ElMessage.success('总结生成成功')
        } else {
            ElMessage.error(res.message || '生成总结失败')
        }
    } catch (error) {
        console.error('生成总结失败:', error)
        ElMessage.error('生成总结失败')
    } finally {
        loadingSummary.value = false
    }
}

onMounted(async () => {
    await loadMessages()
})

// 监听 roomId 变化，重新加载数据
watch(targetRoomId, async (newVal) => {
    if (newVal) {
        messages.value = []
        summaryData.value = null
        currentPage.value = 1
        total.value = 0
        await loadMessages()
    }
})

// 监听切换到对话纪要标签，自动查询总结
watch(activeTab, async (newVal) => {
    if (newVal === 'summary' && !summaryData.value && !loadingSummary.value) {
        await loadLatestSummary()
    }
})
</script>
<style scoped lang="scss">
@import url("./ChatMessage.scss");

.loading-more,
.no-more {
    text-align: center;
    padding: 12px;
    color: #909399;
    font-size: 12px;
}

.loading-more span {
    display: inline-block;
    animation: pulse 1.5s ease-in-out infinite;
}

@keyframes pulse {
    0%, 100% { opacity: 0.5; }
    50% { opacity: 1; }
}
</style>