<template>
    <view class="chat-list-page">
        <view class="chat-nav" :style="{ paddingTop: statusBarHeight + 'px' }">
            <view class="chat-nav__btn" @tap="goBack">
                <u-icon name="arrow-left" size="34" color="#111827" />
            </view>
            <text class="chat-nav__title">私聊消息</text>
            <view class="chat-nav__btn" @tap="loadSessions(true)">
                <u-icon name="reload" size="30" color="#111827" />
            </view>
        </view>

        <scroll-view scroll-y class="chat-list-scroll" @scrolltolower="loadMore">
            <view v-if="loading && sessions.length === 0" class="chat-list-state">
                <u-loading mode="circle" />
            </view>

            <view v-for="item in sessions" :key="item.id" class="session-item" @tap="openRoom(item)">
                <image class="session-item__avatar" :src="item.target_user?.avatar || defaultAvatar"
                    mode="aspectFill" />
                <view class="session-item__body">
                    <view class="session-item__top">
                        <text class="session-item__name">{{ item.target_user?.nickname || '用户' }}</text>
                        <text class="session-item__time">{{ formatTime(item.last_active_time || item.create_time)
                        }}</text>
                    </view>
                    <view class="session-item__bottom">
                        <text class="session-item__message">{{ lastMessageText(item) }}</text>
                        <text class="session-item__relation">{{ relationText(item) }}</text>
                    </view>
                </view>
                <view v-if="item.unread_count > 0" class="session-item__badge">
                    <text>{{ item.unread_count > 99 ? '99+' : item.unread_count }}</text>
                </view>
            </view>

            <view v-if="!loading && sessions.length === 0" class="chat-list-empty">
                <u-empty text="暂无私聊消息" mode="data" />
            </view>
            <view v-if="finished && sessions.length > 0" class="chat-list-finished">
                <text>没有更多了</text>
            </view>
        </scroll-view>
    </view>
</template>

<script setup lang="ts">
import { onLoad, onShow } from '@dcloudio/uni-app'
import { ref } from 'vue'
import { getChatSessions, type PrivateChatSession } from '@/api/chat'

const defaultAvatar = '/static/images/avatar.png'
const statusBarHeight = ref(0)
const sessions = ref<PrivateChatSession[]>([])
const loading = ref(false)
const finished = ref(false)
const page = ref(1)
const pageSize = 20

onLoad(() => {
    const sysInfo = uni.getSystemInfoSync()
    // #ifdef APP-PLUS || MP
    statusBarHeight.value = sysInfo.statusBarHeight || 44
    // #endif
    // #ifdef H5
    statusBarHeight.value = 0
    // #endif
})

onShow(() => {
    loadSessions(true)
})

const loadSessions = async (reset = true) => {
    if (loading.value) return
    if (reset) {
        page.value = 1
        finished.value = false
    }
    if (finished.value) return
    loading.value = true
    try {
        const res = await getChatSessions({ page_no: page.value, page_size: pageSize })
        const list = res?.lists || []
        sessions.value = reset ? list : sessions.value.concat(list)
        if (list.length < pageSize) {
            finished.value = true
        } else {
            page.value++
        }
    } catch (e) {
        if (reset) sessions.value = []
    } finally {
        loading.value = false
    }
}

const loadMore = () => {
    if (loading.value || finished.value) return
    loadSessions(false)
}

const openRoom = (item: PrivateChatSession) => {
    uni.navigateTo({ url: `/pages/private_chat/room?session_id=${item.id}` })
}

const lastMessageText = (item: PrivateChatSession) => {
    if (!item.last_message_id) return '还没有消息'
    if (item.last_message_type === 'image') return '[图片]'
    return item.last_message_content || '消息'
}

const relationText = (item: PrivateChatSession) => {
    return item.relationship?.relationship_text || (item.relationship?.is_mutual ? '互相关注' : '对方还未添加你为好友')
}

const formatTime = (value: string | number) => {
    if (!value) return ''
    let timestamp = 0
    if (typeof value === 'number') {
        timestamp = value > 1000000000000 ? value : value * 1000
    } else {
        const numeric = Number(value)
        timestamp = Number.isFinite(numeric) && numeric > 0
            ? numeric * 1000
            : new Date(value.replace(/-/g, '/')).getTime()
    }
    if (!timestamp || Number.isNaN(timestamp)) return ''
    const d = new Date(timestamp)
    const now = new Date()
    const sameDay = d.getFullYear() === now.getFullYear()
        && d.getMonth() === now.getMonth()
        && d.getDate() === now.getDate()
    const hh = String(d.getHours()).padStart(2, '0')
    const mm = String(d.getMinutes()).padStart(2, '0')
    if (sameDay) return `${hh}:${mm}`
    return `${d.getMonth() + 1}-${d.getDate()}`
}

const goBack = () => {
    const pages = getCurrentPages()
    if (pages.length > 1) {
        uni.navigateBack()
        return
    }
    uni.switchTab({ url: '/pages/user/user' })
}
</script>

<style lang="scss" scoped>
.chat-list-page {
    height: 100vh;
    display: flex;
    flex-direction: column;
    background: #eef2f6;
}

.chat-nav {
    flex-shrink: 0;
    height: 96rpx;
    padding-left: 20rpx;
    padding-right: 20rpx;
    background: #fff;
    display: flex;
    align-items: center;
    border-bottom: 1rpx solid #e8edf3;

    &__btn {
        width: 64rpx;
        height: 64rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
    }

    &__title {
        flex: 1;
        min-width: 0;
        text-align: center;
        font-size: 32rpx;
        font-weight: 700;
        color: #111827;
    }
}

.chat-list-scroll {
    flex: 1;
    min-height: 0;
    padding: 18rpx 22rpx 36rpx;
    box-sizing: border-box;
}

.session-item {
    position: relative;
    display: flex;
    align-items: center;
    gap: 20rpx;
    padding: 24rpx;
    margin-bottom: 16rpx;
    background: #fff;
    border: 1rpx solid #dbe6f5;
    border-radius: 8rpx;
    box-sizing: border-box;

    &__avatar {
        width: 88rpx;
        height: 88rpx;
        border-radius: 8rpx;
        flex-shrink: 0;
        background: #e5e7eb;
    }

    &__body {
        flex: 1;
        min-width: 0;
    }

    &__top,
    &__bottom {
        display: flex;
        align-items: center;
        gap: 16rpx;
    }

    &__top {
        margin-bottom: 8rpx;
    }

    &__name {
        flex: 1;
        min-width: 0;
        font-size: 30rpx;
        font-weight: 700;
        color: #111827;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    &__time {
        font-size: 22rpx;
        color: #9ca3af;
        flex-shrink: 0;
    }

    &__message {
        flex: 1;
        min-width: 0;
        font-size: 24rpx;
        color: #6b7280;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    &__relation {
        height: 34rpx;
        padding: 0 12rpx;
        border-radius: 6rpx;
        background: #f3f6fa;
        color: #185dff;
        font-size: 20rpx;
        line-height: 34rpx;
        flex-shrink: 0;
    }

    &__badge {
        min-width: 34rpx;
        height: 34rpx;
        padding: 0 8rpx;
        border-radius: 17rpx;
        background: #ef4444;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;

        text {
            color: #fff;
            font-size: 20rpx;
            line-height: 1;
        }
    }
}

.chat-list-state,
.chat-list-empty,
.chat-list-finished {
    display: flex;
    justify-content: center;
    padding: 120rpx 0;
}

.chat-list-finished {
    padding: 24rpx 0 56rpx;

    text {
        font-size: 24rpx;
        color: #9ca3af;
    }
}
</style>
