<template>
  <div class="message-layout">
    <!-- 左侧：会话列表 -->
    <div class="sidebar">
      <div class="search-bar">
        <el-input 
          v-model="searchText" 
          placeholder="搜索联系人..." 
          prefix-icon="Search" 
          clearable
        />
        <el-button icon="Plus" circle class="add-btn" @click="showUserSelector = true" />
      </div>

      <div class="conversation-toolbar">
        <el-button
          type="primary"
          link
          :loading="markingAllRead"
          :disabled="conversations.length === 0"
          @click="markAllRead"
        >
          全部已读
        </el-button>
      </div>

      <div class="conversation-list" v-loading="loadingConversations">
        <div 
          v-for="chat in filteredConversations" 
          :key="chat.user_id"
          class="chat-item"
          :class="{ active: currentChatId === chat.user_id }"
          @click="selectChat(chat)"
        >
          <PlatformIcon
            v-if="hasSystemAppLogo(chat)"
            class="msg-conv-avatar"
            :text="chat.app_name || chat.full_name || chat.username || '应用'"
            :size="40"
            shape="circle"
            :icon-url="chat.icon_url"
            :app-id="chat.application_app_id"
            :icon-object-key="chat.icon_object_key"
            :show-caption="false"
          />
          <UserAvatar
            v-else
            :name="chat.full_name || chat.username || '未知'"
            :userId="chat.user_id"
            :size="40"
          />
          
          <div class="chat-info">
            <div class="chat-header">
              <span class="chat-name">
                <template v-if="chat.is_system">
                  {{ chat.app_name || chat.full_name || chat.username }}
                </template>
                <template v-else>
                  {{ chat.full_name || chat.username }}
                </template>
              </span>
              <span class="chat-time">{{ formatTime(chat.updated_at) }}</span>
            </div>
            <div v-if="chat.remarks" class="chat-remarks">{{ chat.remarks }}</div>
            <div class="chat-preview">
              {{ chat.last_message }}
            </div>
          </div>
          
          <div v-if="(chat.unread_count || 0) > 0" class="unread-badge">
            {{ (chat.unread_count || 0) > 99 ? '99+' : chat.unread_count }}
          </div>
        </div>
        
        <el-empty v-if="conversations.length === 0 && !loadingConversations" description="暂无消息" :image-size="60" />
      </div>
    </div>

    <!-- 右侧：聊天窗口 -->
    <div class="chat-window">
      <template v-if="currentChatId !== null">
        <!-- 顶部标题 -->
        <header class="chat-header-bar">
          <PlatformIcon
            v-if="hasSystemAppLogo(currentChatUser)"
            class="chat-header-app-icon"
            :text="currentChatUser.app_name || currentChatUser.full_name || '应用'"
            :size="36"
            shape="circle"
            :icon-url="currentChatUser.icon_url"
            :app-id="currentChatUser.application_app_id"
            :icon-object-key="currentChatUser.icon_object_key"
            :show-caption="false"
          />
          <div class="chat-header-titles">
            <h3>
              <!-- 系统会话优先显示应用名 -->
              <template v-if="currentChatUser?.is_system">
                {{ currentChatUser.app_name || currentChatUser.full_name || currentChatUser.username }}
              </template>
              <template v-else>
                {{ currentChatUser?.full_name || currentChatUser?.username }}
              </template>
            </h3>
            <p v-if="currentChatUser?.remarks" class="chat-header-remarks">{{ currentChatUser.remarks }}</p>
          </div>
        </header>

        <!-- 消息流区域 -->
        <main
          class="message-stream"
          ref="scrollContainer"
          :class="{ 'notification-mode': !!currentChatUser?.is_system }"
        >
          <!-- 系统通知卡片样式 -->
          <template v-if="currentChatUser?.is_system">
            <div v-for="msg in messages" :key="msg.id" class="notification-card-wrapper">
              <div class="notification-card">
                <!-- 发送者信息 -->
                <div v-if="msg.app_id || msg.type === 'NOTIFICATION'" class="notification-sender">
                  <PlatformIcon
                    v-if="hasSystemAppLogo(currentChatUser)"
                    class="notification-sender-logo"
                    :text="getAppName(msg) || currentChatUser?.app_name || '应用'"
                    :size="22"
                    shape="circle"
                    :icon-url="currentChatUser?.icon_url"
                    :app-id="currentChatUser?.application_app_id"
                    :icon-object-key="currentChatUser?.icon_object_key"
                    :show-caption="false"
                  />
                  <el-icon v-else class="sender-icon"><House /></el-icon>
                  <span class="sender-name">{{ getAppName(msg) || '系统通知' }}</span>
                </div>
                
                <!-- 通知标题 -->
                <div class="notification-title">{{ msg.title }}</div>
                
                <!-- 通知内容 -->
                <div class="notification-content">
                  <!-- 如果内容是JSON格式，解析为键值对 -->
                  <template v-if="isJsonContent(msg.content)">
                    <div 
                      v-for="(value, key) in parseJsonContent(msg.content)" 
                      :key="key"
                      class="notification-detail-item"
                    >
                      <span class="detail-label">{{ key }}:</span>
                      <span class="detail-value">{{ value }}</span>
                    </div>
                  </template>
                  <!-- 普通文本内容 -->
                  <template v-else>
                    <div class="notification-text">{{ msg.content }}</div>
                  </template>
                </div>
                
                <!-- 操作按钮 -->
                <div v-if="msg.action_url" class="notification-action">
                  <a 
                    :href="msg.action_url" 
                    class="action-link"
                    @click.prevent="handleNotificationAction(msg)"
                  >
                    <span>{{ msg.action_text || '进入小程序查看' }}</span>
                    <el-icon class="action-icon"><ArrowRight /></el-icon>
                  </a>
                </div>
                
                <!-- 时间戳 -->
                <div class="notification-time">{{ formatTime(msg.created_at) }}</div>
              </div>
            </div>
          </template>
          
          <!-- 普通消息样式（用户私信） -->
          <template v-else>
            <div v-for="msg in messages" :key="msg.id" class="message-row" :class="{ 'is-me': msg.sender_id === currentUserId }">
              
              <UserAvatar 
                v-if="msg.sender_id !== currentUserId && msg.sender_id !== null"
                :name="currentChatUser?.full_name || currentChatUser?.username || '系统通知'" 
                :userId="msg.sender_id || 0" 
                :size="36" 
                class="msg-avatar"
              />
              
              <div class="message-content-wrapper">
                 <div class="message-bubble">
                  <!-- 用户应用内“申请通知”：在私信界面展示通知样式（title + action_url） -->
                  <template v-if="msg.content_type === 'USER_NOTIFICATION'">
                    <div class="user-notification-title">{{ msg.title || '申请通知' }}</div>

                    <div class="notification-content">
                      <!-- 如果内容是 JSON 格式，解析为键值对 -->
                      <template v-if="isJsonContent(msg.content)">
                        <div
                          v-for="(value, key) in parseJsonContent(msg.content)"
                          :key="key"
                          class="notification-detail-item"
                        >
                          <span class="detail-label">{{ key }}:</span>
                          <span class="detail-value">{{ value }}</span>
                        </div>
                      </template>
                      <!-- 普通文本内容 -->
                      <template v-else>
                        <div class="notification-text">{{ msg.content }}</div>
                      </template>
                    </div>

                    <!-- 操作按钮（复用通知点击回调逻辑） -->
                    <div v-if="msg.action_url" class="notification-action">
                      <a
                        :href="msg.action_url"
                        class="action-link"
                        @click.prevent="handleNotificationAction(msg)"
                      >
                        <span>{{ msg.action_text || '查看' }}</span>
                        <el-icon class="action-icon"><ArrowRight /></el-icon>
                      </a>
                    </div>
                  </template>

                  <!-- TEXT -->
                  <span v-else-if="msg.content_type === 'TEXT'">{{ msg.content }}</span>

                  <!-- IMAGE -->
                  <el-image
                    v-else-if="msg.content_type === 'IMAGE'"
                    :src="msg.content"
                    :preview-src-list="[msg.content]"
                    class="msg-image"
                  />

                  <!-- FILE -->
                  <div v-else-if="msg.content_type === 'FILE'" class="msg-file">
                    <el-icon><Document /></el-icon>
                    <a :href="msg.content" target="_blank">下载文件</a>
                  </div>

                  <!-- VIDEO -->
                  <video v-else-if="msg.content_type === 'VIDEO'" :src="msg.content" controls class="msg-video"></video>
                 </div>
                 <div class="message-time">{{ formatTime(msg.created_at) }}</div>
              </div>

              <!-- Removed UserAvatar for Me -->
            </div>
          </template>
          
          <!-- 空状态提示 -->
          <el-empty v-if="messages.length === 0" description="暂无消息" :image-size="60" />
        </main>

        <!-- 底部输入框 - 系统会话不显示输入框 -->
        <footer v-if="!currentChatUser?.is_system" class="input-area">
          <div class="toolbar">
            <el-upload
              class="upload-demo"
              action="#"
              :http-request="handleUpload"
              :show-file-list="false"
              accept="image/*"
            >
              <el-icon title="图片" class="tool-icon"><Picture /></el-icon>
            </el-upload>
            <!-- <el-icon title="文件" class="tool-icon"><Folder /></el-icon> -->
          </div>
          <textarea 
            v-model="inputMessage" 
            @keydown.enter.prevent="sendMessage"
            placeholder="输入消息..."
            class="input-textarea"
          ></textarea>
          <div class="send-actions">
            <el-button type="primary" @click="sendMessage" :disabled="!inputMessage.trim()">发送</el-button>
          </div>
        </footer>
      </template>
      
      <div v-else class="empty-state">
        <el-empty description="选择一个联系人开始聊天" />
      </div>
    </div>
    
    <!-- 用户选择器弹窗 -->
    <el-dialog v-model="showUserSelector" title="发起聊天" width="500px">
       <el-select
        v-model="selectedUserId"
        filterable
        remote
        reserve-keyword
        placeholder="搜索用户(输入手机号或名字)"
        :remote-method="searchUsersRemote"
        :loading="searchingUsers"
        style="width: 100%"
      >
        <el-option
          v-for="item in userOptions"
          :key="item.id"
          :label="`${item.name || item.username || '未命名'} (${item.mobile})`"
          :value="item.id"
        />
      </el-select>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showUserSelector = false">取消</el-button>
          <el-button type="primary" @click="startNewChat">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, onActivated, computed, nextTick } from 'vue'
