<template>
  <div class="chat-app">
    <!-- 左侧会话列表 -->
    <div class="chat-sidebar">
      <div class="sidebar-header">
        <div class="header-title">
          <el-icon><ChatDotRound /></el-icon>
          <span>消息</span>
        </div>
        <div class="header-actions">
          <el-tooltip content="新建会话" placement="bottom">
            <el-button link icon="Plus" @click="showNewMessageDialog = true" />
          </el-tooltip>
        </div>
      </div>

      <div class="search-container">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索联系人、消息"
          prefix-icon="Search"
          clearable
          class="search-input"
        />
      </div>

      <div class="conversation-list">
        <div
          v-for="conv in displayConversations"
          :key="conv.conversationId"
          class="conversation-item"
          :class="{ 
            'active': currentConversation && currentConversation.conversationId === conv.conversationId,
            'unread': conv.unreadCount > 0 
          }"
          @click="selectConversation(conv)"
          @contextmenu.prevent="showContextMenu($event, conv)"
        >
          <div class="conversation-avatar">
            <el-avatar v-if="conv.conversationId === 'sys_notification'" :size="48" style="background-color: #409eff;">
              <el-icon :size="24"><Promotion /></el-icon>
            </el-avatar>
            <el-avatar v-else :size="48" :src="conv.avatar">
              {{ (conv.otherUserName || conv.title || '未知').charAt(0) }}
            </el-avatar>
          </div>
          
          <div class="conversation-content">
            <div class="conversation-header">
              <div class="conversation-name">{{ conv.remarkName || conv.otherUserName || conv.title || '未知用户' }}</div>
              <div class="conversation-time">{{ formatTime(conv.lastMessageTime) }}</div>
            </div>
            <div class="conversation-preview">
              <div class="last-message">{{ conv.lastMessage || '暂无消息' }}</div>
              <el-badge v-if="conv.unreadCount > 0" :value="conv.unreadCount > 99 ? '99+' : conv.unreadCount" class="unread-count" />
            </div>
          </div>
        </div>

        <div v-if="displayConversations.length === 0" class="empty-conversations">
          <el-icon :size="48"><ChatLineRound /></el-icon>
          <p>暂无会话</p>
        </div>
      </div>
    </div>

    <!-- 右侧聊天区域 -->
    <div class="chat-main">
      <div v-if="currentConversation" class="chat-window">
        <div class="chat-header">
          <div class="chat-user-info">
            <el-avatar v-if="currentConversation.conversationId === 'sys_notification'" :size="40" style="background-color: #409eff;">
              <el-icon :size="20"><Promotion /></el-icon>
            </el-avatar>
            <el-avatar v-else :size="40" :src="currentConversation.avatar">
              {{ (currentConversation.otherUserName || '未知').charAt(0) }}
            </el-avatar>
            <div class="user-details">
              <div class="user-name">{{ currentConversation.otherUserName || currentConversation.title || '未知用户' }}</div>
            </div>
          </div>
          <div class="header-actions">
            <el-button 
              v-if="currentConversation.conversationId === 'sys_notification'"
              link
              icon="CircleCheck"
              @click="markAllNotificationsAsRead"
            >全部已读</el-button>
            <el-button 
              v-else
              link
              icon="Edit"
              @click="editRemark"
            >备注</el-button>
          </div>
        </div>

        <div class="messages-container" ref="messagesContainerRef">
          <!-- 系统通知 -->
          <div v-if="currentConversation.conversationId === 'sys_notification'" class="notification-container">
            <div v-if="systemNotifications.length === 0" class="empty-notifications">
              <el-icon :size="48"><Bell /></el-icon>
              <p>暂无系统通知</p>
            </div>
            <div 
              v-for="notif in systemNotifications" 
              :key="notif.notification_id" 
              class="notification-card"
              :class="{ 'is-unread': notif.is_read === '0' }"
              @click="handleNotificationClick(notif)"
            >
              <div class="card-title">{{ notif.title }}</div>
              <div class="card-content" v-if="notif.content">{{ notif.content }}</div>
              <div class="card-time">{{ formatNotificationTime(notif.create_time) }}</div>
            </div>
          </div>

          <!-- 对话消息 -->
          <div v-else class="messages-list">
            <div v-for="(group, date) in groupedMessages" :key="date" class="message-group">
              <div class="date-divider">
                <span class="date-text">{{ formatDate(date) }}</span>
              </div>
              
              <div
                v-for="msg in group"
                :key="msg.messageId"
                class="message-wrapper"
                :class="{ 'is-mine': msg.senderId === userId }"
              >
                <div class="message-item">
                  <div v-if="msg.senderId !== userId" class="message-avatar">
                    <el-avatar :size="36" :src="msg.senderAvatar">
                      {{ (msg.senderName || '未知').charAt(0) }}
                    </el-avatar>
                  </div>
                  
                  <div class="message-content">
                    <div class="message-bubble" :class="msg.senderId === userId ? 'bubble-mine' : 'bubble-other'">
                      {{ msg.content }}
                    </div>
                    <div class="message-meta">
                      <span class="message-time">{{ formatMessageTime(msg.createTime) }}</span>
                    </div>
                  </div>
                  
                  <div v-if="msg.senderId === userId" class="message-avatar">
                    <el-avatar :size="36" :src="userAvatar">
                      {{ (userName || '我').charAt(0) }}
                    </el-avatar>
                  </div>
                </div>
              </div>
            </div>

            <div v-if="messages.length === 0" class="empty-messages">
              <el-icon :size="48"><ChatDotRound /></el-icon>
              <p>还没有消息</p>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div v-if="currentConversation.conversationId !== 'sys_notification'" class="input-area">
          <div class="input-container">
            <el-input
              v-model="messageContent"
              type="textarea"
              :rows="3"
              placeholder="输入消息... (Enter发送, Ctrl+Enter换行)"
              :maxlength="1000"
              resize="none"
              @keydown="handleKeyDown"
            />
            <div class="input-footer">
              <span class="char-count">{{ messageContent.length }}/1000</span>
              <el-button 
                type="primary" 
                :disabled="!messageContent.trim() || sending"
                :loading="sending"
                @click="sendMessage"
              >发送</el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 欢迎界面 -->
      <div v-else class="welcome-screen">
        <el-icon :size="64"><ChatDotRound /></el-icon>
        <h2>欢迎使用消息中心</h2>
        <p>选择一个会话开始聊天</p>
        <el-button type="primary" icon="Plus" @click="showNewMessageDialog = true">开始新对话</el-button>
      </div>
    </div>

    <!-- 新建会话对话框 -->
    <el-dialog title="新建会话" v-model="showNewMessageDialog" width="400px">
      <el-form :model="newConvForm" :rules="newConvRules" ref="newConvFormRef" label-width="80px">
        <el-form-item label="选择用户" prop="userId">
          <el-select
            v-model="newConvForm.userId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入昵称/手机号搜索"
            :remote-method="searchUsers"
            :loading="searchLoading"
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="user in userOptions"
              :key="user.userId"
              :label="user.nickName + ' (' + (user.phonenumber || '无') + ')'"
              :value="user.userId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showNewMessageDialog = false">取消</el-button>
        <el-button type="primary" @click="createNewConversation" :loading="sending">创建</el-button>
      </template>
    </el-dialog>

    <!-- 设置备注对话框 -->
    <el-dialog title="设置备注" v-model="showRemarkDialog" width="400px">
      <el-form :model="remarkForm" label-width="80px">
        <el-form-item label="用户名">
          <el-input :model-value="currentConversation?.otherUserName || ''" disabled />
        </el-form-item>
        <el-form-item label="备注名">
          <el-input v-model="remarkForm.remark" placeholder="请输入备注名" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showRemarkDialog = false">取消</el-button>
        <el-button type="primary" @click="saveRemark">保存</el-button>
      </template>
    </el-dialog>

    <!-- 右键菜单 -->
    <div 
      v-if="contextMenu.visible" 
      class="context-menu"
      :style="{ top: contextMenu.top + 'px', left: contextMenu.left + 'px' }"
    >
      <div class="context-menu-item" @click="deleteConversationItem(contextMenu.conversation)">
        <el-icon><Delete /></el-icon>
        <span>删除会话</span>
      </div>
    </div>
  </div>
