<template>
	<!-- #ifdef APP -->
	<scroll-view style="flex:1">
	<!-- #endif -->
	<view class="page">
		<!-- 自定义导航栏 -->
		<view class="nav" :style="{ paddingTop: navPaddingTop + 'px', height: navHeight + 'px' }">
			<view class="nav-back" @tap="goBack">
				<view class="nav-back-icon"></view>
			</view>
			<text class="nav-title">我的聊天室</text>
			<view class="nav-capsule"></view>
		</view>

		<!-- 聊天室列表 -->
		<scroll-view class="list" scroll-y="true" :style="{ marginTop: navHeight + 'px' }">
			<view class="room-card" v-for="(room, index) in chatRooms" :key="index" @tap="enterRoom(room)">
				<view class="room-avatar">
					<text class="avatar-text">{{ room.guestName?.charAt(0) || '客' }}</text>
				</view>
				<view class="room-info">
					<view class="room-header">
						<text class="room-name">{{ room.roomName || '聊天室' }}</text>
						<text class="room-time">{{ formatTime(room.lastMessageTime) }}</text>
					</view>
					<view class="room-footer">
						<text class="last-message">{{ getPlainTextPreview(room.lastMessage) }}</text>
						<view class="unread-badge" v-if="room.unreadCount && room.unreadCount > 0">
							<text class="badge-text">{{ room.unreadCount > 99 ? '99+' : room.unreadCount }}</text>
						</view>
					</view>
				</view>
				<view class="room-status" :class="getStatusClass(room.status)">
					<text class="status-dot"></text>
					<text class="status-text">{{ getStatusText(room.status) }}</text>
				</view>
			</view>

			<!-- 空状态 -->
			<view class="empty-state" v-if="chatRooms.length === 0">
				<text class="empty-icon">💬</text>
				<text class="empty-text">暂无聊天室</text>
				<text class="empty-hint">点击"联系人工"创建新聊天室</text>
			</view>
		</scroll-view>
	</view>
	<!-- #ifdef APP -->
	</scroll-view>
	<!-- #endif -->
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { workcaseChatAPI } from '@/api'
import type { ChatRoomVO, TbChatRoomDTO, PageRequest, ChatRoomMessageVO } from '@/types'
import { wsClient } from '@/utils/websocket'
import { WS_HOST } from '@/config'

// 导航栏
const navPaddingTop = ref<number>(0)
const navHeight = ref<number>(44)
const capsuleHeight = ref<number>(32)

// 加载状态
const loading = ref<boolean>(false)

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

// 生命周期
onMounted(() => {
	const windowInfo = uni.getWindowInfo()
	const statusBarHeight = windowInfo.statusBarHeight || 20
	
	// #ifdef MP-WEIXIN
	try {
		const menuButton = uni.getMenuButtonBoundingClientRect()
		navPaddingTop.value = menuButton.top
		capsuleHeight.value = menuButton.height
		navHeight.value = menuButton.bottom + 8
	} catch (e) {
		navPaddingTop.value = statusBarHeight
		navHeight.value = navPaddingTop.value + 44
	}
	// #endif
	// #ifndef MP-WEIXIN
	navPaddingTop.value = statusBarHeight
	navHeight.value = navPaddingTop.value + 44
	// #endif
	
	loadChatRooms()
	initWebSocket()
})

// 组件卸载时断开WebSocket
onUnmounted(() => {
	disconnectWebSocket()
})

// 加载聊天室列表
async function loadChatRooms() {
	loading.value = true
	try {
		// 获取当前用户ID
		const userId = uni.getStorageSync('userId') || ''
		
		const pageRequest: PageRequest<TbChatRoomDTO> = {
			filter: {
				guestId: userId // 查询当前用户的聊天室
			},
			pageParam: {
				pageNumber: 1,
				pageSize: 50
			}
		}
		
		const res = await workcaseChatAPI.getChatRoomPage(pageRequest)
		if (res.success && res.pageDomain?.dataList) {
			chatRooms.value = res.pageDomain.dataList
		}
	} catch (error) {
		console.error('加载聊天室列表失败:', error)
		uni.showToast({
			title: '加载失败',
			icon: 'none'
		})
	} finally {
		loading.value = false
	}
}

// 格式化时间（兼容 iOS）
function formatTime(time?: string): string {
	if (!time) return ''
	// iOS 不支持 "yyyy-MM-dd HH:mm:ss" 格式，需要转换为 "yyyy-MM-ddTHH:mm:ss"
	const iosCompatibleTime = time.replace(' ', 'T')
	const date = new Date(iosCompatibleTime)
	if (isNaN(date.getTime())) return ''

	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) + '小时前'
	if (diff < 172800000) return '昨天'

	return `${date.getMonth() + 1}/${date.getDate()}`
}

