<template>
  <div class="instant-message-container">
    <!-- 对话列表 -->
    <div class="conversation-list">
      <div class="conversation-header">
        <h3>对话</h3>
        <div class="search-box">
          <input type="text" placeholder="搜索对话" v-model="searchKeyword" />
          <img src="/images/profile/message.png" alt="搜索" class="search-icon" />
        </div>
      </div>
      
      <div class="conversation-items">
        <div 
          v-for="conversation in filteredConversations" 
          :key="conversation.id"
          :class="['conversation-item', { active: selectedConversation?.id === conversation.id }]"
          @click="selectConversation(conversation)"
        >
          <div class="avatar-container">
            <img :src="conversation.avatar" :alt="conversation.name" class="conversation-avatar" />
            <div v-if="conversation.unreadCount > 0" class="unread-badge">{{ conversation.unreadCount }}</div>
          </div>
          <div class="conversation-info">
            <div class="conversation-name">{{ conversation.name }}</div>
            <div class="last-message">{{ conversation.lastMessage }}</div>
          </div>
          <div class="conversation-meta">
            <div class="last-time">{{ conversation.lastTime }}</div>
            <div v-if="conversation.isOnline" class="online-indicator"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 聊天区域 -->
    <div class="chat-area">
      <div v-if="!selectedConversation" class="no-conversation">
        <img src="/images/profile/message.png" alt="选择对话" class="placeholder-image" />
        <p>选择一个对话开始聊天</p>
      </div>
      
      <div v-else class="chat-container">
        <!-- 聊天头部 -->
        <div class="chat-header">
          <div class="chat-user-info">
            <img :src="selectedConversation.avatar" :alt="selectedConversation.name" class="chat-avatar" />
            <div class="chat-user-details">
              <div class="chat-user-name">{{ selectedConversation.name }}</div>
              <div class="chat-user-status">{{ selectedConversation.isOnline ? '在线' : '离线' }}</div>
            </div>
          </div>
          <div class="chat-actions">
            <button class="chat-action-btn">
              <img src="/images/profile/message.png" alt="视频通话" />
            </button>
            <button class="chat-action-btn">
              <img src="/images/profile/message.png" alt="语音通话" />
            </button>
            <button class="chat-action-btn">
              <img src="/images/profile/message.png" alt="更多" />
            </button>
          </div>
        </div>

        <!-- 消息列表 -->
        <div class="messages-container" ref="messagesContainer">
          <div v-for="message in selectedConversation.messages" :key="message.id" 
               :class="['message-item', message.isSelf ? 'message-self' : 'message-other']">
            <div v-if="!message.isSelf" class="message-avatar">
              <img :src="selectedConversation.avatar" :alt="selectedConversation.name" />
            </div>
            <div class="message-content">
              <div class="message-bubble">
                <div v-if="message.type === 'text'" class="message-text">{{ message.content }}</div>
                <div v-else-if="message.type === 'image'" class="message-image">
                  <img :src="message.content" alt="图片" />
                </div>
                <div v-else-if="message.type === 'file'" class="message-file">
                  <img src="/images/profile/message.png" alt="文件" />
                  <span>{{ message.fileName }}</span>
                </div>
              </div>
              <div class="message-time">{{ message.time }}</div>
            </div>
            <div v-if="message.isSelf" class="message-avatar">
              <img src="/images/profile/profile.png" alt="我" />
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="input-area">
          <div class="input-toolbar">
            <button class="toolbar-btn" @click="showEmojiPicker = !showEmojiPicker">
              <img src="/images/profile/message.png" alt="表情" />
            </button>
            <button class="toolbar-btn" @click="selectFile">
              <img src="/images/profile/message.png" alt="附件" />
            </button>
            <button class="toolbar-btn">
              <img src="/images/profile/message.png" alt="图片" />
            </button>
          </div>
          <div class="input-container">
            <textarea 
              v-model="messageInput" 
              placeholder="输入消息..." 
              @keydown.enter.prevent="sendMessage"
              @input="adjustTextareaHeight"
              ref="messageTextarea"
              rows="1"
            ></textarea>
            <button class="send-btn" @click="sendMessage" :disabled="!messageInput.trim()">
              发送
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick, onMounted } from 'vue'