import UserAvatar from '@/components/UserAvatar.vue'
import PlatformIcon from '@/components/PlatformIcon.vue'
import { Picture, Document, House, ArrowRight } from '@element-plus/icons-vue'
import api from '@/utils/request'
import { useAuthStore } from '@/store/auth'
import { useMessageStore, onNewMessage } from '@/store/message'
import { ElMessage } from 'element-plus'

const authStore = useAuthStore()
const messageStore = useMessageStore()
const currentUser = computed(() => authStore.user)
const currentUserId = computed(() => authStore.user?.id)

// State
const searchText = ref('')
const loadingConversations = ref(false)
const conversations = ref<any[]>([])
const currentChatId = ref<number | null>(null)
const currentChatUser = ref<any>(null)
const messages = ref<any[]>([])
const inputMessage = ref('')
const scrollContainer = ref<HTMLElement | null>(null)

// User Selector
const showUserSelector = ref(false)
const selectedUserId = ref<number | null>(null)
const userOptions = ref<any[]>([])
const searchingUsers = ref(false)
const markingAllRead = ref(false)

/** 按应用拆分的系统会话（user_id < 0）且有 Logo URL 或 object key */
const hasSystemAppLogo = (c: Record<string, unknown> | null | undefined) => {
  if (!c || !c.is_system || typeof c.user_id !== 'number' || c.user_id >= 0) return false
  const u = String((c.icon_url as string) || '').trim()
  const k = String((c.icon_object_key as string) || '').trim()
  return !!(u || k)
}

