<template>
  <!-- 消息页面 -->
  <div class="message-page" ref="messagePageRef">
    <div class="message-layout">
      <!-- 会话列表 -->
      <div class="conversation-panel">
        <div class="conversation-list">
          <div
            v-for="(item, index) in chatList"
            :key="index"
            class="conversation-item"
            :class="{ active: selectedChat === item }"
            @click="selectChat(item)"
          >
            <el-badge :value="item.unread > 0 ? item.unread : ''" :max="99">
            </el-badge>
            <div class="conv-info">
              <div class="conv-header">
                <span class="conv-name">{{ item.data?.nickname || '用户' }}</span>
                <span class="conv-time">{{ formatTime(item.lastMessage?.timestamp) }}</span>
              </div>
              <div class="conv-preview">{{ item.lastMessage?.payload?.text || '' }}</div>
            </div>
            <span
              class="conv-delete"
              @click.stop="removeConversation(item, index)"
              title="删除会话"
            >×</span>
          </div>

          <div v-if="chatList.length === 0" class="empty-tip">暂无会话</div>
        </div>
      </div>

      <!-- 消息列表 -->
      <div class="chat-panel">
        <div v-if="selectedChat" class="chat-container">
          <div class="chat-header">
            <span class="chat-header-name">{{ selectedChat.data?.nickname || '用户' }}</span>
          </div>
          <div class="chat-messages" ref="chatMessagesRef" :style="{ visibility: isScrollReady ? 'visible' : 'hidden' }">
            <div
              v-for="(msg, index) in messagesList"
              :key="index"
              class="message-item"
              :class="{ mine: msg.senderId == currentUser.id }"
            >
              <div
                class="message-bubble"
                @contextmenu.prevent="msg.type !== 'pk' ? showContextMenu($event, msg, index) : null"
              >
                <div v-if="msg.recalled" class="recalled-tip">消息已撤回</div>
                <template v-else>
                  <div v-if="msg.type === 'text'" class="text-message">{{ msg.payload.text }}</div>
                  <PictureMessage v-else-if="msg.type === 'image'" :item="msg" />
                  <MiniPKMessage v-else-if="msg.type === 'pk'" :item="msg" />
                  <VoiceMessage v-else-if="msg.type === 'audio'" :item="msg.payload.url" :size="msg.payload.duration" />
                  <div v-if="msg.senderId == currentUser.id" class="read-status">
                    {{ msg.read ? '已读' : '未读' }}
                  </div>
                </template>
              </div>
            </div>
          </div>

          <div class="chat-input-area">
            <div class="input-toolbar">
              <div class="toolbar-btn" @click="handleSendImage">
                <span class="material-icons-round">image</span>
              </div>
            </div>
            <div class="input-box">
              <textarea
                v-model="inputText"
                placeholder="输入消息..."
                @keydown.enter.prevent="sendMessage"
              ></textarea>
              <el-button type="primary" @click="sendMessage">发送</el-button>
            </div>
          </div>
        </div>

        <div v-else class="chat-placeholder">
          <span class="material-icons-round placeholder-icon">chat_bubble_outline</span>
          <p>选择左侧会话开始聊天</p>
        </div>
      </div>
    </div>

    <!-- 隐藏的文件输入 -->
    <input
      ref="fileInputRef"
      type="file"
      accept="image/*"
      style="display: none"
      @change="handleFileSelect"
    />
    <!-- 右键菜单 -->
    <div
      v-if="contextMenu.visible"
      class="context-menu"
      :style="{ top: contextMenu.y + 'px', left: contextMenu.x + 'px', transformOrigin: contextMenu.isMine ? 'top right' : 'top left' }"
      @mouseleave="hideContextMenu"
    >
      <div v-if="contextMenu.msg?.type === 'text'" class="context-menu-item" @click="copyMessage">复制</div>
      <div v-if="contextMenu.msg?.senderId == currentUser.id" class="context-menu-item danger" @click="recallMessage">撤回</div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, onActivated, nextTick, watch } from 'vue'
import { getMainUserData } from '@/utils/pk-mini/storage'
import { TimestamptolocalTime } from '@/utils/pk-mini/timeConversion'
import { isGoEasyEnabled } from '@/config/pk-mini'
import {
  goEasyGetConversations,
  goEasyGetMessages,
  goEasySendMessage,
  goEasySendImageMessage,
  goEasyMessageRead,
  goEasyRemoveConversation,
  goEasyRecallMessage,
  getPkGoEasy,
  GoEasy
} from '@/utils/pk-mini/goeasy'
import PictureMessage from '@/components/pk-mini/chat/PictureMessage.vue'
import MiniPKMessage from '@/components/pk-mini/chat/MiniPKMessage.vue'
import VoiceMessage from '@/components/pk-mini/chat/VoiceMessage.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { pkUnreadStore } from '@/stores/pk-mini/notice.js'