// 消息类型
interface Message {
  id: number
  type: 'text' | 'image' | 'file'
  content: string
  fileName?: string
  time: string
  isSelf: boolean
}

// 对话类型
interface Conversation {
  id: number
  name: string
  avatar: string
  lastMessage: string
  lastTime: string
  unreadCount: number
  isOnline: boolean
  messages: Message[]
}

// 响应式数据
const searchKeyword = ref('')
const selectedConversation = ref<Conversation | null>(null)
const messageInput = ref('')
const showEmojiPicker = ref(false)
const messagesContainer = ref<HTMLElement>()
const messageTextarea = ref<HTMLTextAreaElement>()

// 模拟对话数据
const conversations = ref<Conversation[]>([
  {
    id: 1,
    name: '张老师',
    avatar: '/images/traings/traing1.png',
    lastMessage: '好的，我知道了',
    lastTime: '14:30',
    unreadCount: 2,
    isOnline: true,
    messages: [
      { id: 1, type: 'text', content: '你好，有什么问题吗？', time: '14:25', isSelf: false },
      { id: 2, type: 'text', content: '我想问一下关于课程的问题', time: '14:26', isSelf: true },
      { id: 3, type: 'text', content: '好的，请说', time: '14:27', isSelf: false },
      { id: 4, type: 'text', content: '这个作业的截止时间是什么时候？', time: '14:28', isSelf: true },
      { id: 5, type: 'text', content: '下周五晚上12点前提交', time: '14:29', isSelf: false },
      { id: 6, type: 'text', content: '好的，我知道了', time: '14:30', isSelf: true }
    ]
  },
  {
    id: 2,
    name: '李同学',
    avatar: '/images/traings/traing2.png',
    lastMessage: '谢谢你的帮助',
    lastTime: '昨天',
    unreadCount: 0,
    isOnline: false,
    messages: [
      { id: 1, type: 'text', content: '能帮我看看这道题吗？', time: '昨天 16:20', isSelf: false },
      { id: 2, type: 'text', content: '当然可以，发过来看看', time: '昨天 16:21', isSelf: true },
      { id: 3, type: 'image', content: '/images/homework/question1.png', time: '昨天 16:22', isSelf: false },
      { id: 4, type: 'text', content: '这道题需要用到递归的思想...', time: '昨天 16:25', isSelf: true },
      { id: 5, type: 'text', content: '谢谢你的帮助', time: '昨天 16:30', isSelf: false }
    ]
  },
  {
    id: 3,
    name: '王助教',
    avatar: '/images/traings/traing3.png',
    lastMessage: '课程资料已发送',
    lastTime: '2天前',
    unreadCount: 1,
    isOnline: true,
    messages: [
      { id: 1, type: 'text', content: '你好，这是本周的课程资料', time: '2天前 10:00', isSelf: false },
      { id: 2, type: 'file', content: '/files/course-material.pdf', fileName: '第三章课程资料.pdf', time: '2天前 10:01', isSelf: false },
      { id: 3, type: 'text', content: '课程资料已发送', time: '2天前 10:02', isSelf: false }
    ]
  }
])

