<template>
    <div class="chat-room-container">
        <!-- 聊天室列表侧边栏 -->
        <aside class="room-list-sidebar">
            <!-- 头部 -->
            <div class="sidebar-header">
                <span class="title">聊天室</span>
            </div>

            <!-- 搜索框 -->
            <div class="search-box">
                <ElInput
                    v-model="searchText"
                    placeholder="搜索工单号、来客姓名、电话..."
                    :prefix-icon="Search"
                    clearable
                />
            </div>

            <!-- chatRoom列表 -->
            <div class="room-list-container">
                <div v-if="filteredRooms.length === 0" class="empty-tip">
                    暂无聊天室
                </div>
                <div
                    v-for="room in filteredRooms"
                    :key="room.roomId"
                    class="room-item"
                    :class="{ active: currentRoomId === room.roomId }"
                    @click="selectRoom(room.roomId!)"
                >
                    <!-- 头像 -->
                    <div class="room-avatar">
                        {{ room.guestName?.substring(0, 1) || '?' }}
                    </div>

                    <!-- 信息 -->
                    <div class="room-info">
                        <div class="room-header">
                            <div class="room-name">{{ room.roomName }}</div>
                            <div class="room-time">{{ formatTime(room.lastMessageTime) }}</div>
                        </div>
                        <div class="last-message">{{ room.lastMessage || '暂无消息' }}</div>
                    </div>

                    <!-- 未读红点 -->
                    <div v-if="(room.unreadCount ?? 0) > 0" class="unread-badge">
                        {{ (room.unreadCount ?? 0) > 99 ? '99+' : room.unreadCount }}
                    </div>
                </div>
            </div>
        </aside>

        <!-- 主聊天区域 -->
        <main class="chat-main">
            <template v-if="currentRoomId">
                <ChatRoom
                    :messages="messages"
                    :current-user-id="userId"
                    :room-name="currentRoom?.roomName"
                    :meeting-url="currentMeetingUrl"
                    :show-meeting="showMeetingIframe"
                    :file-download-url="FILE_DOWNLOAD_URL"
                    @send-message="handleSendMessage"
                    @start-meeting="startMeeting"
                    @download-file="downloadFile"
                >
                    <template #header>
                        <div class="chat-room-header">
                            <div class="header-left">
                                <div class="room-avatar-small">
                                    {{ currentRoom?.guestName?.substring(0, 1) }}
                                </div>
                                <div class="room-title-group">
                                    <div class="room-name-text">{{ currentRoom?.roomName }}</div>
                                    <div class="room-subtitle">
                                        工单 #{{ currentRoom?.workcaseId }} · {{ currentRoom?.guestName }}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </template>

                    <template #action-area>
                        <ElButton type="primary" @click="showWorkcaseDetail = true">
                            <FileText :size="16" />
                            查看工单
                        </ElButton>
                    </template>
                </ChatRoom>
            </template>

            <!-- 空状态 -->
            <div v-else class="empty-state">
                <div class="empty-content">
                    <div class="empty-icon">
                        <MessageSquare :size="40" />
                    </div>
                    <h3 class="empty-title">选择一个聊天室开始对话</h3>
                    <p class="empty-desc">从左侧列表中选择一个聊天室查看消息</p>
                </div>
            </div>
        </main>

        <!-- 工单详情对话框 -->
        <ElDialog
            v-model="showWorkcaseDetail"
            title="工单详情"
            width="800px"
            class="workcase-dialog"
        >
            <WorkcaseDetail :workcase-id="currentWorkcaseId" />
        </ElDialog>
    </div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { ElButton, ElInput, ElDialog, ElMessage } from 'element-plus'
import { Search, FileText, MessageSquare } from 'lucide-vue-next'
import { ChatRoom } from '@/components/chatRoom'
import WorkcaseDetail from '@/views/public/workcase/WorkcaseDetail/WorkcaseDetail.vue'
import { workcaseChatAPI } from '@/api/workcase'
import { fileAPI } from 'shared/api/file'
import { FILE_DOWNLOAD_URL } from '@/config'
import type { ChatRoomVO, ChatRoomMessageVO, TbChatRoomMessageDTO } from '@/types/workcase'
import SockJS from 'sockjs-client'
import { Client } from '@stomp/stompjs'

