<?php
/**
 * HuSNS - 私信列表页面
 */
$currentPage = 'messages';
$pageType = 'messages';
$bodyClass = 'messages-page';
$this->setLayout('app');
?>
<style>
    .messages-content {
        padding-bottom: 60px;
    }

    .conversation-list {
        padding: 8px;
    }

    .conversation-item {
        display: flex;
        align-items: center;
        padding: 12px;
        background: var(--card-color);
        border-radius: 12px;
        margin-bottom: 8px;
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .conversation-item:active {
        background: var(--border-color);
    }

    .conversation-avatar {
        width: 48px;
        height: 48px;
        border-radius: 50%;
        margin-right: 12px;
        object-fit: cover;
        position: relative;
    }

    .avatar-online {
        position: absolute;
        bottom: 0;
        right: 0;
        width: 14px;
        height: 14px;
        background: #28a745;
        border: 2px solid var(--card-color);
        border-radius: 50%;
    }

    .conversation-info {
        flex: 1;
        overflow: hidden;
    }

    .conversation-name {
        font-weight: 600;
        font-size: 15px;
        color: var(--text-color);
        margin-bottom: 4px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .conversation-preview {
        font-size: 13px;
        color: var(--text-secondary-color);
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .conversation-right {
        text-align: right;
    }

    .conversation-time {
        font-size: 12px;
        color: var(--text-secondary-color);
        margin-bottom: 8px;
    }

    .unread-badge {
        background: var(--danger-color);
        color: #fff;
        font-size: 12px;
        min-width: 20px;
        height: 20px;
        line-height: 20px;
        text-align: center;
        border-radius: 10px;
        padding: 0 6px;
    }

    .empty-state {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 80px 20px;
        text-align: center;
    }

    .empty-icon {
        font-size: 64px;
        margin-bottom: 16px;
        opacity: 0.3;
    }

    .empty-text {
        font-size: 16px;
        color: var(--text-secondary-color);
        margin-bottom: 8px;
    }

    .empty-subtext {
        font-size: 14px;
        color: var(--text-secondary-color);
        opacity: 0.7;
    }

    .search-bar {
        padding: 12px;
        background: var(--card-color);
        border-bottom: 1px solid var(--border-color);
    }

    .search-input {
        width: 100%;
        padding: 10px 40px 10px 16px;
        background: var(--background-color);
        border: 1px solid var(--border-color);
        border-radius: 20px;
        font-size: 14px;
        box-sizing: border-box;
    }

    .search-icon {
        position: absolute;
        right: 24px;
        top: 50%;
        transform: translateY(-50%);
        color: var(--text-secondary-color);
    }
</style>

<div class="messages-content">
    <div class="search-bar">
        <div style="position: relative;">
            <input type="text" class="search-input" placeholder="搜索联系人..." id="searchInput">
            <span class="search-icon"><span class="iconify" data-icon="mdi:search"></span></span>
        </div>
    </div>

    <div class="conversation-list" id="conversationList">
        <div class="empty-state">
            <div class="empty-icon"><span class="iconify" data-icon="mdi:message-circle-outline"></span></div>
            <div class="empty-text">暂无私信</div>
            <div class="empty-subtext">去关注用户或被关注后开始聊天吧</div>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        loadConversations();
        
        // 搜索功能
        const searchInput = document.getElementById('searchInput');
        searchInput.addEventListener('input', function() {
            filterConversations(this.value);
        });
    });

    function loadConversations() {
        fetch('<?php echo $this->url('mobileApi/getConversations'); ?>')
            .then(r => r.json())
            .then(data => {
                if (data.code === 0 && data.data && data.data.items.length > 0) {
                    renderConversations(data.data.items);
                }
            })
            .catch(() => {});
    }

    function renderConversations(conversations) {
        const list = document.getElementById('conversationList');
        list.innerHTML = '';

        conversations.forEach(conv => {
            const item = document.createElement('div');
            item.className = 'conversation-item';
            item.onclick = () => openChat(conv.partner_id, conv.username);
            
            // 格式化消息预览
            const preview = formatMessagePreview(conv.last_message);
            
            item.innerHTML = `
                <div style="position: relative;">
                    <img class="conversation-avatar" src="${conv.avatar || '/templates/mobile/images/avatar_default.png'}" alt="${conv.username}">
                    ${conv.is_online ? '<div class="avatar-online"></div>' : ''}
                </div>
                <div class="conversation-info">
                    <div class="conversation-name">${escapeHtml(conv.username)}</div>
                    <div class="conversation-preview">${preview}</div>
                </div>
                <div class="conversation-right">
                    <div class="conversation-time">${conv.time_ago}</div>
                    ${conv.unread_count > 0 ? `<div class="unread-badge">${conv.unread_count}</div>` : ''}
                </div>
            `;
            
            list.appendChild(item);
        });
    }
    
    // 格式化消息预览
    function formatMessagePreview(message) {
        if (!message) return '';
        
        // 如果包含图片标签
        if (message.includes('<img') || message.includes('[图片]')) {
            return '📷 图片';
        }
        // 如果包含视频标签
        if (message.includes('<video') || message.includes('[视频]')) {
            return '🎬 视频';
        }
        // 如果包含语音标签
        if (message.includes('<audio') || message.includes('[语音]')) {
            return '🎤 语音';
        }
        // 如果包含红包
        if (message.includes('red-packet') || message.includes('[红包]')) {
            return '🧧 红包';
        }
        // 如果包含礼物
        if (message.includes('gift') || message.includes('[礼物]')) {
            return '🎁 礼物';
        }
        // 如果包含位置
        if (message.includes('[位置]') || message.includes('location')) {
            return '📍 位置';
        }
        
        // 如果包含其他HTML标签，提取纯文本
        if (/<[^>]+>/.test(message)) {
            const temp = document.createElement('div');
            temp.innerHTML = message;
            return temp.textContent || temp.innerText || '[消息]';
        }
        
        return escapeHtml(message);
    }
    
    // HTML转义函数
    function escapeHtml(str) {
        if (!str) return '';
        return str.replace(/[<>\"'&]/g, function(c) {
            return {'<':'&lt;','>':'&gt;','\"':'&quot;',"'":"&#39;",'&':'&amp;'}[c];
        });
    }

    function filterConversations(keyword) {
        const items = document.querySelectorAll('.conversation-item');
        items.forEach(item => {
            const name = item.querySelector('.conversation-name').textContent;
            const preview = item.querySelector('.conversation-preview').textContent;
            if (name.includes(keyword) || preview.includes(keyword)) {
                item.style.display = 'flex';
            } else {
                item.style.display = 'none';
            }
        });
    }

    async function openChat(userId, username) {
        // 先标记消息为已读
        try {
            await fetch(BASE_URL + '/?r=mobileApi/markMessagesRead', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: 'user_id=' + userId
            });
        } catch (e) {
            console.error('标记消息已读失败', e);
        }
        
        // 更新页脚导航的消息数量
        await fetchNotificationCount();
        
        // 跳转到聊天页面
        window.location.href = '<?php echo $this->url('mobile/chat'); ?>&user_id=' + userId + '&username=' + encodeURIComponent(username);
    }
</script>
