MessageDetail.vue 16.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
<template>
  <nut-popup v-model:visible="visible" position="right" :style="{ width: '100%', height: '100%' }" closeable
    close-icon-position="top-right" @close="handleClose">
    <view class="message-detail-container">
      <!-- 详情页头部 -->
      <view class="detail-header">
        <view class="flex items-center">
          <image v-if="conversation?.avatar" :src="conversation.avatar" class="w-12 h-12 rounded-full object-cover mr-3"
            mode="aspectFill" />
          <view v-else class="w-12 h-12 rounded-full bg-gray-100 flex items-center justify-center mr-3">
            <component :is="conversation?.icon" />
          </view>
          <view class="flex-1">
            <text class="text-lg font-medium">{{ conversation?.name }}</text>
            <text class="text-sm text-gray-500 block">{{ conversation?.time }}</text>
          </view>
        </view>
      </view>

      <!-- 消息内容区域 -->
      <view class="detail-content">
        <!-- 系统通知样式 -->
        <view v-if="conversation?.type === 'system'" class="system-content">
          <view class="message-content">
            <view class="message-title" v-if="conversation?.title">
              <text class="text-lg font-medium">{{ conversation.title }}</text>
            </view>
            <view class="message-body">
              <text class="text-base">{{ conversation?.note || conversation?.lastMessage }}</text>
            </view>
            <view class="message-meta" v-if="conversation?.created_time_desc">
              <text class="text-sm text-gray-500">发布时间:{{ conversation.created_time_desc }}</text>
            </view>
          </view>
        </view>

        <!-- 聊天记录样式 -->
        <view v-else class="chat-content">
          <scroll-view class="chat-messages" :scroll-y="true" :scroll-top="scrollTop" :scroll-into-view="scrollIntoView"
            :refresher-enabled="true" :refresher-triggered="isLoadingMessages" @refresherrefresh="handleRefresh">
            <!-- 数据加载完成提示 -->
            <view v-if="!hasMoreMessages && !isInitialLoad && messages.length > 0 && hasTriedLoadMore"
              class="load-complete-tip">
              <text class="tip-text">已加载完所有数据</text>
            </view>

            <view v-for="(message, index) in messages" :key="index" :id="`msg-${index}`" class="message-item" :class="{
              'message-sent': message.type === 'sent',
              'message-received': message.type === 'received'
            }">
              <view class="message-bubble">
                <text class="message-text">{{ message.content }}</text>
                <text class="message-time">{{ message.time }}</text>
              </view>
            </view>
          </scroll-view>

          <!-- 输入框区域 -->
          <view class="chat-input-area">
            <view class="input-container">
              <textarea v-model="inputMessage" placeholder="请输入回复内容..." :rows="2" :max-length="500"
                :cursorSpacing="50" class="message-input" @focus="handleInputFocus" />
              <nut-button type="primary" size="small" color="orange" @click="sendMessage"
                :disabled="!inputMessage.trim() || isSending" class="send-button">
                {{ isSending ? '发送中...' : '发送' }}
              </nut-button>
            </view>
          </view>
        </view>
      </view>

      <!-- 底部按钮 -->
      <!-- <view class="detail-footer">
        <nut-button type="primary" size="large" block @click="handleClose" color="orange">
          {{ conversation?.type === 'system' ? '关闭' : '返回' }}
        </nut-button>
      </view> -->
    </view>
  </nut-popup>
</template>

<script setup>
import { ref, computed, watch, nextTick } from 'vue'
import Taro from '@tarojs/taro'
import { sendChatAPI, getChatListAPI } from '@/api/chat'
import { useUserStore } from '@/stores/user'

/**
 * 消息详情组件 Props
 */
const props = defineProps({
  // 弹框显示状态
  modelValue: {
    type: Boolean,
    default: false
  },
  // 当前对话信息
  conversation: {
    type: Object,
    default: () => ({})
  }
})

/**
 * 组件事件
 */
const emit = defineEmits(['update:modelValue', 'close', 'sendMessage'])

// 弹框显示状态
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 输入消息内容
const inputMessage = ref('')
// 发送状态标记
const isSending = ref(false)

// 滚动相关
const scrollTop = ref(0)
const scrollIntoView = ref('')