</template>

<script setup name="MessageCenter">
import { ChatDotRound, ChatLineRound, Promotion, Bell, Delete } from '@element-plus/icons-vue'
import { getConversationList, getConversationMessages, sendMessage as sendMessageAPI, setConversationRemark, createPrivateConversation, markConversationAsRead as markReadAPI, deleteConversation } from '@/api/system/message'
import { listUser } from '@/api/system/user'
import { getAllNotifications, markNotificationAsRead } from '@/api/system/notification'
import useUserStore from '@/store/modules/user'

const { proxy } = getCurrentInstance()
const userStore = useUserStore()

const loading = ref(false)
const searchKeyword = ref('')
const conversationList = ref([])
const currentConversation = ref(null)
const messages = ref([])
const systemNotifications = ref([])
const messageContent = ref('')
const sending = ref(false)
const messagesContainerRef = ref(null)

// 对话框
const showNewMessageDialog = ref(false)
const showRemarkDialog = ref(false)
const searchLoading = ref(false)

// 表单
const newConvForm = ref({ userId: null })
const newConvRules = { userId: [{ required: true, message: '请选择用户', trigger: 'change' }] }
const userOptions = ref([])
const remarkForm = ref({ remark: '' })
const newConvFormRef = ref(null)

// 右键菜单
const contextMenu = reactive({
  visible: false,
  top: 0,
  left: 0,
  conversation: null
})