const defaultAvatar = 'https://vv-1317974657.cos.ap-shanghai.myqcloud.com/util/default-avatar.png'
const chatList = ref([])
const selectedChat = ref(null)
const messagesList = ref([])
const inputText = ref('')
const currentUser = ref({})
const isScrollReady = ref(false)
const chatMessagesRef = ref(null)
const fileInputRef = ref(null)
const unreadStore = pkUnreadStore()
const contextMenu = ref({ visible: false, x: 0, y: 0, msg: null, index: -1 })
const messagePageRef = ref(null)

function showContextMenu(event, msg, index) {
  const menuWidth = 110
  const menuHeight = msg.senderId == currentUser.value.id ? 80 : 44
  const rect = messagePageRef.value?.getBoundingClientRect() || { left: 0, top: 0, width: window.innerWidth, height: window.innerHeight }
  let x = event.clientX - rect.left
  let y = event.clientY - rect.top
  const isMine = msg.senderId == currentUser.value.id
  // 自己的消息在右侧，菜单向左偏移
  if (isMine) x -= menuWidth
  if (x + menuWidth > rect.width) x -= menuWidth
  if (x < 0) x = 0
  if (y + menuHeight > rect.height) y -= menuHeight
  contextMenu.value = { visible: true, x, y, msg, index, isMine }
}

function hideContextMenu() {
  contextMenu.value.visible = false
}

function copyMessage() {
  const text = contextMenu.value.msg?.payload?.text || ''
  if (navigator.clipboard) {
    navigator.clipboard.writeText(text).catch(() => {})
  } else {
    const el = document.createElement('textarea')
    el.value = text
    document.body.appendChild(el)
    el.select()
    document.execCommand('copy')
    document.body.removeChild(el)
  }
  hideContextMenu()
}

async function recallMessage() {
  const msg = contextMenu.value.msg
  const index = contextMenu.value.index
  hideContextMenu()
  if (!msg) return
  try {
    await goEasyRecallMessage(msg)
    // 用对象替换触发 Vue 响应式更新
    messagesList.value.splice(index, 1, { ...msg, recalled: true })
  } catch (e) {
    console.error('撤回失败', e)
    ElMessage.error('撤回失败，消息超过4小时或发送中')
  }
}

const formatTime = TimestamptolocalTime

async function loadConversations() {
  if (!isGoEasyEnabled()) {
    ElMessage.warning('消息功能暂时不可用（GoEasy 订阅未续费）')
    return
  }

  try {
    const result = await goEasyGetConversations()
    chatList.value = result?.content?.conversations || []
  } catch (e) {
    console.error('加载会话列表失败', e)
  }
}

async function selectChat(item) {
  if (!isGoEasyEnabled()) return

  selectedChat.value = item
  try {
    const messages = await goEasyGetMessages({ id: String(item.userId), timestamp: null })
    messagesList.value = messages || []
    await nextTick()
    scrollToBottom()
    // 异步卡片内容加载完后再滚一次
    scrollToBottomHidden()
    // 标记消息已读
    goEasyMessageRead({ id: String(item.userId) }).catch(() => {})
    unreadStore.decrease(item.unread || 0)
    item.unread = 0
  } catch (e) {
    console.error('加载消息失败', e)
  }
}

function scrollToBottom() {
  if (chatMessagesRef.value) {
    chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight
  }
}

function scrollToBottomHidden() {
  isScrollReady.value = false
  setTimeout(() => {
    if (chatMessagesRef.value) {
      chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight
    }
    isScrollReady.value = true
  }, 300)
}

async function sendMessage() {
  if (!isGoEasyEnabled()) {
    ElMessage.warning('消息功能暂时不可用（GoEasy 订阅未续费）')
    return
  }

  if (!inputText.value.trim()) return
  if (!selectedChat.value) return

  try {
    const msg = await goEasySendMessage({
      text: inputText.value,
      id: String(selectedChat.value.userId),
      avatar: selectedChat.value.data?.avatar || '',
      nickname: selectedChat.value.data?.nickname || ''
    })
    messagesList.value.push(msg)
    inputText.value = ''
    await nextTick()
    scrollToBottom()
    // 发送消息后标记已读，清除该会话红点
    const conv = chatList.value.find(c => c.userId === selectedChat.value.userId)
    if (conv && conv.unread > 0) {
      goEasyMessageRead({ id: String(selectedChat.value.userId) }).catch(() => {})
      unreadStore.decrease(conv.unread)
      conv.unread = 0
    }
  } catch (e) {
     console.error('发送消息失败', e)
    if(e =='Error: id can not be the same as your id'){
      ElMessage.error('不能给自己发消息')
    }else{
       ElMessage.error('发送失败')
    }
  }
}

