<template>
  <BaseLayout>
    <div class="chat-container user-chat">
      <div class="chat-header">
        <h1>运动场地聊天室</h1>
        <div class="user-info">
          <span>{{ currentUsername }}</span>
          <span class="role-badge user-role">{{
            getRoleName(userRoleValue)
          }}</span>
        </div>
      </div>

      <div class="chat-messages" ref="messageContainer">
        <div v-if="loadingHistory" class="loading-more">
          正在加载历史消息...
        </div>
        <button
          v-if="hasMoreHistory"
          class="load-more-btn"
          @click="loadMoreHistory"
          :disabled="loadingHistory"
        >
          {{ loadingHistory ? '加载中...' : '查看历史消息' }}
        </button>

        <div
          v-for="(message, index) in chatMessages"
          :key="index"
          :class="getMessageClass(message)"
        >
          <div class="message-header">
            <span class="sender" :class="getRoleClass(message.senderRole)">{{
              message.sender
            }}</span>
            <span
              class="role-badge"
              :class="getRoleClass(message.senderRole)"
              >{{ message.roleName || getRoleName(message.senderRole) }}</span
            >
            <span class="timestamp">{{
              formatTimestamp(message.timestamp)
            }}</span>
          </div>
          <div class="message-content">
            {{ message.content || message.message }}
          </div>
        </div>
      </div>

      <div class="chat-input">
        <input
          v-model="messageInput"
          placeholder="输入消息..."
          @keyup.enter="sendMessage"
        />
        <button @click="sendMessage" :disabled="!messageInput.trim()">
          发送
        </button>
      </div>
    </div>
  </BaseLayout>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
import { useUserStore } from '@/stores'
import BaseLayout from '@/components/BaseLayout.vue'
const userStore = useUserStore()
const messageContainer = ref(null)
const messageInput = ref('')
const chatMessages = ref([])
const currentUsername = ref('')
const userRoleValue = ref(1) // 默认普通用户角色
const loadingHistory = ref(false)
const hasMoreHistory = ref(true)
const oldestTimestamp = ref(0)

const ws = ref(null)

// 初始化用户信息
onMounted(() => {
  userRoleValue.value = userStore.user.type || 1 // 确保是普通用户角色
  initWebSocket()
})

// 清理WebSocket连接
onBeforeUnmount(() => {
  disconnect()
})

// 监听消息变化，自动滚动到底部
watch(
  chatMessages,
  () => {
    scrollToBottom()
  },
  { deep: true }
)

// 初始化WebSocket连接
const initWebSocket = () => {
  try {
    ws.value = new WebSocket('ws://localhost:9030/ws')

    ws.value.onopen = () => {
      console.log('WebSocket连接已建立')
      login()
    }

    ws.value.onmessage = (event) => {
      try {
        const message = JSON.parse(event.data)

        if (message.type === 'history') {
          handleHistoryMessage(message)
        } else {
          chatMessages.value.push(message)
        }
      } catch (error) {
        console.error('解析消息失败:', error)
        chatMessages.value.push({
          type: 'error',
          message: '收到格式错误的消息'
        })
      }
    }

    ws.value.onclose = () => {
      console.log('WebSocket连接已关闭')
      // 5秒后尝试重连
      setTimeout(initWebSocket, 5000)
    }

    ws.value.onerror = (error) => {
      console.error('WebSocket错误:', error)
      chatMessages.value.push({
        type: 'error',
        message: 'WebSocket连接发生错误'
      })
    }
  } catch (error) {
    console.error('创建WebSocket失败:', error)
    chatMessages.value.push({
      type: 'error',
      message: '无法连接到服务器'
    })
  }
}

// 处理历史消息
const handleHistoryMessage = (message) => {
  loadingHistory.value = false

  if (message.messages && message.messages.length > 0) {
    const formattedMessages = message.messages.map((msg) => ({
      ...msg,
      timestamp: msg.timestamp
        ? new Date(msg.timestamp).toISOString()
        : new Date().toISOString()
    }))

    chatMessages.value.unshift(...formattedMessages)

    const oldestMsg = formattedMessages[formattedMessages.length - 1]
    oldestTimestamp.value = new Date(oldestMsg.timestamp).getTime()
  }

  hasMoreHistory.value = message.hasMore
}

// 加载更多历史消息
const loadMoreHistory = () => {
  if (loadingHistory.value) return

  loadingHistory.value = true
  const loadMessage = {
    type: 'loadHistory',
    username: currentUsername.value,
    lastTimestamp: oldestTimestamp.value,
    pageSize: 20
  }

  ws.value.send(JSON.stringify(loadMessage))
}