// 去除markdown语法并截取前10个字符
function getPlainTextPreview(text?: string): string {
	if (!text) return '暂无消息'

	// 去除markdown语法
	let plainText = text
		// 去除代码块
		.replace(/```[\s\S]*?```/g, '[代码]')
		// 去除行内代码
		.replace(/`([^`]+)`/g, '$1')
		// 去除粗体
		.replace(/\*\*([^\*]+)\*\*/g, '$1')
		// 去除斜体
		.replace(/\*([^\*]+)\*/g, '$1')
		// 去除链接
		.replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
		// 去除标题标记
		.replace(/^#{1,6}\s+/gm, '')
		// 去除列表标记
		.replace(/^[*-]\s+/gm, '')
		// 去除多余的空白字符
		.replace(/\s+/g, ' ')
		.trim()

	// 截取前10个字符
	if (plainText.length > 10) {
		return plainText.substring(0, 10) + '...'
	}

	return plainText
}

// 获取状态样式类
function getStatusClass(status?: string): string {
	switch (status) {
		case 'active': return 'status-active'
		case 'waiting': return 'status-waiting'
		case 'closed': return 'status-closed'
		default: return 'status-waiting'
	}
}

// 获取状态文本
function getStatusText(status?: string): string {
	switch (status) {
		case 'active': return '进行中'
		case 'waiting': return '等待中'
		case 'closed': return '已关闭'
		default: return '未知'
	}
}

// 进入聊天室
function enterRoom(room: ChatRoomVO) {
	room.unreadCount = 0
	uni.navigateTo({
		url: `/pages/chatRoom/chatRoom/chatRoom?roomId=${room.roomId}&workcaseId=${room.workcaseId || ''}`
	})
}

// 返回上一页
function goBack() {
	uni.navigateBack()
}

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

// 初始化WebSocket连接
async function initWebSocket() {
	try {
		const token = uni.getStorageSync('token') || ''
		if (!token) {
			console.warn('[chatRoomList] 未找到token，跳过WebSocket连接')
			return
		}
		
		// 构建WebSocket URL
		// 开发环境：ws://localhost:8180 或 ws://192.168.x.x:8180
		// 生产环境：wss://your-domain.com
		const protocol = 'ws:' // 开发环境使用ws，生产环境改为wss
		// 小程序使用原生WebSocket端点（不是SockJS端点）
		const wsUrl = `${protocol}//${WS_HOST}/urban-lifeline/workcase/ws/chat?token=${encodeURIComponent(token)}`
		
		console.log('[chatRoomList] 开始连接WebSocket')
		await wsClient.connect(wsUrl, token)
		
		// 订阅聊天室列表更新频道
		wsClient.subscribe('/topic/chat/list-update', handleListUpdate)
		console.log('[chatRoomList] WebSocket连接成功，已订阅列表更新频道')
	} catch (error) {
		console.error('[chatRoomList] WebSocket连接失败:', error)
	}
}

// 断开WebSocket连接
function disconnectWebSocket() {
	try {
		wsClient.disconnect()
		console.log('[chatRoomList] WebSocket已断开')
	} catch (error) {
		console.error('[chatRoomList] 断开WebSocket失败:', error)
	}
}

// 处理列表更新消息
async function handleListUpdate(message: ChatRoomMessageVO) {
	console.log('[chatRoomList] 收到列表更新消息:', message)
	
	// 更新对应聊天室的lastMessage和lastMessageTime
	const roomIndex = chatRooms.value.findIndex((r: ChatRoomVO) => r.roomId === message.roomId)
	if (roomIndex !== -1) {
		// 查询当前用户在该聊天室的未读数
		let unreadCount = 0
		try {
			const userInfo = uni.getStorageSync('userInfo')
			const userId = typeof userInfo === 'string' ? JSON.parse(userInfo).userId : userInfo?.userId
			if (userId) {
				const unreadResult = await workcaseChatAPI.getUnreadCount(message.roomId, userId)
				if (unreadResult.success && unreadResult.data !== undefined) {
					unreadCount = unreadResult.data
				}
			}
		} catch (error) {
			console.error('[chatRoomList] 查询未读数失败:', error)
		}
		
		chatRooms.value[roomIndex] = {
			...chatRooms.value[roomIndex],
			lastMessage: message.content || '',
			lastMessageTime: message.sendTime || '',
			unreadCount: unreadCount
		}
		
		// 将更新的聊天室移到列表顶部
		const updatedRoom = chatRooms.value[roomIndex]
		chatRooms.value.splice(roomIndex, 1)
		chatRooms.value.unshift(updatedRoom)
	}
}
</script>

<style lang="scss" scoped>
@import "./chatRoomList.scss";
</style>