<template>
    <view class="im-message-list" :class="[
        `im-message-list--${theme}`,
        `im-message-list--${mode}`,
        {
            'im-message-list--empty': isEmpty,
            'im-message-list--unread': showUnreadTips,
            'im-message-list--typing': showTyping
        }
    ]" :style="listStyle" @touchmove="handleTouchMove" @touchend="handleTouchEnd">
        <!-- 加载更多指示器 -->
        <im-loading v-if="loading" :text="loadingText" />
        <!-- <view v-if="loading && loadingPosition === 'top'" class="im-message-list__loading-top">
            <im-loading :text="loadingText" />
        </view> -->

        <!-- 未读消息提示 -->
        <view v-if="showUnreadTips" class="im-message-list__unread-tips" @click="scrollToUnread">
            <im-icon name="arrow-down" size="16" />
            <text class="unread-text">{{ unreadCount }} 条新消息</text>
        </view>

        <!-- 消息列表容器 -->
        <scroll-view ref="scrollView" class="im-message-list__scroll-view" scroll-y :scroll-top="scrollTop"
            :scroll-into-view="scrollIntoView" :scroll-with-animation="scrollAnimation"
            :upper-threshold="loadMoreThreshold" :lower-threshold="scrollToBottomThreshold"
            :show-scrollbar="showScrollbar" :enable-back-to-top="enableBackToTop" @scroll="handleScroll"
            @scrolltoupper="handleScrollToUpper" @scrolltolower="handleScrollToLower">
            <!-- 列表头部（用于加载更多） -->
            <!-- <view v-if="loadingPosition === 'inside'" class="im-message-list__loading-inside">
                <im-loading v-if="loading" :text="loadingText" />
            </view> -->

            <!-- 消息列表内容 -->
            <view class="im-message-list__content">
                <!-- 日期分隔符 -->
                <!-- <view v-if="showDateDivider" v-for="(dateGroup, dateIndex) in groupedMessages"
                    :key="`date-${dateGroup.date}`" class="im-message-list__date-divider"
                    :id="`date-${dateGroup.date}`">
                    <text class="date-text">{{ formatDate(dateGroup.date) }}</text>
                </view> -->
                <view v-if="showUnreadTips" style="height: 80rpx;"></view>

                <!-- 消息项 -->
                <template v-for="(message, index) in processedMessages" :key="getMessageKey(message, index)">
                    <!-- 时间戳分隔（可选） -->
                    <view v-if="showTimestamp && shouldShowTimestamp(message, index)"
                        class="im-message-list__timestamp">
                        <text class="timestamp-text">{{ datetime.toTimeText(message.sendTime) }}</text>
                    </view>

                    <!-- 消息气泡 -->
                    <slot name="message" :message="message" :index="index">
                        <im-message-item :ref="setMessageRef(message.id)" :id="`msg-${index}`" :msgInfo="message"
                            :displayName="String(message.sendNickName)" :showTime="showMessageTime"
                            :showStatus="showMessageStatus && message.selfSend" :showMenu="showMessageMenu"
                            :showReceipt="showMessageReceipt && message.receipt" :groupMembers="groupMembers"
                            :customStyle="getMessageStyle(message)" @click="handleMessageClick(message, $event)"
                            @longpressAvatar="handleLongpressAvatar"
                            @longpress="handleLongpressMessage(message, $event)" @clickAvatar="handleAvatarClick"
                            @click-name="handleNameClick(message, $event)" @resend="handleMessageResend(message)"
                            @recall="handleMessageRecall(message)" @delete="handleMessageDelete(message)"
                            @copy="handleMessageCopy(message)" @forward="handleMessageForward(message)"
                            @reply="handleMessageReply(message)" @download="handleMessageDownload(message)"
                            @audio-state-change="handleAudioPlay(message)" />
                    </slot>

                    <!-- 消息发送状态 -->
                    <!-- <view v-if="showMessageStatus && message.selfSend && message.status" class="im-message-list__status"
                        :class="`im-message-list__status--${message.status}`">
                        <im-icon v-if="getStatusIcons(message.status)" :name="getStatusIcons(message.status)" :size="14"
                            :class="{ 'spin-icon': message.status === MESSAGE_STATUS.SENDING }" />
                        <text v-else class="status-text">{{ getStatusText(message.status) || message.status }}></text>
                    </view> -->
                </template>

                <!-- 空状态 -->
                <view v-if="isEmpty" class="im-message-list__empty">
                    <slot name="empty">
                        <im-icon name="message" size="48" :color="emptyIconColor" />
                        <text class="empty-text">{{ emptyText }}</text>
                    </slot>
                </view>

                <!-- 正在输入指示器 -->
                <view v-if="showTyping" class="im-message-list__typing">
                    <slot name="typing">
                        <view class="typing-indicator">
                            <im-avatar :url="typingUser?.avatar" :name="typingUser?.name" size="small" />
                            <view class="typing-dots">
                                <view class="typing-dot" v-for="i in 3" :key="i"></view>
                            </view>
                            <text class="typing-text">{{ typingUser?.name || '对方' }}正在输入...</text>
                        </view>
                    </slot>
                </view>
            </view>

            <!-- 列表底部（用于填充） -->
            <view class="im-message-list__bottom-spacer" :style="{ height: bottomSpacerHeight + 'px' }"></view>
        </scroll-view>

        <!-- 滚动到底部按钮 -->
        <view v-if="showScrollToBottom && !isAtBottom" class="im-message-list__scroll-bottom" @click="scrollToBottom">
            <im-icon name="arrow-down" size="20" />
            <text v-if="newMessageCount > 0" class="new-message-count">{{ newMessageCount }}</text>
        </view>

        <!-- 消息操作菜单 -->
        <im-message-action v-if="showActionMenu" ref="actionMenu" :visible="actionMenuVisible"
            :message="selectedMessage" :position="actionMenuPosition" :actions="actionMenuActions"
            @close="closeActionMenu" @select="handleActionMenuSelect" />
    </view>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick, onMounted, onUnmounted } from 'vue'
