<?php
/**
 * 语音输入模块
 */
?>
<style>
    .voice-input-panel {
        position: fixed;
        bottom: calc(60px + env(safe-area-inset-bottom));
        left: 0;
        right: 0;
        background: var(--card-color);
        border-top-left-radius: 16px;
        border-top-right-radius: 16px;
        box-shadow: 0 -4px 20px rgba(0,0,0,0.15);
        z-index: 99;
        animation: slideUp 0.3s ease;
        padding: 24px;
    }
    
    @keyframes slideUp {
        from { transform: translateY(100%); }
        to { transform: translateY(0); }
    }
    
    .voice-input-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 24px;
    }
    
    .voice-input-title {
        font-size: 16px;
        font-weight: 600;
        color: var(--text-color);
    }
    
    .voice-input-close {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        background: var(--background-color);
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        font-size: 20px;
        color: var(--text-secondary-color);
    }
    
    .voice-input-content {
        text-align: center;
    }
    
    .voice-input-mic-container {
        position: relative;
        width: 120px;
        height: 120px;
        margin: 0 auto 24px;
    }
    
    .voice-input-mic {
        width: 100%;
        height: 100%;
        border-radius: 50%;
        background: linear-gradient(135deg, #ff3b30 0%, #ff5252 100%);
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: transform 0.2s;
        box-shadow: 0 4px 20px rgba(255, 59, 48, 0.4);
    }
    
    .voice-input-mic:hover {
        transform: scale(1.05);
    }
    
    .voice-input-mic.active {
        animation: pulse 1s ease-in-out infinite;
    }
    
    @keyframes pulse {
        0%, 100% { transform: scale(1); box-shadow: 0 4px 20px rgba(255, 59, 48, 0.4); }
        50% { transform: scale(1.1); box-shadow: 0 8px 30px rgba(255, 59, 48, 0.6); }
    }
    
    .voice-input-mic-icon {
        font-size: 48px;
        color: #fff;
    }
    
    .voice-input-wave {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 100%;
        height: 100%;
        pointer-events: none;
    }
    
    .voice-input-wave-bar {
        position: absolute;
        bottom: 50%;
        width: 4px;
        background: rgba(255, 255, 255, 0.6);
        border-radius: 2px;
        transition: height 0.1s;
    }
    
    .voice-input-hint {
        font-size: 14px;
        color: var(--text-secondary-color);
        margin-bottom: 16px;
    }
    
    .voice-input-duration {
        font-size: 18px;
        font-weight: 600;
        color: var(--primary-color);
        margin-bottom: 16px;
    }
    
    .voice-input-actions {
        display: flex;
        justify-content: center;
        gap: 48px;
    }
    
    .voice-input-action-btn {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 8px;
        cursor: pointer;
        color: var(--text-secondary-color);
    }
    
    .voice-input-action-btn-icon {
        width: 48px;
        height: 48px;
        border-radius: 50%;
        background: var(--background-color);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 20px;
    }
    
    .voice-input-action-btn-label {
        font-size: 12px;
    }
</style>

<script>
    let voiceRecording = false;
    let voiceDuration = 0;
    let voiceTimer = null;
    let audioChunks = [];
    
    /**
     * 显示语音输入面板
     */
    function showVoiceInputPanel() {
        closeActionPanel();
        
        const overlay = document.createElement('div');
        overlay.className = 'panel-overlay show';
        overlay.id = 'voiceInputOverlay';
        overlay.onclick = closeVoiceInputPanel;
        document.body.appendChild(overlay);
        
        const panel = document.createElement('div');
        panel.className = 'voice-input-panel';
        panel.id = 'voiceInputPanel';
        
        panel.innerHTML = `
            <div class="voice-input-header">
                <span class="voice-input-title">语音输入</span>
                <div class="voice-input-close" onclick="closeVoiceInputPanel()">×</div>
            </div>
            <div class="voice-input-content">
                <div class="voice-input-mic-container">
                    <div class="voice-input-mic" id="voiceMic" onclick="toggleVoiceRecording()">
                        <span class="voice-input-mic-icon"><span class="iconify" data-icon="mdi:mic"></span></span>
                    </div>
                    <div class="voice-input-wave" id="voiceWave"></div>
                </div>
                <div class="voice-input-duration" id="voiceDuration">00:00</div>
                <div class="voice-input-hint" id="voiceHint">点击开始录音</div>
                <div class="voice-input-actions">
                    <div class="voice-input-action-btn" onclick="cancelVoiceRecording()">
                        <div class="voice-input-action-btn-icon"><span class="iconify" data-icon="mdi:delete"></span></div>
                        <span class="voice-input-action-btn-label">取消</span>
                    </div>
                    <div class="voice-input-action-btn" onclick="sendVoiceMessage()">
                        <div class="voice-input-action-btn-icon" style="background:#00d95e;color:#fff;"><span class="iconify" data-icon="mdi:send"></span></div>
                        <span class="voice-input-action-btn-label">发送</span>
                    </div>
                </div>
            </div>
        `;
        
        document.body.appendChild(panel);
        
        // 加载 iconify
        loadIconify();
    }
    
    /**
     * 切换录音状态
     */
    function toggleVoiceRecording() {
        if (voiceRecording) {
            stopVoiceRecording();
        } else {
            startVoiceRecording();
        }
    }
    
    /**
     * 开始录音
     */
    function startVoiceRecording() {
        voiceRecording = true;
        voiceDuration = 0;
        audioChunks = [];
        
        const mic = document.getElementById('voiceMic');
        const hint = document.getElementById('voiceHint');
        
        mic.classList.add('active');
        hint.textContent = '正在录音...';
        
        // 更新时长
        voiceTimer = setInterval(() => {
            voiceDuration++;
            updateVoiceDuration();
            updateVoiceWave();
        }, 1000);
        
        // 模拟录音
        showToast('开始录音');
    }
    
    /**
     * 停止录音
     */
    function stopVoiceRecording() {
        voiceRecording = false;
        
        if (voiceTimer) {
            clearInterval(voiceTimer);
            voiceTimer = null;
        }
        
        const mic = document.getElementById('voiceMic');
        const hint = document.getElementById('voiceHint');
        
        mic.classList.remove('active');
        hint.textContent = '点击开始录音';
        
        // 清除波形
        clearVoiceWave();
        
        showToast('录音已停止');
    }
    
    /**
     * 更新录音时长
     */
    function updateVoiceDuration() {
        const el = document.getElementById('voiceDuration');
        if (el) {
            const mins = Math.floor(voiceDuration / 60).toString().padStart(2, '0');
            const secs = (voiceDuration % 60).toString().padStart(2, '0');
            el.textContent = `${mins}:${secs}`;
        }
    }
    
    /**
     * 更新语音波形
     */
    function updateVoiceWave() {
        const wave = document.getElementById('voiceWave');
        if (!wave) return;
        
        // 清除现有波形
        wave.innerHTML = '';
        
        // 生成随机波形
        const bars = 20;
        for (let i = 0; i < bars; i++) {
            const bar = document.createElement('div');
            bar.className = 'voice-input-wave-bar';
            bar.style.left = `${(i / bars) * 100}%`;
            bar.style.height = `${Math.random() * 60 + 20}px`;
            wave.appendChild(bar);
        }
    }
    
    /**
     * 清除波形
     */
    function clearVoiceWave() {
        const wave = document.getElementById('voiceWave');
        if (wave) {
            wave.innerHTML = '';
        }
    }
    
    /**
     * 取消录音
     */
    function cancelVoiceRecording() {
        stopVoiceRecording();
        closeVoiceInputPanel();
    }
    
    /**
     * 发送语音消息
     */
    function sendVoiceMessage() {
        if (voiceDuration === 0) {
            showToast('请先录音');
            return;
        }
        
        stopVoiceRecording();
        closeVoiceInputPanel();
        
        // 模拟发送语音消息
        fetch('<?php echo $this->url('mobileApi/sendMessage'); ?>', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                user_id: partnerId,
                content: `<div class="voice-message" data-duration="${voiceDuration}">
                    <span class="voice-play-btn"><span class="iconify" data-icon="mdi:play"></span></span>
                    <div class="voice-wave-bars">
                        ${Array.from({length: Math.min(voiceDuration * 2, 30)}).map((_, i) => 
                            `<span style="height:${Math.random() * 24 + 8}px;"></span>`
                        ).join('')}
                    </div>
                    <span class="voice-duration">${Math.floor(voiceDuration / 60)}:${(voiceDuration % 60).toString().padStart(2, '0')}</span>
                </div>`
            })
        })
        .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" style="background:var(--primary-color);color:#fff;padding:8px 16px;display:flex;align-items:center;gap:12px;">
                            <div style="width:32px;height:32px;border-radius:50%;background:rgba(255,255,255,0.2);display:flex;align-items:center;justify-content:center;">
                                <span class="iconify" data-icon="mdi:play" style="font-size:16px;"></span>
                            </div>
                            <div style="display:flex;align-items:center;gap:4px;">
                                ${Array.from({length: Math.min(voiceDuration * 2, 30)}).map((_, i) => 
                                    `<span style="display:inline-block;width:3px;background:rgba(255,255,255,0.7);border-radius:2px;" 
                                        style="height:${Math.random() * 24 + 8}px;"></span>`
                                ).join('')}
                            </div>
                            <span style="font-size:12px;opacity:0.9;">${Math.floor(voiceDuration / 60)}:${(voiceDuration % 60).toString().padStart(2, '0')}</span>
                        </div>
                        <div class="message-time">刚刚</div>
                    </div>
                `;
                container.appendChild(item);
                scrollToBottom();
                showToast('语音消息已发送');
            } else {
                showToast(data.message || '发送失败');
            }
        })
        .catch(() => {
            showToast('发送失败');
        });
    }
    
    /**
     * 关闭语音输入面板
     */
    function closeVoiceInputPanel() {
        stopVoiceRecording();
        
        const overlay = document.getElementById('voiceInputOverlay');
        const panel = document.getElementById('voiceInputPanel');
        
        if (panel) {
            panel.style.transform = 'translateY(100%)';
            panel.style.transition = 'transform 0.3s';
            setTimeout(() => panel.remove(), 300);
        }
        
        if (overlay) {
            overlay.classList.remove('show');
            setTimeout(() => overlay.remove(), 300);
        }
    }
    
    function loadIconify() {
        if (!window.iconifyLoaded) {
            const script = document.createElement('script');
            script.src = 'https://code.iconify.design/1/1.0.7/iconify.min.js';
            document.head.appendChild(script);
            window.iconifyLoaded = true;
        }
    }
</script>