// 用户登录
const login = () => {
  currentUsername.value =
    userStore.user.username || '用户' + Math.floor(Math.random() * 1000)

  const loginMessage = {
    type: 'login',
    username: currentUsername.value,
    userRole: userRoleValue.value
  }

  ws.value.send(JSON.stringify(loginMessage))

  chatMessages.value.push({
    type: 'system',
    message: '已成功连接到聊天室',
    timestamp: new Date().toISOString()
  })

  // 初始加载历史消息
  loadMoreHistory()
}

// 发送消息
const sendMessage = () => {
  if (!messageInput.value.trim()) return

  const message = {
    type: 'message',
    username: currentUsername.value,
    userRole: userRoleValue.value,
    content: messageInput.value
  }

  ws.value.send(JSON.stringify(message))
  messageInput.value = ''
}

// 断开连接
const disconnect = () => {
  if (ws.value) {
    ws.value.close()
    ws.value = null
  }
}

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

// 获取消息样式类
const getMessageClass = (message) => {
  if (message.type === 'system') {
    return 'system-message'
  } else if (message.type === 'error') {
    return 'error-message'
  } else {
    return message.sender === currentUsername.value
      ? 'my-message'
      : 'other-message'
  }
}

// 获取角色名称
const getRoleName = () => {
  return '普通用户' // 普通用户界面只显示普通用户角色
}

// 获取角色样式类
const getRoleClass = () => {
  return 'role-user' // 普通用户界面使用统一样式
}

// 格式化时间戳
const formatTimestamp = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
}
</script>
<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 90vh;
  margin: 20px auto;
  border-radius: 8px;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  background-color: white;
}

.chat-header {
  padding: 15px 20px;
  background-color: #4a6fa5;
  color: white;
  border-bottom: 1px solid #ddd;
}

.chat-header h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 500;
}

.user-info {
  margin-top: 5px;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.role-badge {
  margin-left: 10px;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.role-user {
  background-color: rgba(52, 152, 219, 0.2);
  color: #3498db;
}

.role-admin {
  background-color: rgba(230, 126, 34, 0.2);
  color: #e67e22;
}

.role-superadmin {
  background-color: rgba(192, 57, 43, 0.2);
  color: #c0392b;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #f8f9fa;
  display: flex;
  flex-direction: column;
}

.loading-more {
  text-align: center;
  padding: 10px;
  color: #6c757d;
  font-size: 14px;
}

.load-more-btn {
  margin: 10px auto;
  padding: 8px 16px;
  background-color: #4a6fa5;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.load-more-btn:hover {
  background-color: #3a5a80;
}

.load-more-btn:disabled {
  background-color: #e9ecef;
  color: #6c757d;
  cursor: not-allowed;
}

.system-message {
  text-align: center;
  margin: 10px 0;
}

.system-message .message-content {
  display: inline-block;
  padding: 5px 15px;
  background-color: #e9ecef;
  border-radius: 15px;
  color: #6c757d;
  font-size: 14px;
}

.error-message {
  text-align: center;
  margin: 10px 0;
}

.error-message .message-content {
  display: inline-block;
  padding: 5px 15px;
  background-color: #f8d7da;
  border-radius: 15px;
  color: #721c24;
  font-size: 14px;
}

.message {
  margin-bottom: 15px;
  max-width: 80%;
}

.my-message {
  margin-left: auto;
  text-align: right;
}

.message-header {
  margin-bottom: 5px;
  font-size: 14px;
}

.sender {
  font-weight: bold;
}

.timestamp {
  margin-left: 10px;
  color: #6c757d;
  font-size: 12px;
}

.message-content {
  display: inline-block;
  padding: 10px 15px;
  border-radius: 18px;
  font-size: 16px;
  line-height: 1.4;
}

.my-message .message-content {
  background-color: #4a6fa5;
  color: white;
  text-align: left;
}

.other-message .message-content {
  background-color: #e9ecef;
  color: #212529;
}

.chat-input {
  display: flex;
  padding: 15px 20px;
  background-color: white;
  border-top: 1px solid #ddd;
}

.chat-input input {
  flex: 1;
  padding: 10px 15px;
  margin-right: 15px;
  border: 1px solid #ddd;
  border-radius: 20px;
  font-size: 16px;
  outline: none;
}

.chat-input input:focus {
  border-color: #4a6fa5;
  box-shadow: 0 0 0 2px rgba(74, 111, 165, 0.2);
}

.chat-input button {
  padding: 10px 20px;
  background-color: #4a6fa5;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
}

.chat-input button:hover {
  background-color: #3a5a80;
}

.chat-input button:disabled {
  background-color: #e9ecef;
  color: #6c757d;
  cursor: not-allowed;
}
</style>