import { useDynamicRefs, datetime } from 'im-ui-mobile'
import { MESSAGE_TYPE, MESSAGE_STATUS } from '../../utils/enums'
import { Message } from '../../libs'
import type { ActionMenuAction, MessageListProps, MessageListEvents } from '../../types/components/message-list'

// 使用动态引用
const { setRef: setMessageRef, getRef: getMessageRef } = useDynamicRefs();

// // 类型定义
// interface TypingUser {
//     id: number
//     name: string
//     avatar?: string
// }

// interface ActionMenuAction {
//     key: string
//     text: string
//     icon?: string
//     color?: string
//     disabled?: boolean
// }

// interface Props {
//     // 数据相关
//     messages: Message[]
//     groupMembers?: GroupMember[]
//     typingUser?: TypingUser | null

//     // 显示控制
//     theme?: 'light' | 'dark'
//     mode?: 'normal' | 'compact'
//     loading?: boolean
//     loadingText?: string
//     loadingPosition?: 'top' | 'inside'

//     // 日期时间显示
//     // showDateDivider?: boolean
//     showTimestamp?: boolean
//     timestampInterval?: number // 时间戳显示间隔（分钟）
//     showMessageTime?: boolean
//     dateFormat?: string
//     timeFormat?: string

//     // 消息显示
//     showMessageStatus?: boolean
//     showMessageMenu?: boolean
//     showMessageReceipt?: boolean
//     displayName?: string
//     showAvatar?: boolean
//     groupShowName?: boolean // 群聊是否显示名称

//     // 滚动相关
//     autoScroll?: boolean
//     scrollAnimation?: boolean
//     showScrollbar?: boolean
//     enableBackToTop?: boolean
//     loadMoreThreshold?: number
//     scrollToBottomThreshold?: number
//     keepAtBottom?: boolean // 新消息时保持底部

//     // 交互提示
//     showScrollToBottom?: boolean
//     showUnreadTips?: boolean
//     unreadCount?: number
//     newMessageCount?: number

//     // 空状态
//     emptyText?: string
//     emptyIconColor?: string

//     // 样式控制
//     backgroundColor?: string
//     minHeight?: string | number
//     maxHeight?: string | number
//     padding?: string | number
//     margin?: string | number

//     // 自定义操作
//     showActionMenu: boolean
//     actionMenuActions?: ActionMenuAction[]
// }