// 应用名称缓存
const appNameCache = ref<Record<number, string>>({})

// Computed
const filteredConversations = computed(() => {
  if (!searchText.value) return conversations.value
  const lower = searchText.value.toLowerCase()
  return conversations.value.filter(c => 
    (c.full_name && c.full_name.toLowerCase().includes(lower)) ||
    (c.username && c.username.toLowerCase().includes(lower)) ||
    (c.remarks && String(c.remarks).toLowerCase().includes(lower)) ||
    (c.app_name && String(c.app_name).toLowerCase().includes(lower))
  )
})

// WS 推送到来时同步会话列表上的 unread_count（防抖）
let convRefreshTimer: ReturnType<typeof setTimeout> | null = null
const scheduleRefreshConversations = () => {
  if (convRefreshTimer) clearTimeout(convRefreshTimer)
  convRefreshTimer = setTimeout(() => {
    convRefreshTimer = null
    fetchConversations()
  }, 400)
}

// WS message handler (called by store when a new message arrives)
const handleWsMessage = (newMessage: any) => {
  const isSystemNotification = newMessage.type === 'NOTIFICATION' || newMessage.sender_id === null
  const systemConvId = isSystemNotification && newMessage.app_id ? -newMessage.app_id : 0

  if (isSystemNotification && currentChatId.value === systemConvId) {
    messages.value.push(newMessage)
    scrollToBottom()
  } else if (
    currentChatId.value === newMessage.sender_id ||
    (newMessage.sender_id === currentUserId.value && currentChatId.value === newMessage.receiver_id)
  ) {
    messages.value.push(newMessage)
    scrollToBottom()
  }

  if (isSystemNotification) {
    updateConversationPreview(systemConvId, newMessage.content, newMessage.content_type, {
      is_system: true,
      app_id: newMessage.app_id,
      app_name: newMessage.app_name,
      title: newMessage.title
    })
  } else {
    updateConversationPreview(
      newMessage.sender_id === currentUserId.value ? newMessage.receiver_id : newMessage.sender_id,
      newMessage.content,
      newMessage.content_type,
      newMessage.content_type === 'USER_NOTIFICATION' ? { title: newMessage.title } : undefined
    )
  }

  scheduleRefreshConversations()
}