function handleSendImage() {
  if (!isGoEasyEnabled()) {
    ElMessage.warning('消息功能暂时不可用（GoEasy 订阅未续费）')
    return
  }
  if (!selectedChat.value) {
    ElMessage.warning('请先选择一个会话')
    return
  }
  fileInputRef.value?.click()
}

async function handleFileSelect(event) {
  const file = event.target.files?.[0]
  event.target.value = ''

  if (!file || !isGoEasyEnabled()) return
  if (!selectedChat.value) return

  try {
    const msg = await goEasySendImageMessage({
      imagefile: file,
      id: String(selectedChat.value.userId),
      avatar: selectedChat.value.data?.avatar || '',
      nickname: selectedChat.value.data?.nickname || ''
    })
    messagesList.value.push(msg)
    await nextTick()
    scrollToBottom()
  } catch (e) {
    console.error('发送图片失败', e)
    ElMessage.error('发送图片失败')
  }
}

async function removeConversation(item, index) {
  try {
    await ElMessageBox.confirm('确定删除该会话吗？', '删除会话', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning'
    })
  } catch {
    return
  }
  try {
    await goEasyRemoveConversation(item)
    chatList.value.splice(index, 1)
    if (selectedChat.value === item) {
      selectedChat.value = null
      messagesList.value = []
    }
  } catch (e) {
    console.error('删除会话失败', e)
    ElMessage.error('删除会话失败')
  }
}

onMounted(() => {
  currentUser.value = getMainUserData() || {}
  document.addEventListener('click', hideContextMenu)
  if (isGoEasyEnabled()) {
    loadConversations()
    const goeasy = getPkGoEasy()
    if (goeasy) {
      goeasy.im.on(GoEasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, onMessageReceived)
      goeasy.im.on(GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, onConversationsUpdated)
      goeasy.im.on(GoEasy.IM_EVENT.MESSAGE_READ, onMessageRead)
      goeasy.im.on(GoEasy.IM_EVENT.MESSAGE_RECALLED, onMessageRecalled)
    }
  }
  // 切换回消息页面时，滚到聊天记录最底部
  nextTick(() => scrollToBottomHidden())
})

// KeepAlive 缓存激活时触发（从其他页面切回消息页面）
onActivated(() => {
  scrollToBottomHidden()
})

// 监听 chatMessagesRef 出现（selectedChat 从 null 变为有值时 DOM 才渲染）
watch(chatMessagesRef, (el) => {
  if (el) scrollToBottomHidden()
})

function onConversationsUpdated(conversations) {
  chatList.value = conversations.conversations || []
  console.log("chatList返回",chatList.value)
}

function onMessageRead(messages) {
  messages.forEach(readMsg => {
    const index = messagesList.value.findIndex(m => m.messageId === readMsg.messageId)
    if (index !== -1) {
      messagesList.value.splice(index, 1, { ...messagesList.value[index], read: true })
    }
  })
}

function onMessageRecalled(messages) {
  messages.forEach(recalled => {
    const index = messagesList.value.findIndex(m => m.messageId === recalled.messageId)
    if (index !== -1) {
      messagesList.value.splice(index, 1, { ...messagesList.value[index], recalled: true })
    }
  })
}

function onMessageReceived(message) {
  if (!isGoEasyEnabled()) return
  // 始终累加会话未读数和更新最后一条消息（全局 unreadStore 由 PkAppaside 统一维护）
  const conv = chatList.value.find(c => c.userId === message.senderId)
  if (conv) {
    conv.unread = (conv.unread || 0) + 1
    conv.lastMessage = message
  }
  // 如果当前正在查看该会话，追加消息到列表
  if (selectedChat.value && selectedChat.value.userId === message.senderId) {
    messagesList.value.push(message)
    nextTick(() => scrollToBottom())
  }
}

onUnmounted(() => {
  document.removeEventListener('click', hideContextMenu)
  if (isGoEasyEnabled()) {
    const goeasy = getPkGoEasy()
    if (goeasy) {
      try {
        goeasy.im.off(GoEasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, onMessageReceived)
        goeasy.im.off(GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, onConversationsUpdated)
        goeasy.im.off(GoEasy.IM_EVENT.MESSAGE_READ, onMessageRead)
        goeasy.im.off(GoEasy.IM_EVENT.MESSAGE_RECALLED, onMessageRecalled)
      } catch (e) {
        console.warn('清理 GoEasy 监听器失败', e)
      }
    }
  }
})
</script>