const props = withDefaults(defineProps<MessageListProps>(), {
    theme: 'light',
    mode: 'normal',
    loading: false,
    loadingText: '加载中...',
    loadingPosition: 'inside',

    // showDateDivider: true,
    showTimestamp: true,
    timestampInterval: 5,
    showMessageTime: false,
    dateFormat: 'MM月dd日',
    timeFormat: 'HH:mm',

    showMessageStatus: true,
    showMessageMenu: true,
    showMessageReceipt: false,
    displayName: '',
    showAvatar: true,
    groupShowName: true,

    autoScroll: true,
    scrollAnimation: true,
    showScrollbar: true,
    enableBackToTop: true,
    loadMoreThreshold: 50,
    scrollToBottomThreshold: 200,
    keepAtBottom: true,

    showScrollToBottom: true,
    showUnreadTips: false,
    unreadCount: 0,
    newMessageCount: 0,

    emptyText: '暂无消息',
    emptyIconColor: '#C0C4CC',

    showActionMenu: false,
    actionMenuActions: () => [
        { key: 'copy', text: '复制', icon: 'copy' },
        { key: 'reply', text: '回复', icon: 'reply' },
        { key: 'forward', text: '转发', icon: 'share' },
        { key: 'recall', text: '撤回', icon: 'undo' },
        { key: 'delete', text: '删除', icon: 'delete', color: '#F56C6C' }
    ]
})

// Emits
const emit = defineEmits<MessageListEvents>()

// 响应式数据
const scrollView = ref<any>(null)
const scrollTop = ref(0)
const scrollIntoView = ref('')
const isAtBottom = ref(true)
const isAtTop = ref(false)
const scrollDirection = ref<'up' | 'down'>('down')
const lastScrollTop = ref(0)
const actionMenuVisible = ref(false)
const selectedMessage = ref<Message | null>(null)
const actionMenuPosition = ref<'top' | 'bottom' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'>('bottom')
const playingAudio = ref<Message | null>(null)
const touchStartY = ref(0)
const touchMoveY = ref(0)

// 计算属性
const isEmpty = computed(() => props.messages.length === 0)

const processedMessages = computed(() => {
    return props.messages.filter(msg => {
        // 过滤掉撤回的消息（如果需要可以配置化）
        return msg.status !== MESSAGE_STATUS.RECALL
    })
})

// const groupedMessages = computed(() => {
//     if (!props.showDateDivider || isEmpty.value) return []

//     const groups: Array<{ date: string; messages: Message[] }> = []
//     let currentDate = ''
//     let currentGroup: Message[] = []

//     processedMessages.value.forEach((message, index) => {
//         const messageDate = formatDate(message.sendTime, 'YYYY-MM-DD')

//         if (messageDate !== currentDate) {
//             if (currentGroup.length > 0) {
//                 groups.push({ date: currentDate, messages: [...currentGroup] })
//             }
//             currentDate = messageDate
//             currentGroup = [message]
//         } else {
//             currentGroup.push(message)
//         }

//         // 处理最后一批
//         if (index === processedMessages.value.length - 1) {
//             groups.push({ date: currentDate, messages: currentGroup })
//         }
//     })

//     return groups
// })

const showTyping = computed(() => !!props.typingUser)

const listStyle = computed(() => {
    const style: Record<string, string> = {}

    if (props.backgroundColor) {
        style.backgroundColor = props.backgroundColor
    }

    if (props.minHeight) {
        style.minHeight = typeof props.minHeight === 'number' ? `${props.minHeight}px` : props.minHeight
    }

    if (props.maxHeight) {
        style.maxHeight = typeof props.maxHeight === 'number' ? `${props.maxHeight}px` : props.maxHeight
    }

    if (props.padding) {
        style.padding = typeof props.padding === 'number' ? `${props.padding}px` : props.padding
    }

    if (props.margin) {
        style.margin = typeof props.margin === 'number' ? `${props.margin}px` : props.margin
    }

    return style
})

const bottomSpacerHeight = computed(() => {
    // 为键盘弹出留出空间
    return showTyping.value ? 60 : 20
})