// 聊天消息数据
const messages = ref([])

// 分页相关状态
const PAGE_SIZE = 20 // 每页加载的消息数量
const currentPage = ref(0)
const hasMoreMessages = ref(true)
const isLoadingMessages = ref(false)
const isInitialLoad = ref(true)
const hasTriedLoadMore = ref(false) // 是否已经尝试过手动上拉加载更多

/**
 * 加载聊天消息
 * @param {boolean} isLoadMore - 是否为加载更多(下拉加载历史记录)
 */
const loadChatMessages = async (isLoadMore = false) => {
  if (props.conversation?.type !== 'chat' || !props.conversation?.id) {
    return
  }

  // 如果正在加载,则不继续加载
  if (isLoadingMessages.value) {
    return
  }

  // 对于scrolltoupper事件,如果没有更多消息则不加载
  // 但对于下拉刷新,总是允许尝试加载
  if (!hasMoreMessages.value && isLoadMore && !isInitialLoad.value) {
    // 这里可以根据具体需求决定是否允许重新加载
  }

  const userStore = useUserStore()
  const currentUserId = userStore.userInfo?.id

  try {
    isLoadingMessages.value = true

    // 如果是加载更多,页码+1
    const page = isLoadMore ? currentPage.value + 1 : 0

    const response = await getChatListAPI({
      conversation_id: props.conversation.id,
      page: page,
      limit: PAGE_SIZE
    })

    if (response.code && response.data) {
      const newMessages = (response.data.list || []).reverse() // 逆序排列,因为后端无法处理排序要求

      // 转换API数据格式为组件需要的格式
      const formattedMessages = newMessages.map(msg => ({
        type: msg.created_by === currentUserId ? 'sent' : 'received',
        content: msg.note || '',
        time: msg.created_time_desc || '',
        id: msg.id,
        created_by: msg.created_by,
        create_time: msg.create_time
      }))

      if (isLoadMore) {
        // 加载更多时,将新消息添加到列表顶部(历史消息)
        messages.value = [...formattedMessages, ...messages.value]
        currentPage.value = page
      } else {
        // 初始加载时,直接设置消息列表
        messages.value = formattedMessages
        currentPage.value = 0
        isInitialLoad.value = false
      }

      // 判断是否还有更多消息
      hasMoreMessages.value = newMessages.length >= PAGE_SIZE

      // 如果没有任何消息,显示欢迎消息
      if (messages.value.length === 0 && !isLoadMore) {
        messages.value = [
          {
            type: 'received',
            content: '您好,有什么可以帮助您的吗?',
            time: new Date().toLocaleTimeString('zh-CN', {
              hour: '2-digit',
              minute: '2-digit'
            })
          }
        ]
      }
    }
  } catch (error) {
    console.error('加载聊天消息失败:', error)
    Taro.showToast({
      title: '加载消息失败',
      icon: 'error'
    })
  } finally {
    isLoadingMessages.value = false
  }
}

/**
 * 发送消息
 */