// 过滤对话
const filteredConversations = computed(() => {
  if (!searchKeyword.value) return conversations.value
  return conversations.value.filter(conv => 
    conv.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

// 选择对话
const selectConversation = (conversation: Conversation) => {
  selectedConversation.value = conversation
  // 清除未读消息
  conversation.unreadCount = 0
  // 滚动到底部
  nextTick(() => {
    scrollToBottom()
  })
}

// 发送消息
const sendMessage = () => {
  if (!messageInput.value.trim() || !selectedConversation.value) return
  
  const newMessage: Message = {
    id: Date.now(),
    type: 'text',
    content: messageInput.value.trim(),
    time: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
    isSelf: true
  }
  
  selectedConversation.value.messages.push(newMessage)
  selectedConversation.value.lastMessage = newMessage.content
  selectedConversation.value.lastTime = newMessage.time
  
  messageInput.value = ''
  
  // 滚动到底部
  nextTick(() => {
    scrollToBottom()
    resetTextareaHeight()
  })
}

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

// 调整文本框高度
const adjustTextareaHeight = () => {
  if (messageTextarea.value) {
    messageTextarea.value.style.height = 'auto'
    messageTextarea.value.style.height = Math.min(messageTextarea.value.scrollHeight, 120) + 'px'
  }
}

// 重置文本框高度
const resetTextareaHeight = () => {
  if (messageTextarea.value) {
    messageTextarea.value.style.height = 'auto'
  }
}

// 选择文件
const selectFile = () => {
  // 这里可以实现文件选择逻辑
  console.log('选择文件')
}

// 组件挂载时默认选择第一个对话
onMounted(() => {
  if (conversations.value.length > 0) {
    selectConversation(conversations.value[0])
  }
})
</script>

<style scoped>
.instant-message-container {
  display: flex;
  height: 600px;
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  overflow: hidden;
}

/* 对话列表样式 */
.conversation-list {
  width: 300px;
  border-right: 1px solid #e6e6e6;
  display: flex;
  flex-direction: column;
}

.conversation-header {
  padding: 16px;
  border-bottom: 1px solid #e6e6e6;
}

.conversation-header h3 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
}

.search-box {
  position: relative;
}

.search-box input {
  width: 100%;
  padding: 8px 32px 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  font-size: 14px;
}

.search-icon {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  width: 16px;
  height: 16px;
}

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

.conversation-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.2s;
}

.conversation-item:hover {
  background-color: #f5f5f5;
}

.conversation-item.active {
  background-color: #e6f7ff;
}

.avatar-container {
  position: relative;
  margin-right: 12px;
}

.conversation-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.unread-badge {
  position: absolute;
  top: -4px;
  right: -4px;
  background: #ff4d4f;
  color: white;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 10px;
  min-width: 16px;
  text-align: center;
}

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

.conversation-name {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 4px;
}

.last-message {
  font-size: 12px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.conversation-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
}

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

.online-indicator {
  width: 8px;
  height: 8px;
  background: #52c41a;
  border-radius: 50%;
}

/* 聊天区域样式 */
.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.no-conversation {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
}

.placeholder-image {
  width: 120px;
  height: 120px;
  margin-bottom: 16px;
  opacity: 0.5;
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chat-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #e6e6e6;
}

.chat-user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.chat-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.chat-user-name {
  font-size: 16px;
  font-weight: 500;
}

.chat-user-status {
  font-size: 12px;
  color: #52c41a;
}

.chat-actions {
  display: flex;
  gap: 8px;
}

.chat-action-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: none;
  cursor: pointer;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chat-action-btn:hover {
  background-color: #f5f5f5;
}

.chat-action-btn img {
  width: 20px;
  height: 20px;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.message-item {
  display: flex;
  gap: 8px;
}

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

.message-avatar img {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
}

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

.message-self .message-content {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.message-bubble {
  padding: 8px 12px;
  border-radius: 12px;
  word-wrap: break-word;
}

.message-other .message-bubble {
  background-color: #f0f0f0;
  border-bottom-left-radius: 4px;
}

.message-self .message-bubble {
  background-color: #1890ff;
  color: white;
  border-bottom-right-radius: 4px;
}

.message-text {
  line-height: 1.4;
}

.message-image img {
  max-width: 200px;
  border-radius: 8px;
}

.message-file {
  display: flex;
  align-items: center;
  gap: 8px;
}

.message-file img {
  width: 24px;
  height: 24px;
}

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

.input-area {
  border-top: 1px solid #e6e6e6;
  padding: 16px;
}

.input-toolbar {
  display: flex;
  gap: 8px;
  margin-bottom: 8px;
}

.toolbar-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: none;
  cursor: pointer;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.toolbar-btn:hover {
  background-color: #f5f5f5;
}

.toolbar-btn img {
  width: 20px;
  height: 20px;
}

.input-container {
  display: flex;
  gap: 8px;
  align-items: flex-end;
}

.input-container textarea {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  resize: none;
  font-family: inherit;
  font-size: 14px;
  line-height: 1.4;
  min-height: 36px;
  max-height: 120px;
}

.send-btn {
  padding: 8px 16px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  height: 36px;
}

.send-btn:disabled {
  background-color: #d9d9d9;
  cursor: not-allowed;
}

.send-btn:not(:disabled):hover {
  background-color: #40a9ff;
}
</style>