// const getStatusIcons = (status: MESSAGE_STATUS) => {
//     switch (status) {
//         case MESSAGE_STATUS.SENDING:
//             return 'loading'
//         case MESSAGE_STATUS.SENT:
//             return 'ok'
//         case MESSAGE_STATUS.RECEIVED:
//             return 'ok'
//         case MESSAGE_STATUS.READ:
//             return 'ok'
//         case MESSAGE_STATUS.FAILED:
//             return 'close'
//     }
// }

// const getStatusText = (status: MESSAGE_STATUS) => {
//     switch (status) {
//         case MESSAGE_STATUS.SENDING:
//             return '发送中'
//         case MESSAGE_STATUS.SENT:
//             return '已发送'
//         case MESSAGE_STATUS.RECEIVED:
//             return '已送达'
//         case MESSAGE_STATUS.READ:
//             return '已读'
//         case MESSAGE_STATUS.FAILED:
//             return '发送失败'
//     }
// }

// 方法
const getMessageKey = (message: Message, index: number) => {
    return message.id ? `msg-${message.id}` : `msg-tmp-${index}-${message.sendTime}`
}

// const formatDate = (timestamp: any, format?: string): string => {
//     const date = new Date(timestamp)
//     const fmt = format || props.dateFormat

//     if (fmt === 'MM月dd日') {
//         return `${date.getMonth() + 1}月${date.getDate()}日`
//     } else if (fmt === 'YYYY-MM-DD') {
//         return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
//     }

//     // 简单实现，可以替换为更完整的日期格式化库
//     return fmt
//         .replace('YYYY', date.getFullYear().toString())
//         .replace('MM', (date.getMonth() + 1).toString().padStart(2, '0'))
//         .replace('dd', date.getDate().toString().padStart(2, '0'))
//         .replace('M', (date.getMonth() + 1).toString())
//         .replace('d', date.getDate().toString())
// }

// const formatTime = (timestamp: any): string => {
//     const date = new Date(timestamp)
//     const fmt = props.timeFormat

//     return fmt
//         .replace('HH', date.getHours().toString().padStart(2, '0'))
//         .replace('mm', date.getMinutes().toString().padStart(2, '0'))
//         .replace('H', date.getHours().toString())
//         .replace('m', date.getMinutes().toString())
// }

const shouldShowTimestamp = (message: Message, index: number): boolean => {
    if (index === 0) {
        return (+new Date() - Number(message.sendTime)) > props.timestampInterval * 60 * 1000
    }

    if (!props.showTimestamp) {
        return false
    }

    const prevMessage = processedMessages.value[index - 1]
    const timeDiff = Number(message.sendTime) - Number(prevMessage.sendTime)

    // 超过时间间隔显示时间戳
    return timeDiff > props.timestampInterval * 60 * 1000
}

// const shouldShowName = (message: Message, index: number): boolean => {
//     if (!props.displayName || message.selfSend) return false

//     if (props.groupMembers && props.groupMembers.length > 0) {
//         if (!props.groupShowName) return false

//         // 群聊中，连续多条同一个人发的消息，只显示一次名字
//         if (index > 0) {
//             const prevMessage = processedMessages.value[index - 1]
//             if (prevMessage.sendId === message.sendId) {
//                 const timeDiff = message.sendTime - prevMessage.sendTime
//                 // 10分钟内连续发送不显示名字
//                 if (timeDiff < 10 * 60 * 1000) {
//                     return false
//                 }
//             }
//         }
//         return true
//     }

//     return false
// }

// const shouldShowAvatar = (message: Message, index: number): boolean => {
//     if (!props.showAvatar) return false

//     if (props.groupMembers && props.groupMembers.length > 0) {
//         // 群聊中，连续多条同一个人发的消息，只显示一次头像
//         if (index > 0) {
//             const prevMessage = processedMessages.value[index - 1]
//             if (prevMessage.sendId === message.sendId) {
//                 const timeDiff = Number(message.sendTime) - Number(prevMessage.sendTime)
//                 // 10分钟内连续发送不显示头像
//                 if (timeDiff < 10 * 60 * 1000) {
//                     return false
//                 }
//             }
//         }
//     }

//     return true
// }

const getMessageStyle = (message: Message): Record<string, any> => {
    const style: Record<string, any> = {}

    // 可以根据消息类型添加特殊样式
    if (message.type === MESSAGE_TYPE.TIP_TEXT) {
        style.opacity = 0.7
    }

    return style
}