const sendMessage = async () => {
  if (!inputMessage.value.trim()) {
    Taro.showToast({
      title: '请输入消息内容',
      icon: 'none'
    })
    return
  }

  // 防止重复发送
  if (isSending.value) {
    return
  }

  // 只有聊天类型才能发送消息
  if (props.conversation?.type !== 'chat') {
    Taro.showToast({
      title: '系统消息无法回复',
      icon: 'none'
    })
    return
  }

  const messageContent = inputMessage.value.trim()

  // 设置发送状态并立即清空输入框
  isSending.value = true
  inputMessage.value = ''
  await nextTick() // 确保输入框立即清空

  try {
    // 先添加到本地显示(新消息添加到末尾)
    const newMessage = {
      type: 'sent',
      content: messageContent,
      time: new Date().toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })
    }
    messages.value.push(newMessage)

    // 滚动到底部
    await nextTick()
    scrollToBottom()

    // 调用API发送消息
    const response = await sendChatAPI({
      conversation_id: props.conversation.id,
      note: messageContent
    })

    if (response.code) {
      // 发送成功,更新消息ID
      if (response.data && response.data.id) {
        newMessage.id = response.data.id
      }

      // // 添加自动回复提示消息
      // setTimeout(() => {
      //   const autoReplyMessage = {
      //     type: 'received',
      //     content: '您的消息已发送,我们会尽快回复您,请耐心等待。',
      //     time: new Date().toLocaleTimeString('zh-CN', {
      //       hour: '2-digit',
      //       minute: '2-digit'
      //     }),
      //     isAutoReply: true // 标记为自动回复消息
      //   }
      //   messages.value.push(autoReplyMessage)

      //   // 滚动到底部显示新消息
      //   nextTick(() => {
      //     scrollToBottom()
      //   })
      // }, 1000) // 延迟1秒显示自动回复

      // 触发发送消息事件,通知父组件更新列表
      emit('sendMessage', {
        conversation: props.conversation,
        message: messageContent
      })

      Taro.showToast({
        title: '发送成功',
        icon: 'success'
      })
    } else {
      // 发送失败,移除本地消息
      messages.value.pop()
      // 只在真正失败时才恢复输入框内容,避免闪烁
      await nextTick()
      inputMessage.value = messageContent
      Taro.showToast({
        title: response.msg || '发送失败',
        icon: 'error'
      })
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    // 发送失败,移除本地消息
    messages.value.pop()
    // 只在真正失败时才恢复输入框内容,避免闪烁
    await nextTick()
    inputMessage.value = messageContent
    Taro.showToast({
      title: '发送失败',
      icon: 'error'
    })
  } finally {
    // 重置发送状态
    isSending.value = false
  }
}

/**
 * 处理下拉刷新
 */
const handleRefresh = async () => {
  if (!isLoadingMessages.value) {
    hasTriedLoadMore.value = true // 标记用户已经尝试手动加载更多
    await loadChatMessages(true)
  }
  // 确保刷新状态被重置
  setTimeout(() => {
    isLoadingMessages.value = false
  }, 100)
}

/**
 * 滚动到底部
 */
const scrollToBottom = () => {
  if (messages.value.length > 0) {
    // 先重置 scrollIntoView,然后设置新值确保滚动触发
    scrollIntoView.value = ''
    nextTick(() => {
      setTimeout(() => {
        scrollIntoView.value = `msg-${messages.value.length - 1}`
      }, 100)
    })
  }
}

/**
 * 输入框获得焦点
 */
const handleInputFocus = () => {
  setTimeout(() => {
    scrollToBottom()
  }, 300)
}

/**
 * 关闭弹框
 */
const handleClose = () => {
  visible.value = false
  inputMessage.value = ''
  // 重置滚动相关状态
  scrollTop.value = 0
  scrollIntoView.value = ''
  messages.value = []
  // 重置分页状态
  currentPage.value = 0
  hasMoreMessages.value = true
  isLoadingMessages.value = false
  isInitialLoad.value = true
  hasTriedLoadMore.value = false // 重置手动加载标记
  emit('close')
}

/**
 * 监听对话变化,加载消息
 */
watch(
  () => props.conversation,
  async (newConversation) => {
    if (newConversation && visible.value) {
      // 重置状态
      currentPage.value = 0
      hasMoreMessages.value = true
      isInitialLoad.value = true
      hasTriedLoadMore.value = false // 重置手动加载标记

      await loadChatMessages()
      // 延迟滚动确保消息渲染完成
      setTimeout(() => {
        nextTick(() => {
          scrollToBottom()
        })
      }, 200)
    }
  },
  { immediate: true }
)

/**
 * 监听弹框显示状态
 */
watch(visible, async (newVisible) => {
  if (newVisible && props.conversation) {
    // 重置状态
    currentPage.value = 0
    hasMoreMessages.value = true
    isInitialLoad.value = true
    hasTriedLoadMore.value = false // 重置手动加载标记

    await loadChatMessages()
    // 确保弹框完全打开后再滚动到底部
    setTimeout(() => {
      nextTick(() => {
        scrollToBottom()
      })
    }, 300)
  }
})
</script>

<style lang="less">
.message-detail-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #ffffff;
}

.detail-header {
  padding: 32rpx 24rpx;
  border-bottom: 1rpx solid #f0f0f0;
  background: #ffffff;
  flex-shrink: 0;
}

.detail-content {
  flex: 1;
  overflow: hidden;
  background: #f8f9fa;
}