const refreshMessagePage = () => {
  fetchConversations()
  messageStore.fetchUnreadCount()
}

// Lifecycle
let unsubscribeWs: (() => void) | null = null

onMounted(() => {
  refreshMessagePage()
  if (!currentUser.value) authStore.fetchUser()
  unsubscribeWs = onNewMessage(handleWsMessage)
})

onActivated(() => {
  refreshMessagePage()
})

onUnmounted(() => {
  if (convRefreshTimer) {
    clearTimeout(convRefreshTimer)
    convRefreshTimer = null
  }
  messageStore.setCurrentChat(null)
  if (unsubscribeWs) unsubscribeWs()
})

// Methods
const fetchConversations = async () => {
  loadingConversations.value = true
  try {
    const res = await api.get('/messages/conversations')
    conversations.value = res.data
  } catch (e) {
    console.error(e)
  } finally {
    loadingConversations.value = false
  }
}

const selectChat = async (chat: any) => {
  currentChatId.value = chat.user_id
  currentChatUser.value = chat
  messageStore.setCurrentChat(chat.user_id)
  try {
    await api.put(`/messages/history/${chat.user_id}/read-all`)
    const conv = conversations.value.find(c => c.user_id === chat.user_id)
    if (conv) conv.unread_count = 0
    await messageStore.fetchUnreadCount()
  } catch (e) {
    console.error(e)
  }
  await loadHistory(chat.user_id)
}