const handleScroll = (event: any) => {
    scrollIntoView.value = ''
    const currentScrollTop = event.detail.scrollTop

    // 判断滚动方向
    scrollDirection.value = currentScrollTop > lastScrollTop.value ? 'down' : 'up'
    lastScrollTop.value = currentScrollTop

    // 判断是否在底部
    const scrollHeight = event.detail.scrollHeight
    const clientHeight = event.detail.clientHeight
    // isAtBottom.value = scrollHeight - currentScrollTop - (clientHeight || 0) < 10

    isAtBottom.value = false
    // console.log('计算滚动 ', event.detail)

    // 判断是否在顶部
    isAtTop.value = currentScrollTop < 10

    emit('scroll', event)
}

const handleScrollToUpper = () => {
    if (props.loading) return

    emit('load-more')
    emit('scroll-to-top')
}

const handleScrollToLower = () => {
    emit('scrollToBottom')
}

const scrollToBottom = () => {
    nextTick(() => {
        if (processedMessages.value.length > 0) {
            const lastIndex = processedMessages.value.length - 1
            scrollIntoView.value = `msg-${lastIndex}`
            // scrollIntoView.value = `msg-${processedMessages.value[lastIndex].id || lastIndex}`
            // console.log('scrollToBottom id', scrollIntoView.value)
        }

        // 如果是手动滚动到底部，更新状态
        isAtBottom.value = true
        emit('scrollToBottom')
    })
}

const scrollToMessage = (messageId: number | string) => {
    scrollIntoView.value = `msg-${messageId}`
}

const scrollToUnread = () => {
    if (props.unreadCount && props.unreadCount > 0) {
        // 滚动到第一条未读消息
        const unreadIndex = processedMessages.value.findIndex(msg => msg.status !== MESSAGE_STATUS.READ && !msg.selfSend)
        if (unreadIndex !== -1) {
            scrollIntoView.value = `msg-${processedMessages.value[unreadIndex].id || unreadIndex}`
        }
    }
}

const handleTouchMove = (event: TouchEvent) => {
    touchMoveY.value = event.touches[0].clientY
}

const handleTouchEnd = () => {
    // 滑动结束处理
    touchStartY.value = 0
    touchMoveY.value = 0
}

// 消息事件处理
const handleMessageClick = (message: Message, event: MouseEvent) => {
    emit('clickMessage', message, event)
}

const handleLongpressMessage = (message: Message, event: TouchEvent) => {
    if (props.showMessageMenu) {
        selectedMessage.value = message
        // actionMenuPosition.value = {
        //     x: event.touches[0].clientX,
        //     y: event.touches[0].clientY
        // }
        actionMenuVisible.value = true
    }

    emit('longpressMessage', message, event)
}

const handleLongpressAvatar = () => {
    emit('longpressAvatar')
}

const handleAvatarClick = () => {
    emit('clickAvatar')
}

const handleNameClick = (message: Message, event: MouseEvent) => {
    emit('click-name', message, event)
}

const handleMessageResend = (message: Message) => {
    emit('resend', message)
}

const handleMessageRecall = (message: Message) => {
    emit('recall', message)
}

const handleMessageDelete = (message: Message) => {
    emit('delete', message)
}

const handleMessageCopy = (message: Message) => {
    emit('copy', message)
}

const handleMessageForward = (message: Message) => {
    emit('forward', message)
}

const handleMessageReply = (message: Message) => {
    emit('reply', message)
}

const handleMessageDownload = (message: Message) => {
    emit('download', message)
}

const handleAudioPlay = (message: Message) => {
    // 停止当前播放的音频
    if (playingAudio.value && playingAudio.value.id !== message.id) {
        const audioRef = getMessageRef(playingAudio.value.id)?.[0]
        audioRef?.stopAudio?.()
    }

    playingAudio.value = message
    emit('audio-play', message)
}