// 系统通知样式
.system-content {
  padding: 24rpx;
  height: 100%;
  overflow-y: auto;

  .message-content {
    background: #ffffff;
    padding: 24rpx;
    border-radius: 16rpx;
    margin-bottom: 24rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);

    .message-title {
      margin-bottom: 16rpx;
      padding-bottom: 12rpx;
      border-bottom: 1rpx solid #f0f0f0;
    }

    .message-body {
      line-height: 1.6;
      margin-bottom: 16rpx;
    }

    .message-meta {
      padding-top: 12rpx;
      border-top: 1rpx solid #f0f0f0;
    }
  }
}

// 聊天记录样式
.chat-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chat-messages {
  flex: 1;
  padding: 24rpx;
  overflow-y: auto;
}

// 数据加载完成提示样式
.load-complete-tip {
  text-align: center;
  padding: 20rpx 0;
  margin-bottom: 16rpx;

  .tip-text {
    font-size: 24rpx;
    color: #999999;
    background: #f5f5f5;
    padding: 12rpx 24rpx;
    border-radius: 20rpx;
    display: inline-block;
  }
}

.message-item {
  margin-bottom: 24rpx;
  display: flex;
  padding: 0 8rpx; // 添加左右内边距防止遮挡

  &.message-sent {
    justify-content: flex-end;
    padding-right: 60rpx; // 右侧消息增加右边距

    .message-bubble {
      background: #f97416be;
      color: #ffffff;
      border-radius: 20rpx 20rpx 8rpx 20rpx;
      max-width: 65%; // 减少最大宽度,留出更多空间
    }
  }

  &.message-received {
    justify-content: flex-start;
    padding-left: 16rpx; // 左侧消息增加左边距

    .message-bubble {
      background: #ffffff;
      color: #333333;
      border-radius: 20rpx 20rpx 20rpx 8rpx;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
      max-width: 65%; // 减少最大宽度,保持一致
    }
  }
}

.message-bubble {
  padding: 16rpx 20rpx;
  position: relative;
  word-wrap: break-word;
  overflow-wrap: break-word;
}

.message-text {
  font-size: 30rpx;
  line-height: 1.5;
  word-break: break-word;
  display: block;
}

.message-time {
  font-size: 22rpx;
  opacity: 0.7;
  margin-top: 8rpx;
  display: block;
}

.chat-input-area {
  background: #ffffff;
  border-top: 1rpx solid #f0f0f0;
  flex-shrink: 0;
}

.input-container {
  padding: 30rpx;
  display: flex;
  align-items: flex-end;
  gap: 16rpx;
}

.message-input {
  flex: 1;
  min-height: 80rpx;
  max-height: 160rpx;
}

.send-button {
  height: 70rpx;
  padding: 0 48rpx;
  flex-shrink: 0;
}

.detail-footer {
  padding: 24rpx;
  background: #ffffff;
  border-top: 1rpx solid #f0f0f0;
  flex-shrink: 0;
}

// Tailwind CSS 类的补充样式
// .w-12 {
//   width: 88rpx;
// }

// .h-12 {
//   height: 88rpx;
// }

// .rounded-full {
//   border-radius: 50%;
// }

// .object-cover {
//   object-fit: cover;
// }

// .bg-gray-100 {
//   background-color: #f3f4f6;
// }

// .flex {
//   display: flex;
// }

// .flex-1 {
//   flex: 1;
// }

// .items-center {
//   align-items: center;
// }

// .mr-3 {
//   margin-right: 24rpx;
// }

// .font-medium {
//   font-weight: 500;
// }

// .text-lg {
//   font-size: 36rpx;
// }

// .text-sm {
//   font-size: 28rpx;
// }

// .text-base {
//   font-size: 32rpx;
//   line-height: 1.5;
// }

// .text-gray-500 {
//   color: #6b7280;
// }

// .block {
//   display: block;
// }

// NutUI 组件样式覆盖
:deep(.nut-textarea) {
  .nut-textarea__textarea {
    border: 1rpx solid #e5e7eb;
    border-radius: 12rpx;
    padding: 16rpx;
    font-size: 30rpx;
    line-height: 1.5;
  }
}

:deep(.nut-button) {
  border-radius: 12rpx;
}
</style>