// WebSocket配置 (通过Nginx代理访问网关，再到workcase服务)
// SockJS URL (http://)
const getWsUrl = () => {
    const token = localStorage.getItem('token') || ''
    const protocol = window.location.protocol
    const host = window.location.host
    return `${protocol}//${host}/api/urban-lifeline/workcase/ws/chat-sockjs?token=${encodeURIComponent(token)}`
}

// STOMP客户端
let stompClient: any = null
let roomSubscription: any = null
let listSubscription: any = null

// 当前用户ID（从登录状态获取）
const userId = ref(localStorage.getItem('userId') || '')

// 搜索文本
const searchText = ref('')

// 加载状态
const loading = ref(false)
const messageLoading = ref(false)

// 聊天室列表
const chatRooms = ref<ChatRoomVO[]>([])

// 当前选中的聊天室ID
const currentRoomId = ref<string | null>(null)

// 当前聊天室
const currentRoom = computed(() => 
    chatRooms.value.find((r: ChatRoomVO) => r.roomId === currentRoomId.value)
)

// 当前工单ID
const currentWorkcaseId = computed(() => currentRoom.value?.workcaseId || '')

// 过滤后的聊天室列表
const filteredRooms = computed(() => {
    if (!searchText.value) return chatRooms.value
    const keyword = searchText.value.toLowerCase()
    return chatRooms.value.filter((room: ChatRoomVO) => 
        room.roomName?.toLowerCase().includes(keyword) ||
        room.guestName?.toLowerCase().includes(keyword) ||
        room.workcaseId?.toLowerCase().includes(keyword)
    )
})

// 消息列表
const messages = ref<ChatRoomMessageVO[]>([])

// 工单详情对话框
const showWorkcaseDetail = ref(false)

// Jitsi Meet会议相关
const currentMeetingUrl = ref('')
const showMeetingIframe = ref(false)

// 获取聊天室列表
const fetchChatRooms = async () => {
    loading.value = true
    try {
        const result = await workcaseChatAPI.getChatRoomPage({
            filter: { status: 'active' },
            pageParam: { page: 1, pageSize: 100, total: 0 }
        })
        if (result.success && result.pageDomain) {
            chatRooms.value = result.pageDomain.dataList || []
        }
    } catch (error) {
        console.error('获取聊天室列表失败:', error)
        ElMessage.error('获取聊天室列表失败')
    } finally {
        loading.value = false
    }
}

// 选择聊天室
const selectRoom = (roomId: string) => {
    currentRoomId.value = roomId
    loadMessages(roomId)
}

// 加载消息
const loadMessages = async (roomId: string) => {
    messageLoading.value = true
    try {
        const result = await workcaseChatAPI.getChatMessagePage({
            filter: { roomId },
            pageParam: { page: 1, pageSize: 100, total: 0 }
        })
        if (result.success && result.pageDomain) {
            messages.value = result.pageDomain.dataList || []
        }
        scrollToBottom()
    } catch (error) {
        console.error('加载消息失败:', error)
        ElMessage.error('加载消息失败')
    } finally {
        messageLoading.value = false
    }
}

// 处理发送消息（从ChatRoom组件触发）
const handleSendMessage = async (content: string, files: File[]) => {
    if (!currentRoomId.value) return
    
    try {
        // 上传文件获取fileIds
        let fileIds: string[] = []
        if (files.length > 0) {
            const uploadResult = await fileAPI.batchUpload(files, 'chatroom')
            if (uploadResult.success && uploadResult.dataList) {
                fileIds = uploadResult.dataList.map((f: any) => f.fileId)
            }
        }
        
        // 构造消息
        const messageData: TbChatRoomMessageDTO = {
            roomId: currentRoomId.value,
            senderId: userId.value,
            senderType: 'agent',
            content,
            files: fileIds,
            messageType: 'text'
        }
        
        // 发送消息
        const result = await workcaseChatAPI.sendMessage(messageData)
        if (result.success && result.data) {
            // 添加到消息列表
            messages.value.push(result.data as ChatRoomMessageVO)
            scrollToBottom()
        } else {
            ElMessage.error(result.message || '发送失败')
        }
    } catch (error) {
        console.error('发送消息失败:', error)
        ElMessage.error('发送消息失败')
    }
}

// 下载文件
const downloadFile = (fileId: string) => {
    window.open(`${FILE_DOWNLOAD_URL}/${fileId}`, '_blank')
}