const markAllRead = async () => {
  markingAllRead.value = true
  try {
    await api.put('/messages/read-all')
    conversations.value.forEach(c => {
      c.unread_count = 0
    })
    await messageStore.fetchUnreadCount()
    ElMessage.success('已全部标为已读')
  } catch (e) {
    console.error(e)
  } finally {
    markingAllRead.value = false
  }
}

const loadHistory = async (userId: number) => {
  try {
    const res = await api.get(`/messages/history/${userId}`)
    messages.value = res.data.reverse()
    scrollToBottom()
  } catch (e) {
    console.error(e)
  }
}

const sendMessage = async () => {
  if (!inputMessage.value.trim() || !currentChatId.value || currentChatUser.value?.is_system) return
  
  const payload = {
    receiver_id: currentChatId.value,
    content: inputMessage.value,
    type: 'MESSAGE',
    content_type: 'TEXT',
    title: '私信'
  }

  try {
    const res = await api.post('/messages/', payload)
    messages.value.push(res.data)
    inputMessage.value = ''
    scrollToBottom()
    
    // Update conversation list preview
    updateConversationPreview(currentChatId.value, res.data.content, 'TEXT')
    
  } catch (e) {
    ElMessage.error('发送失败')
  }
}

const handleUpload = async (options: any) => {
  if (!currentChatId.value || currentChatUser.value?.is_system) return
  
  const { file } = options
  const formData = new FormData()
  formData.append('file', file)
  
  try {
    // 1. Upload
    const uploadRes = await api.post('/messages/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    
    const url = uploadRes.data.url // assuming response { url: '...' }
    
    // 2. Send Message
    const payload = {
      receiver_id: currentChatId.value,
      content: url, // Or JSON
      type: 'MESSAGE',
      content_type: 'IMAGE',
      title: '图片'
    }
    
    const res = await api.post('/messages/', payload)
    messages.value.push(res.data)
    scrollToBottom()
    updateConversationPreview(currentChatId.value!, '[图片]', 'IMAGE')
    
  } catch (e) {
    ElMessage.error('上传失败')
  }
}

const updateConversationPreview = (
  userId: number,
  content: string,
  type: string,
  extra?: { is_system?: boolean; app_id?: number; app_name?: string; title?: string }
) => {
  const conv = conversations.value.find(c => c.user_id === userId)
  if (conv) {
    if (type === 'USER_NOTIFICATION') {
      const t = (extra?.title && String(extra.title).trim()) || ''
      conv.last_message = t || '申请通知'
    } else if (type === 'TEXT') {
      conv.last_message = content
    } else {
      conv.last_message = `[${type}]`
    }
    conv.last_message_type = type
    conv.updated_at = new Date().toISOString()

    if (extra) {
      if (extra.is_system !== undefined) conv.is_system = extra.is_system
      if (extra.app_id !== undefined) conv.app_id = extra.app_id
      if (extra.app_name !== undefined) conv.app_name = extra.app_name
    }

    // Move to top
    conversations.value = [conv, ...conversations.value.filter(c => c.user_id !== userId)]
  } else {
    // 新会话：直接重新获取会话列表，由后端聚合
    fetchConversations()
  }
}

const scrollToBottom = () => {
  nextTick(() => {
    if (scrollContainer.value) {
      scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight
    }
  })
}

const formatTime = (timeStr: string) => {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  const now = new Date()
  
  if (date.toDateString() === now.toDateString()) {
    // Today: HH:mm
    return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
  }
  // Other: MM-DD
  return `${date.getMonth() + 1}-${date.getDate()}`
}

// User Search Logic
const searchUsersRemote = async (query: string) => {
  if (query) {
    searchingUsers.value = true
    try {
      // Assuming existing user search API
      const res = await api.get('/users/search', { params: { q: query, limit: 10 } })
      userOptions.value = res.data.data || res.data // Adapt to actual response structure
    } catch (e) {
      console.error(e)
    } finally {
      searchingUsers.value = false
    }
  } else {
    userOptions.value = []
  }
}

const startNewChat = () => {
  if (!selectedUserId.value) return
  
  const user = userOptions.value.find(u => u.id === selectedUserId.value)
  if (user) {
    // Check if exists
    const existing = conversations.value.find(c => c.user_id === user.id)
    if (existing) {
      selectChat(existing)
    } else {
      // Add temporary conversation item
      const newChat = {
        user_id: user.id,
        username: user.mobile, // Use mobile as username
        full_name: user.name || user.username || user.mobile, // Better fallback
        unread_count: 0,
        last_message: '',
        last_message_type: 'TEXT',
        updated_at: new Date().toISOString()
      }
      conversations.value.unshift(newChat)
      selectChat(newChat)
    }
  }
  showUserSelector.value = false
  selectedUserId.value = null
}

// 获取应用名称
const getAppName = (msg: any) => {
  // 优先使用后端返回的app_name
  if (msg.app_name) {
    return msg.app_name
  }
  // 如果没有，尝试从缓存获取
  if (msg.app_id && appNameCache.value[msg.app_id]) {
    return appNameCache.value[msg.app_id]
  }
  return null
}

// 判断内容是否为JSON格式
const isJsonContent = (content: string) => {
  if (!content) return false
  try {
    const parsed = JSON.parse(content)
    return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)
  } catch {
    return false
  }
}