// 操作菜单处理
const handleActionMenuSelect = (action: ActionMenuAction) => {
    if (selectedMessage.value) {
        emit('action-menu-select', action, selectedMessage.value)

        // 执行对应操作
        switch (action.key) {
            case 'copy':
                handleMessageCopy(selectedMessage.value)
                break
            case 'reply':
                handleMessageReply(selectedMessage.value)
                break
            case 'forward':
                handleMessageForward(selectedMessage.value)
                break
            case 'recall':
                handleMessageRecall(selectedMessage.value)
                break
            case 'delete':
                handleMessageDelete(selectedMessage.value)
                break
        }
    }

    closeActionMenu()
}

const closeActionMenu = () => {
    actionMenuVisible.value = false
    selectedMessage.value = null
}

// 监听消息变化，自动滚动到底部
watch(() => props.messages.length, (newLength, oldLength) => {
    if (newLength > oldLength && props.autoScroll && (isAtBottom.value || props.keepAtBottom)) {
        nextTick(() => {
            scrollToBottom()
        })
    }
})

// 监听输入状态
watch(() => props.typingUser, (newTyping) => {
    if (newTyping && isAtBottom.value) {
        // 正在输入时保持滚动到底部
        nextTick(() => {
            scrollToBottom()
        })
    }
})

// 生命周期
onMounted(() => {
    // 初始化滚动到底部
    if (props.autoScroll && !isEmpty.value) {
        nextTick(() => {
            scrollToBottom()
        })
    }
})

onUnmounted(() => {
    // 清理
    if (playingAudio.value) {
        const audioRef = getMessageRef(playingAudio.value.id)?.[0]
        audioRef?.stopAudio?.()
    }
})

// 暴露给父组件的方法
defineExpose({
    scrollToBottom,
    scrollToMessage,
    scrollToUnread,
    getScrollTop: () => scrollTop.value,
    setScrollTop: (top: number) => {
        scrollTop.value = top
    },
    stopAllAudio: () => {
        if (playingAudio.value) {
            const audioRef = getMessageRef(playingAudio.value.id)?.[0]
            audioRef?.stopAudio?.()
            playingAudio.value = null
        }
    }
})
</script>

<style scoped lang="scss">
.im-message-list {
    position: relative;
    height: 100%;
    background-color: #f5f7fa;
    overflow: hidden;
    box-sizing: border-box;

    // 主题变体
    &--light {
        background-color: #f5f7fa;
        color: #333333;
    }

    &--dark {
        background-color: #1a1a1a;
        color: #ffffff;
    }

    &--compact {

        .im-message-list__date-divider,
        .im-message-list__timestamp {
            margin: 8rpx 0;
        }
    }

    // 状态类
    &--loading {
        opacity: 0.8;
    }

    &--empty {
        display: flex;
        align-items: center;
        justify-content: center;
    }

    &--unread {
        .im-message-list__unread-tips {
            display: flex;
        }
    }

    &--typing {
        .im-message-list__typing {
            display: block;
        }
    }
}

// 加载指示器
.im-message-list__loading-top,
.im-message-list__loading-inside {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20rpx;
    background-color: inherit;
}

.im-message-list__loading-top {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    z-index: 10;
    border-bottom: 1rpx solid rgba(0, 0, 0, 0.05);

    .im-message-list--dark & {
        border-bottom-color: rgba(255, 255, 255, 0.1);
    }
}

// 未读消息提示
.im-message-list__unread-tips {
    position: absolute;
    top: 10rpx;
    left: 50%;
    transform: translateX(-50%);
    display: flex;
    align-items: center;
    background-color: #ffffff;
    padding: 8rpx 24rpx;
    border-radius: 20rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
    z-index: 20;
    cursor: pointer;

    .im-message-list--dark & {
        background-color: #2a2a2a;
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.3);
    }

    .unread-text {
        margin-left: 8rpx;
        font-size: 24rpx;
        color: #409eff;
        font-weight: 500;
    }
}

// 滚动视图
.im-message-list__scroll-view {
    height: 100%;
    box-sizing: border-box;
}

// 内容容器
.im-message-list__content {
    padding: 20rpx;
    box-sizing: border-box;
}