<style scoped lang="less">
.message-page {
  position: relative;
  width: 100%;
  height: 100%;
  background-color: #ffffff;
  border: 1px solid #f1f5f9;
  border-radius: 12px;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.message-layout {
  display: flex;
  height: 100%;
}

.conversation-panel {
  width: 280px;
  min-width: 220px;
  flex-shrink: 0;
  border-right: 1px solid #e5e7eb;
}

.chat-panel {
  flex: 1;
  min-width: 0;
  height: 100%;
}

.conversation-list {
  height: 100%;
  overflow: auto;
  background-color: #f9fafb; // gray-50
}

.conversation-item {
  display: flex;
  padding: 15px;
  cursor: pointer;
  transition: background 0.2s;
  border-bottom: 1px solid #f1f5f9; // slate-100
}

.conversation-item:hover, .conversation-item.active {
  background-color: #eff6ff; // blue-50
}

.conv-avatar {
  width: 50px;
  height: 50px;
  border-radius: 10px;
  overflow: hidden;
  margin-right: 12px;
}

.conv-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.conv-info {
  flex: 1;
  min-width: 0;
}

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

.conv-name {
  font-weight: bold;
  color: #0f172a; // slate-900
}

.conv-time {
  font-size: 12px;
  color: #94a3b8; // slate-400
}

.conv-preview {
  font-size: 13px;
  color: #64748b; // slate-500
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.chat-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chat-header {
  padding: 14px 20px;
  border-bottom: 1px solid #f1f5f9;
  background-color: #ffffff;
  flex-shrink: 0;
}

.chat-header-name {
  font-size: 15px;
  font-weight: bold;
  color: #0f172a;
}

.chat-messages {
  flex: 1;
  overflow: auto;
  padding: 20px;
}

.message-item {
  display: flex;
  margin-bottom: 20px;
}

.message-item.mine {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 45px;
  height: 45px;
  border-radius: 10px;
  overflow: hidden;
  margin: 0 12px;
  flex-shrink: 0;
}

.message-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.message-bubble {
  max-width: 60%;
}

.text-message {
  padding: 12px 16px;
  background-color: #f1f5f9; // slate-100
  border-radius: 12px;
  font-size: 15px;
  line-height: 1.5;
}

.message-item.mine .text-message {
  background-color: #dbeafe; // blue-100
}

.chat-input-area {
  border-top: 1px solid #f1f5f9; // slate-100
}

.input-toolbar {
  display: flex;
  padding: 10px 15px;
  background-color: #eff6ff; // blue-50
}

.toolbar-btn {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border-radius: 8px;
  transition: background 0.2s;
}

.toolbar-btn:hover {
  background-color: rgba(255, 255, 255, 0.8);
}

.toolbar-btn .material-icons-round {
  color: #2563eb; // blue-600
}

.input-box {
  display: flex;
  padding: 10px 15px;
  gap: 10px;
}

.input-box textarea {
  flex: 1;
  border: none;
  outline: none;
  resize: none;
  height: 100px;
  font-size: 14px;
  padding: 10px;
}

.chat-placeholder {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #2563eb; // blue-600
}

.placeholder-icon {
  font-size: 80px;
  opacity: 0.3;
  margin-bottom: 20px;
}

.conversation-item:hover .conv-delete,
.conversation-item.active .conv-delete {
  display: flex;
}

.conv-delete {
  display: none;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  font-size: 16px;
  line-height: 1;
  color: #94a3b8;
  flex-shrink: 0;
  margin-left: 4px;
  &:hover {
    background-color: #fee2e2;
    color: #ef4444;
  }
}

.read-status {
  font-size: 11px;
  color: #94a3b8;
  text-align: right;
  margin-top: 4px;
}

.message-item.mine .read-status {
  color: #60a5fa;
}

.recalled-tip {
  font-size: 13px;
  color: #94a3b8;
  font-style: italic;
  padding: 6px 12px;
}

.context-menu {
  position: absolute;
  z-index: 9999;
  background: #fff;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.12);
  min-width: 100px;
  overflow: hidden;
  transform-origin: top left;
  animation: context-menu-in 0.15s ease-out;
}

@keyframes context-menu-in {
  from {
    opacity: 0;
    transform: scale(0.7);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

.context-menu-item {
  padding: 10px 16px;
  font-size: 14px;
  cursor: pointer;
  color: #374151;
  &:hover {
    background-color: #f3f4f6;
  }
  &.danger {
    color: #ef4444;
    &:hover {
      background-color: #fee2e2;
    }
  }
}

.empty-tip {
  text-align: center;
  padding: 50px;
  color: #94a3b8; // slate-400
}
</style>
