<template>
  <div class="chat-container">
    <!-- 聊天头部 -->
    <div class="chat-header">
      <h3>在线聊天</h3>
      <span class="chat-info">
        {{ isUser ? '正在与商家对话' : '正在与用户对话' }}
      </span>
    </div>

    <!-- 消息列表 -->
    <div class="chat-messages" ref="messagesContainer">
      <div v-if="loading" class="loading">
        <el-icon class="is-loading"><Loading /></el-icon>
        加载中...
      </div>
      <div v-else-if="messages.length === 0" class="no-messages">
        <el-empty description="暂无聊天记录，开始对话吧" />
      </div>
      <div v-else>
        <div 
          v-for="message in messages" 
          :key="message.messageId"
          :class="['message', { 'own': message.senderId == currentUserId }]"
        >
          <div class="message-bubble">
            {{ message.messageContent }}
          </div>
          <div class="message-time">
            {{ formatTime(message.createdAt) }}
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="chat-input">
      <el-input
        v-model="newMessage"
        @keyup.enter="sendMessage"
        placeholder="输入消息..."
        :disabled="!connected"
        clearable
      >
        <template #append>
          <el-button 
            @click="sendMessage"
            :disabled="!connected || !newMessage.trim()"
            type="primary"
          >
            发送
          </el-button>
        </template>
      </el-input>
    </div>

    <!-- 连接状态提示 -->
    <el-alert
      v-if="!connected"
      title="连接中..."
      type="warning"
      :closable="false"
      show-icon
      class="connection-alert"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import SockJS from 'sockjs-client'
import { Client, StompSubscription } from '@stomp/stompjs'
import axios from 'axios'

// 接口定义
interface ChatMessage {
  messageId: number
  conversationId: number
  senderId: number
  senderType: string
  messageContent: string
  messageType?: string
  isRead?: number
  createdAt: string
}

interface Conversation {
  conversationId: number
  userId: number
  merchantId: number
  lastMessageId?: number
  lastMessageContent?: string
  lastMessageTime?: string
  userUnreadCount: number
  merchantUnreadCount: number
  status: string
}

// 响应式数据
const userId = ref<number | null>(null)
const merchantId = ref<number | null>(null)
const currentUserId = ref<number | null>(null)
const isUser = ref(true)
const conversationId = ref<number | null>(null)
const messages = ref<ChatMessage[]>([])
const newMessage = ref('')
const loading = ref(false)
const connected = ref(false)

// DOM引用
const messagesContainer = ref<HTMLElement>()

// WebSocket相关
let stompClient: Client | null = null
let subscription: StompSubscription | null = null
let reconnectInterval: number | null = null

// API基础URL
const API_BASE_URL = 'http://localhost:8080'

// 生命周期
onMounted(() => {
  initParams()
  if (validateParams()) {
    initChat()
  }
})

onUnmounted(() => {
  disconnect()
})

// 初始化URL参数
const initParams = () => {
  const urlParams = new URLSearchParams(window.location.search)
  userId.value = Number(urlParams.get('userId'))
  merchantId.value = Number(urlParams.get('merchantId'))
  currentUserId.value = Number(urlParams.get('currentUserId'))
  isUser.value = urlParams.get('type') === 'user'
}

// 验证参数
const validateParams = (): boolean => {
  if (!userId.value || !merchantId.value || !currentUserId.value) {
    ElMessage.error('缺少必要参数：userId, merchantId, currentUserId')
    return false
  }
  return true
}

// 初始化聊天
const initChat = async () => {
  try {
    await getOrCreateConversation()
    await loadChatHistory()
    connectWebSocket()
  } catch (error) {
    console.error('初始化聊天失败', error)
    ElMessage.error('初始化聊天失败，请刷新重试')
  }
}

// 获取或创建会话
const getOrCreateConversation = async () => {
  try {
    const response = await axios.post(`${API_BASE_URL}/api/chat/conversation/create`, {
      userId: userId.value,
      merchantId: merchantId.value
    })
    
    if (response.data.code === 200) {
      conversationId.value = response.data.data.conversationId
    } else {
      throw new Error('创建会话失败')
    }
  } catch (error) {
    console.error('创建会话失败', error)
    throw error
  }
}

// 加载聊天历史
const loadChatHistory = async () => {
  if (!conversationId.value) return
  
  loading.value = true
  try {
    const response = await axios.get(
      `${API_BASE_URL}/api/chat/history/${conversationId.value}`,
      { params: { page: 1, size: 50 } }
    )
    
    if (response.data.code === 200) {
      messages.value = response.data.data.reverse()
      await nextTick()
      scrollToBottom()
    }
  } catch (error) {
    console.error('加载聊天记录失败', error)
    ElMessage.error('加载聊天记录失败')
  } finally {
    loading.value = false
  }
}