// 用户信息
const userId = computed(() => userStore.id)
const userName = computed(() => userStore.name || '我')
const userAvatar = computed(() => userStore.avatar || '')

// 显示的会话列表
const displayConversations = computed(() => {
  let filtered = conversationList.value
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(conv => 
      (conv.otherUserName || '').toLowerCase().includes(keyword) || 
      (conv.lastMessage || '').toLowerCase().includes(keyword)
    )
  }
  return filtered.sort((a, b) => {
    if (a.unreadCount > 0 && b.unreadCount === 0) return -1
    if (a.unreadCount === 0 && b.unreadCount > 0) return 1
    return new Date(b.lastMessageTime) - new Date(a.lastMessageTime)
  })
})

// 按日期分组的消息
const groupedMessages = computed(() => {
  const groups = {}
  messages.value.forEach(msg => {
    const date = new Date(msg.createTime).toDateString()
    if (!groups[date]) groups[date] = []
    groups[date].push(msg)
  })
  return groups
})

/** 加载数据 */
async function loadData() {
  loading.value = true
  try {
    await loadConversations()
    await loadSystemNotifications()
  } finally {
    loading.value = false
  }
}

/** 加载会话列表 */
async function loadConversations() {
  try {
    const response = await getConversationList()
    conversationList.value = (response.data || []).map(conv => ({
      conversationId: conv.conversation_id,
      userId: conv.userId,
      otherUserName: conv.other_members || '未知用户',
      lastMessage: conv.last_message || '',
      lastMessageTime: conv.last_message_time,
      unreadCount: conv.unread_count || 0,
      remarkName: conv.remark_name,
      messages: []
    }))
    
    // 添加系统通知会话
    conversationList.value.push({
      conversationId: 'sys_notification',
      otherUserName: '系统通知',
      lastMessage: '',
      lastMessageTime: 0,
      unreadCount: 0,
      remarkName: null
    })
  } catch (error) {
    proxy.$modal.msgError('加载会话列表失败')
  }
}