// 日期分隔符
.im-message-list__date-divider {
    display: flex;
    justify-content: center;
    margin: 32rpx 0;
    position: relative;

    &::before,
    &::after {
        content: '';
        position: absolute;
        top: 50%;
        width: 100rpx;
        height: 1rpx;
        background-color: rgba(0, 0, 0, 0.1);
    }

    &::before {
        left: 50rpx;
    }

    &::after {
        right: 50rpx;
    }

    .im-message-list--dark &::before,
    .im-message-list--dark &::after {
        background-color: rgba(255, 255, 255, 0.1);
    }

    .date-text {
        font-size: 24rpx;
        color: #909399;
        background-color: inherit;
        padding: 0 20rpx;
        position: relative;
        z-index: 1;

        .im-message-list--dark & {
            color: #aaaaaa;
        }
    }
}

// 时间戳
.im-message-list__timestamp {
    display: flex;
    justify-content: center;
    margin-bottom: 40rpx;

    .timestamp-text {
        font-size: $im-font-size - 2;
        color: $im-text-color-lighter;
        // padding: 4rpx 16rpx;
        // background-color: rgba(0, 0, 0, 0.05);
        // border-radius: 12rpx;

        .im-message-list--dark & {
            color: #666666;
            background-color: rgba(255, 255, 255, 0.1);
        }
    }
}

// 消息状态
.im-message-list__status {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-top: 4rpx;
    padding-right: 80rpx;
    font-size: 22rpx;

    &--sending {
        color: #909399;
    }

    &--sent,
    &--received,
    &--read {
        color: #67c23a;
    }

    &--failed {
        color: #f56c6c;
    }

    .spin-icon {
        animation: spin 1s linear infinite;
    }

    .status-text {
        margin-left: 4rpx;
    }
}

// 空状态
.im-message-list__empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 0;
    color: #c0c4cc;

    .im-message-list--dark & {
        color: #666666;
    }

    .empty-text {
        margin-top: 20rpx;
        font-size: 28rpx;
    }
}

// 正在输入指示器
.im-message-list__typing {
    margin: 20rpx 0;

    .typing-indicator {
        display: flex;
        align-items: center;
        padding: 16rpx 24rpx;
        background-color: #ffffff;
        border-radius: 20rpx;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

        .im-message-list--dark & {
            background-color: #2a2a2a;
        }
    }

    .typing-dots {
        display: flex;
        align-items: center;
        margin: 0 16rpx;
    }

    .typing-dot {
        width: 8rpx;
        height: 8rpx;
        border-radius: 50%;
        background-color: #409eff;
        margin: 0 4rpx;
        animation: typing 1.4s infinite ease-in-out;

        &:nth-child(1) {
            animation-delay: -0.32s;
        }

        &:nth-child(2) {
            animation-delay: -0.16s;
        }
    }

    .typing-text {
        font-size: 24rpx;
        color: #606266;

        .im-message-list--dark & {
            color: #cccccc;
        }
    }
}

// 底部间距
.im-message-list__bottom-spacer {
    width: 100%;
}

// 滚动到底部按钮
.im-message-list__scroll-bottom {
    position: absolute;
    right: 32rpx;
    bottom: 32rpx;
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #ffffff;
    border-radius: 50%;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
    cursor: pointer;
    z-index: 30;
    transition: all 0.3s ease;

    &:active {
        transform: scale(0.95);
    }

    .im-message-list--dark & {
        background-color: #2a2a2a;
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.3);
    }

    .new-message-count {
        position: absolute;
        top: -8rpx;
        right: -8rpx;
        min-width: 32rpx;
        height: 32rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #f56c6c;
        color: #ffffff;
        font-size: 20rpx;
        border-radius: 16rpx;
        padding: 0 8rpx;
    }
}

// 动画
@keyframes spin {
    0% {
        transform: rotate(0deg);
    }

    100% {
        transform: rotate(360deg);
    }
}

@keyframes typing {

    0%,
    80%,
    100% {
        transform: scale(0.8);
        opacity: 0.5;
    }

    40% {
        transform: scale(1);
        opacity: 1;
    }
}

// 响应式调整
@media (max-width: 768px) {
    .im-message-list__content {
        padding: 16rpx;
    }

    .im-message-list__date-divider {
        margin: 24rpx 0;

        &::before,
        &::after {
            width: 60rpx;
        }

        &::before {
            left: 32rpx;
        }

        &::after {
            right: 32rpx;
        }
    }
}
</style>