// 解析JSON内容
const parseJsonContent = (content: string) => {
  try {
    return JSON.parse(content)
  } catch {
    return {}
  }
}

// 处理通知操作点击
const handleNotificationAction = async (msg: any) => {
  if (msg.action_url) {
    try {
      // 调用后端接口获取 callback URL（实时生成 ticket）
      const res = await api.get(`/messages/${msg.id}/callback-url`)
      if (res.data && res.data.callback_url) {
        window.open(res.data.callback_url, '_blank')
      } else {
        ElMessage.error('获取跳转链接失败')
      }
    } catch (error: any) {
      console.error('获取跳转链接失败:', error)
      ElMessage.error(error.response?.data?.detail || '获取跳转链接失败')
    }
  }
}

</script>

<style scoped>
.message-layout {
  display: flex;
  height: calc(100vh - 120px); /* Adjust based on header/padding */
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  border: 1px solid #e6e6e6;
}

.sidebar {
  width: 280px;
  background: #f7f7f7;
  border-right: 1px solid #e6e6e6;
  display: flex;
  flex-direction: column;
}

.search-bar {
  padding: 15px;
  display: flex;
  gap: 10px;
  background: #f7f7f7;
  border-bottom: 1px solid #e6e6e6;
}

.conversation-toolbar {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 6px 15px;
  background: #f0f0f0;
  border-bottom: 1px solid #e6e6e6;
}

.conversation-list {
  flex: 1;
  overflow-y: auto;
}

.chat-item {
  display: flex;
  padding: 12px 15px;
  cursor: pointer;
  position: relative;
  transition: background 0.2s;
}

.msg-conv-avatar {
  flex-shrink: 0;
}

.msg-conv-avatar :deep(.platform-icon-cell) {
  cursor: inherit;
}

.chat-header-app-icon {
  flex-shrink: 0;
}

.chat-header-app-icon :deep(.platform-icon-cell) {
  cursor: default;
}

.notification-sender-logo {
  flex-shrink: 0;
  margin-right: 6px;
}

.notification-sender-logo :deep(.platform-icon-cell) {
  cursor: default;
}

.notification-sender-logo :deep(.platform-icon:hover) {
  transform: none;
  box-shadow:
    0 4px 6px -1px rgba(0, 0, 0, 0.1),
    0 2px 4px -1px rgba(0, 0, 0, 0.06);
}

.chat-item:hover {
  background: #e9e9e9;
}

.chat-item.active {
  background: #c6c6c6;
}

.chat-info {
  margin-left: 10px;
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 4px;
}