/** 加载系统通知 */
async function loadSystemNotifications() {
  try {
    const response = await getAllNotifications()
    let notifications = response.data || []
    notifications.sort((a, b) => {
      if (a.is_read !== b.is_read) return a.is_read.localeCompare(b.is_read)
      return new Date(b.create_time) - new Date(a.create_time)
    })
    systemNotifications.value = notifications
    
    // 更新未读数
    const unreadCount = systemNotifications.value.filter(n => n.is_read === '0').length
    const sysNotifConv = conversationList.value.find(c => c.conversationId === 'sys_notification')
    if (sysNotifConv) {
      sysNotifConv.unreadCount = unreadCount
      if (notifications.length > 0) {
        sysNotifConv.lastMessage = notifications[0].title
        sysNotifConv.lastMessageTime = new Date(notifications[0].create_time).getTime()
      }
    }
  } catch (error) {
    console.error('加载系统通知失败:', error)
  }
}

/** 选择会话 */
async function selectConversation(conversation) {
  currentConversation.value = conversation
  
  if (conversation.conversationId !== 'sys_notification') {
    await markConversationAsRead(conversation)
    await loadMessages()
    scrollToBottom()
  } else {
    messages.value = []
    await loadSystemNotifications()
  }
}

/** 加载消息 */
async function loadMessages() {
  if (!currentConversation.value) return
  try {
    const response = await getConversationMessages(currentConversation.value.conversationId)
    messages.value = response.data || []
    scrollToBottom()
  } catch (error) {
    messages.value = []
  }
}

/** 发送消息 */
async function sendMessage() {
  if (!messageContent.value.trim() || !currentConversation.value) return
  
  sending.value = true
  try {
    await sendMessageAPI(currentConversation.value.conversationId, messageContent.value)
    messageContent.value = ''
    await loadMessages()
    await loadConversations()
    scrollToBottom()
  } catch (error) {
    proxy.$modal.msgError('发送失败')
  } finally {
    sending.value = false
  }
}

/** 标记会话为已读 */
async function markConversationAsRead(conversation) {
  if (conversation.unreadCount > 0) {
    try {
      await markReadAPI(conversation.conversationId)
      conversation.unreadCount = 0
    } catch (error) {
      conversation.unreadCount = 0
    }
  }
}

/** 标记所有通知为已读 */
async function markAllNotificationsAsRead() {
  try {
    const unread = systemNotifications.value.filter(n => n.is_read === '0')
    await Promise.all(unread.map(n => markNotificationAsRead(n.notification_id)))
    unread.forEach(n => n.is_read = '1')
    
    const sysNotifConv = conversationList.value.find(c => c.conversationId === 'sys_notification')
    if (sysNotifConv) sysNotifConv.unreadCount = 0
  } catch (error) {
    console.error('标记通知失败:', error)
  }
}

/** 处理通知点击 */
async function handleNotificationClick(notif) {
  if (notif.is_read === '0') {
    try {
      await markNotificationAsRead(notif.notification_id)
      notif.is_read = '1'
      
      const unreadCount = systemNotifications.value.filter(n => n.is_read === '0').length
      const sysNotifConv = conversationList.value.find(c => c.conversationId === 'sys_notification')
      if (sysNotifConv) sysNotifConv.unreadCount = unreadCount
    } catch (error) {
      console.error('标记通知失败:', error)
    }
  }
}

/** 搜索用户 */
async function searchUsers(query) {
  if (!query) {
    userOptions.value = []
    return
  }
  searchLoading.value = true
  try {
    const response = await listUser({ nickName: query, pageNum: 1, pageSize: 20 })
    userOptions.value = (response.rows || [])
      .filter(user => user.userId !== userId.value)
      .map(user => ({
        userId: user.userId,
        nickName: user.nickName,
        phonenumber: user.phonenumber
      }))
  } finally {
    searchLoading.value = false
  }
}

/** 创建新会话 */
async function createNewConversation() {
  newConvFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    sending.value = true
    try {
      await createPrivateConversation(newConvForm.value.userId)
      proxy.$modal.msgSuccess('会话创建成功')
      showNewMessageDialog.value = false
      newConvForm.value.userId = null
      userOptions.value = []
      loadConversations()
    } catch (error) {
      proxy.$modal.msgError('创建失败')
    } finally {
      sending.value = false
    }
  })
}