// 发起会议
const startMeeting = async () => {
    if (!currentRoomId.value) return
    
    // TODO: 调用后端API创建Jitsi会议
    const meetingId = 'meeting-' + currentRoomId.value + '-' + Date.now()
    currentMeetingUrl.value = `https://meet.jit.si/${meetingId}`
    showMeetingIframe.value = true
}

// 滚动到底部
const scrollToBottom = () => {
    // TODO: 滚动到ChatRoom组件底部
}

// 格式化时间（用于聊天室列表）
const formatTime = (time: string | null | undefined) => {
    if (!time) return ''
    const date = new Date(time)
    const now = new Date()
    const diff = now.getTime() - date.getTime()
    
    if (diff < 60000) return '刚刚'
    if (diff < 3600000) return Math.floor(diff / 60000) + '分钟前'
    if (diff < 86400000) return Math.floor(diff / 3600000) + '小时前'
    
    return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' })
}

// ==================== WebSocket连接管理 ====================

// 初始化WebSocket连接（支持SockJS降级）
const initWebSocket = () => {
    const token = localStorage.getItem('token') || ''
    const wsUrl = getWsUrl()
    
    console.log('WebSocket连接URL:', wsUrl)
    
    // 创建STOMP客户端，使用SockJS（支持降级）
    stompClient = new Client({
        webSocketFactory: () => new SockJS(wsUrl),
        connectHeaders: {
            Authorization: `Bearer ${token}`
        },
        reconnectDelay: 5000,
        heartbeatIncoming: 4000,
        heartbeatOutgoing: 4000,
        debug: (str: string) => {
            console.log('[STOMP]', str)
        },
        onConnect: () => {
            console.log('WebSocket已连接')
            // 订阅聊天室列表更新
            subscribeToListUpdate()
            // 如果当前有选中的聊天室，订阅该聊天室消息
            if (currentRoomId.value) {
                subscribeToRoom(currentRoomId.value)
            }
        },
        onDisconnect: () => {
            console.log('WebSocket已断开')
        },
        onStompError: (frame: any) => {
            console.error('STOMP错误:', frame)
        },
        onWebSocketError: (event: any) => {
            console.error('WebSocket错误:', event)
        }
    })

    stompClient.activate()
}

// 订阅聊天室列表更新 (用于更新列表中的lastMessage)
const subscribeToListUpdate = () => {
    if (!stompClient || !stompClient.connected) return

    listSubscription = stompClient.subscribe('/topic/chat/list-update', (message: any) => {
        const chatMessage = JSON.parse(message.body)
        // 更新对应聊天室的lastMessage和lastMessageTime
        const roomIndex = chatRooms.value.findIndex((r: ChatRoomVO) => r.roomId === chatMessage.roomId)
        if (roomIndex !== -1) {
            chatRooms.value[roomIndex] = {
                ...chatRooms.value[roomIndex],
                lastMessage: chatMessage.content,
                lastMessageTime: chatMessage.sendTime
            }
        }
    })
}

// 订阅指定聊天室消息 (用于实时接收消息)
const subscribeToRoom = (roomId: string) => {
    if (!stompClient || !stompClient.connected) return

    // 先取消之前的订阅
    if (roomSubscription) {
        roomSubscription.unsubscribe()
        roomSubscription = null
    }

    roomSubscription = stompClient.subscribe(`/topic/chat/${roomId}`, (message: any) => {
        const chatMessage = JSON.parse(message.body) as ChatRoomMessageVO
        // 避免重复添加自己发送的消息
        if (chatMessage.senderId !== userId.value) {
            messages.value.push(chatMessage)
            scrollToBottom()
        }
    })
}

// 断开WebSocket连接
const disconnectWebSocket = () => {
    if (roomSubscription) {
        roomSubscription.unsubscribe()
        roomSubscription = null
    }
    if (listSubscription) {
        listSubscription.unsubscribe()
        listSubscription = null
    }
    if (stompClient) {
        stompClient.deactivate()
        stompClient = null
    }
}

// 监听currentRoomId变化，切换聊天室时重新订阅
watch(currentRoomId, (newRoomId) => {
    if (newRoomId && stompClient?.connected) {
        subscribeToRoom(newRoomId)
    }
})

// 初始化
onMounted(() => {
    fetchChatRooms()
    initWebSocket()
})

// 组件卸载时断开连接
onUnmounted(() => {
    disconnectWebSocket()
})
</script>
<style scoped lang="scss">
@import url("./ChatRoomView.scss");
</style>