.chat-remarks {
  font-size: 12px;
  color: #999;
  margin: 0 0 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.chat-name {
  font-weight: 500;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

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

.chat-preview {
  font-size: 13px;
  color: #888;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.unread-badge {
  position: absolute;
  right: 10px;
  bottom: 12px;
  background: #ff4d4f;
  color: white;
  border-radius: 10px;
  padding: 0 6px;
  font-size: 12px;
  height: 18px;
  line-height: 18px;
}

/* Chat Window */
.chat-window {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
  min-width: 0;
}

.chat-header-bar {
  min-height: 60px;
  border-bottom: 1px solid #e6e6e6;
  padding: 10px 20px;
  display: flex;
  align-items: center;
  gap: 12px;
  background: #f5f5f5;
}

.chat-header-titles {
  min-width: 0;
}

.chat-header-bar h3 {
  margin: 0;
  font-size: 16px;
  line-height: 1.3;
}

.chat-header-remarks {
  margin: 4px 0 0;
  font-size: 12px;
  color: #888;
  line-height: 1.3;
}

.message-stream {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.message-stream.notification-mode {
  background: #f5f5f5;
}

.message-row {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
}

.message-row.is-me {
  flex-direction: row-reverse;
}

.message-content-wrapper {
  max-width: 70%;
  display: flex;
  flex-direction: column;
}

.message-row.is-me .message-content-wrapper {
  align-items: flex-end;
}

.message-bubble {
  background: #fff;
  padding: 10px 14px;
  border-radius: 4px;
  position: relative;
  font-size: 14px;
  line-height: 1.5;
  word-wrap: break-word;
}

.message-row.is-me .message-bubble {
  background: #95ec69; /* WeChat green */
}

/* 私信气泡内的用户通知：标题需醒目（与普通文本区分） */
.user-notification-title {
  font-size: 16px;
  font-weight: 600;
  color: #1a1a1a;
  margin-bottom: 10px;
  line-height: 1.4;
}

.message-row.is-me .user-notification-title {
  color: #0f3d0f;
}

.message-time {
  font-size: 12px;
  color: #b2b2b2;
  margin-top: 4px;
}

.msg-image {
  max-width: 200px;
  border-radius: 4px;
  cursor: pointer;
}

.input-area {
  height: 160px;
  border-top: 1px solid #e6e6e6;
  background: #fff;
  display: flex;
  flex-direction: column;
  padding: 0 20px 20px;
}

.toolbar {
  height: 40px;
  display: flex;
  align-items: center;
  gap: 15px;
}

.tool-icon {
  font-size: 20px;
  color: #666;
  cursor: pointer;
}
.tool-icon:hover {
  color: #333;
}

.input-textarea {
  flex: 1;
  border: none;
  resize: none;
  outline: none;
  font-size: 14px;
  font-family: inherit;
}

.send-actions {
  display: flex;
  justify-content: flex-end;
}

/* 系统通知卡片样式 */
.notification-card-wrapper {
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
}

.notification-card {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  max-width: 90%;
  width: 100%;
  position: relative;
}

.notification-sender {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  font-size: 13px;
  color: #666;
}

.sender-icon {
  font-size: 16px;
  margin-right: 6px;
  color: #999;
}

.sender-name {
  font-weight: 500;
}

.notification-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
  line-height: 1.4;
}

.notification-content {
  margin-bottom: 12px;
}

.notification-detail-item {
  display: flex;
  margin-bottom: 8px;
  font-size: 14px;
  line-height: 1.5;
}

.detail-label {
  color: #666;
  min-width: 80px;
  flex-shrink: 0;
}

.detail-value {
  color: #333;
  flex: 1;
}

.notification-text {
  font-size: 14px;
  color: #333;
  line-height: 1.6;
}

.notification-action {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.action-link {
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: #1890ff;
  text-decoration: none;
  font-size: 14px;
  cursor: pointer;
  transition: color 0.2s;
}

.action-link:hover {
  color: #40a9ff;
}

.action-icon {
  font-size: 14px;
  margin-left: 4px;
}

.notification-time {
  position: absolute;
  top: 16px;
  right: 16px;
  font-size: 12px;
  color: #999;
}
</style>