/** 删除会话 */
async function deleteConversationItem(conversation) {
  contextMenu.visible = false
  try {
    await proxy.$modal.confirm('确定删除该会话吗？')
    await deleteConversation(conversation.conversationId)
    proxy.$modal.msgSuccess('删除成功')
    
    if (currentConversation.value?.conversationId === conversation.conversationId) {
      currentConversation.value = null
      messages.value = []
    }
    loadConversations()
  } catch (error) {
    if (error !== 'cancel') proxy.$modal.msgError('删除失败')
  }
}

/** 编辑备注 */
function editRemark() {
  remarkForm.value.remark = currentConversation.value?.remarkName || ''
  showRemarkDialog.value = true
}

/** 保存备注 */
async function saveRemark() {
  try {
    await setConversationRemark(currentConversation.value.conversationId, remarkForm.value.remark)
    currentConversation.value.remarkName = remarkForm.value.remark
    showRemarkDialog.value = false
    proxy.$modal.msgSuccess('保存成功')
  } catch (error) {
    proxy.$modal.msgError('保存失败')
  }
}

/** 右键菜单 */
function showContextMenu(event, conversation) {
  if (conversation.conversationId === 'sys_notification') return
  contextMenu.visible = true
  contextMenu.top = event.clientY
  contextMenu.left = event.clientX
  contextMenu.conversation = conversation
}

/** 键盘事件 */
function handleKeyDown(event) {
  if (event.key === 'Enter' && !event.ctrlKey) {
    event.preventDefault()
    sendMessage()
  }
}

/** 滚动到底部 */
function scrollToBottom() {
  nextTick(() => {
    if (messagesContainerRef.value) {
      messagesContainerRef.value.scrollTop = messagesContainerRef.value.scrollHeight
    }
  })
}

/** 格式化时间 */
function formatTime(time) {
  if (!time) return ''
  const date = new Date(time)
  const now = new Date()
  const diff = now - date
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return Math.floor(diff / 60000) + '分钟前'
  if (diff < 86400000) return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  return date.toLocaleDateString('zh-CN', { month: 'numeric', day: 'numeric' })
}

function formatMessageTime(time) {
  if (!time) return ''
  return new Date(time).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
}

function formatNotificationTime(time) {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleDateString('zh-CN', { month: 'numeric', day: 'numeric' }) + ' ' + 
         date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
}

function formatDate(dateStr) {
  const date = new Date(dateStr)
  const today = new Date()
  if (date.toDateString() === today.toDateString()) return '今天'
  const yesterday = new Date(today)
  yesterday.setDate(yesterday.getDate() - 1)
  if (date.toDateString() === yesterday.toDateString()) return '昨天'
  return date.toLocaleDateString('zh-CN', { month: 'long', day: 'numeric' })
}

// WebSocket 事件监听
let unsubscribeMessage = null
let unsubscribeNotification = null

// 点击关闭右键菜单
onMounted(async () => {
  document.addEventListener('click', () => { contextMenu.visible = false })
  await loadData()
  
  // 动态导入 WebSocket 服务
  const { wsService } = await import('@/utils/websocket')
  
  // 监听新消息
  unsubscribeMessage = wsService.on('new_message', (payload) => {
    // 刷新会话列表
    loadConversations()
    // 如果当前正在查看该会话，则加载新消息
    if (currentConversation.value && payload.conversationId === currentConversation.value.conversationId) {
      loadMessages(currentConversation.value.conversationId)
    }
  })
  
  // 监听新通知（包括 new_notification 和 system_notification）
  unsubscribeNotification = wsService.on('new_notification', () => {
    // 刷新系统通知
    loadSystemNotifications()
  })
  
  // 监听系统通知
  wsService.on('system_notification', () => {
    loadSystemNotifications()
  })
})

onUnmounted(() => {
  document.removeEventListener('click', () => { contextMenu.visible = false })
  // 取消 WebSocket 事件监听
  if (unsubscribeMessage) unsubscribeMessage()
  if (unsubscribeNotification) unsubscribeNotification()
})
</script>

<style lang="scss" scoped>
@import './chat-styles.scss';
</style>
