/**
 * 媒体上传模块（图片和视频）
 */

// 选择相册图片/视频
function selectImageFromGallery() {
    closeActionPanel();
    document.getElementById('chatImageInput').click();
}

// 打开相机
function openCamera() {
    closeActionPanel();
    document.getElementById('cameraInput').click();
}

// 媒体上传（支持图片和视频）
async function handleMediaUpload(event) {
    const file = event.target.files[0];
    if (!file) return;
    
    const btn = document.getElementById('sendBtn');
    btn.disabled = true;
    btn.innerHTML = '<span class="iconify" data-icon="mdi:loader" style="animation: spin 1s linear infinite;"></span>';
    
    try {
        if (file.type.startsWith('image/')) {
            const compressedFile = await HuSNS.compressImage(file);
            await uploadChatMedia('image', compressedFile, event.target);
        } else if (file.type.startsWith('video/')) {
            const compressedFile = await HuSNS.compressVideo(file);
            await uploadChatMedia('video', compressedFile, event.target);
        } else {
            showToast('不支持的文件类型');
            event.target.value = '';
            btn.innerHTML = '<span class="iconify" data-icon="mdi:send"></span>';
        }
    } catch (error) {
        showToast('文件处理失败');
        event.target.value = '';
        btn.innerHTML = '<span class="iconify" data-icon="mdi:send"></span>';
    }
}

// 相机上传处理
async function handleCameraUpload(event) {
    handleMediaUpload(event);
}

// 上传媒体文件
async function uploadChatMedia(type, file, inputElement) {
    const btn = document.getElementById('sendBtn');
    
    const formData = new FormData();
    formData.append(type, file);
    formData.append('user_id', partnerId);
    
    const url = type === 'image' ? baseUrl + '/?r=mobileApi/uploadChatImage' : baseUrl + '/?r=mobileApi/uploadChatVideo';
    
    try {
        const response = await fetch(url, {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if (data.code === 0 && data.data && data.data.url) {
            if (type === 'image') {
                sendImageMessage(data.data.url);
            } else {
                sendVideoMessage(data.data.url, data.data.thumbnail);
            }
        } else {
            showToast(data.message || (type === 'image' ? '图片上传失败' : '视频上传失败'));
        }
    } catch (error) {
        showToast(type === 'image' ? '图片上传失败' : '视频上传失败');
    } finally {
        btn.innerHTML = '<span class="iconify" data-icon="mdi:send"></span>';
        inputElement.value = '';
    }
}

// 发送图片消息
function sendImageMessage(imageUrl) {
    fetch(baseUrl + '/?r=mobileApi/sendMessage', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({user_id: partnerId, content: `<img src="${imageUrl}" class="chat-image" />`})
    })
    .then(r => r.json())
    .then(data => {
        if (data.code === 0) {
            const container = document.getElementById('messagesContainer');
            const item = document.createElement('div');
            item.className = 'message-item me';
            item.innerHTML = `
                <div class="message-content">
                    <div class="message-bubble"><img src="${imageUrl}" class="chat-image" /></div>
                    <div class="message-time">刚刚</div>
                </div>
            `;
            container.appendChild(item);
            scrollToBottom();
        } else {
            showToast(data.message || '发送失败');
        }
    })
    .catch(() => {
        showToast('发送失败');
    });
}

// 发送视频消息
function sendVideoMessage(videoUrl, thumbnailUrl) {
    // 确保URL路径正确，避免重复
    const cleanVideoUrl = videoUrl.startsWith('http') ? videoUrl : 
                         (videoUrl.startsWith('/') ? videoUrl.slice(1) : videoUrl);
    const cleanThumbnailUrl = thumbnailUrl.startsWith('http') ? thumbnailUrl : 
                             (thumbnailUrl.startsWith('/') ? thumbnailUrl.slice(1) : thumbnailUrl);
    
    fetch(baseUrl + '/?r=mobileApi/sendMessage', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
            user_id: partnerId, 
            type: 'video',
            content: cleanVideoUrl,
            video: cleanVideoUrl,
            cover: cleanThumbnailUrl
        })
    })
    .then(r => r.json())
    .then(data => {
        if (data.code === 0) {
            const container = document.getElementById('messagesContainer');
            const item = document.createElement('div');
            item.className = 'message-item me';
            const hasCover = thumbnailUrl && thumbnailUrl !== 'null' && thumbnailUrl !== 'undefined' && thumbnailUrl.trim() !== '';
            item.innerHTML = `
                <div class="message-content">
                    <div class="chat-video-wrapper chat-video-thumbnail" data-video="${videoUrl}" onclick="openMediaViewer('${videoUrl}', 'video')">
                        <div class="chat-video-thumb">
                            <img class="chat-video-poster" src="${hasCover ? thumbnailUrl : ''}" style="width:100%;height:100%;object-fit:cover;border-radius:8px;background:${hasCover ? 'transparent' : '#000'};"><div class="video-overlay"><div class="video-play-icon">▶</div></div>
                        </div>
                    </div>
                    <div class="message-time">刚刚</div>
                </div>
            `;
            container.appendChild(item);
            scrollToBottom();
            setTimeout(() => {
                if (typeof generateChatVideoThumbnails === 'function') {
                    generateChatVideoThumbnails();
                }
            }, 100);
        } else {
            showToast(data.message || '发送失败');
        }
    })
    .catch(() => {
        showToast('发送失败');
    });
}