// 连接WebSocket
const connectWebSocket = () => {
  stompClient = new Client({
    webSocketFactory: () => new SockJS(`${API_BASE_URL}/ws`),
    
    onConnect: () => {
      console.log('WebSocket连接成功')
      connected.value = true
      
      // 清除重连定时器
      if (reconnectInterval) {
        clearInterval(reconnectInterval)
        reconnectInterval = null
      }
      
      // 订阅个人消息队列
      subscription = stompClient!.subscribe(
        `/user/${currentUserId.value}/queue/messages`,
        (message) => {
          const chatMessage: ChatMessage = JSON.parse(message.body)
          
          // 只接收当前会话的消息，并且过滤掉自己发送的消息
          if (chatMessage.conversationId === conversationId.value) {
            // 检查是否是自己发送的消息（通过发送者ID判断）
            if (chatMessage.senderId !== currentUserId.value) {
              messages.value.push(chatMessage)
              nextTick(() => {
                scrollToBottom()
              })
            }
          }
        }
      )
    },
    
    onStompError: (frame) => {
      console.error('STOMP错误', frame)
      connected.value = false
      reconnect()
    },
    
    onWebSocketError: (error) => {
      console.error('WebSocket错误', error)
      connected.value = false
      reconnect()
    }
  })
  
  // 激活连接
  stompClient.activate()
}

// 重连机制
const reconnect = () => {
  if (!reconnectInterval) {
    reconnectInterval = window.setInterval(() => {
      console.log('尝试重新连接...')
      if (stompClient && !stompClient.active) {
        stompClient.activate()
      }
    }, 5000)
  }
}

// 断开连接
const disconnect = () => {
  if (reconnectInterval) {
    clearInterval(reconnectInterval)
  }
  if (subscription) {
    subscription.unsubscribe()
  }
  if (stompClient && stompClient.active) {
    stompClient.deactivate()
  }
}

// 发送消息
const sendMessage = () => {
  if (!newMessage.value.trim() || !connected.value || !stompClient) return
  
  const message = {
    senderId: currentUserId.value,
    receiverId: isUser.value ? merchantId.value : userId.value,
    senderType: isUser.value ? 'user' : 'merchant',
    content: newMessage.value.trim()
  }
  
  // 通过WebSocket发送
  stompClient.publish({
    destination: '/app/chat.send',
    body: JSON.stringify(message)
  })
  
  // 立即显示在界面上（乐观更新）
  messages.value.push({
    messageId: Date.now(),
    conversationId: conversationId.value!,
    senderId: currentUserId.value!,
    senderType: message.senderType,
    messageContent: newMessage.value.trim(),
    createdAt: new Date().toISOString()
  })
  
  newMessage.value = ''
  nextTick(() => {
    scrollToBottom()
  })
}

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 格式化时间
const formatTime = (time: string): string => {
  if (!time) return ''
  const date = new Date(time)
  const now = new Date()
  
  // 今天的消息只显示时间
  if (date.toDateString() === now.toDateString()) {
    return date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    })
  }
  
  // 昨天
  const yesterday = new Date(now)
  yesterday.setDate(yesterday.getDate() - 1)
  if (date.toDateString() === yesterday.toDateString()) {
    return '昨天 ' + date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    })
  }
  
  // 更早的消息显示日期
  return date.toLocaleDateString('zh-CN') + ' ' + 
         date.toLocaleTimeString('zh-CN', { 
           hour: '2-digit', 
           minute: '2-digit' 
         })
}
</script>

<style scoped lang="scss">
.chat-container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
  position: relative;
}

.chat-header {
  background: #fff;
  padding: 15px 20px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);

  h3 {
    margin: 0;
    font-size: 18px;
    color: #333;
  }

  .chat-info {
    font-size: 14px;
    color: #666;
  }
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #fff;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    background: #f1f1f1;
  }

  &::-webkit-scrollbar-thumb {
    background: #888;
    border-radius: 3px;

    &:hover {
      background: #555;
    }
  }
}

.loading, .no-messages {
  text-align: center;
  color: #999;
  padding: 40px;
  font-size: 14px;
}

.message {
  margin-bottom: 15px;
  display: flex;
  flex-direction: column;

  &.own {
    align-items: flex-end;

    .message-bubble {
      background: #409eff;
      color: white;
    }
  }

  .message-bubble {
    max-width: 70%;
    padding: 10px 15px;
    border-radius: 18px;
    background: #f0f0f0;
    color: #333;
    word-wrap: break-word;
    font-size: 14px;
    line-height: 1.4;
  }

  .message-time {
    font-size: 12px;
    color: #999;
    margin-top: 5px;
    padding: 0 5px;
  }
}

.chat-input {
  padding: 15px;
  background: #fff;
  border-top: 1px solid #e0e0e0;

  :deep(.el-input-group__append) {
    background-color: transparent;
    border: none;
    padding: 0 5px;
  }
}

.connection-alert {
  position: absolute;
  top: 70px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 100;
}

// 响应式布局
@media (max-width: 768px) {
  .message-bubble {
    max-width: 85%;
  }
  
  .chat-header h3 {
    font-size: 16px;
  }
  
  .chat-input {
    padding: 10px;
  }
}
</style>
