<?php
/**
 * 视频通话模块
 */
?>
<style>
    .call-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: #1a1a1a;
        z-index: 1000;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }
    
    .call-status {
        color: #fff;
        font-size: 18px;
        margin-bottom: 24px;
    }
    
    .call-avatar {
        width: 120px;
        height: 120px;
        border-radius: 50%;
        border: 4px solid rgba(255,255,255,0.3);
        margin-bottom: 24px;
    }
    
    .call-name {
        color: #fff;
        font-size: 20px;
        font-weight: 500;
        margin-bottom: 48px;
    }
    
    .call-actions {
        display: flex;
        gap: 32px;
    }
    
    .call-action-btn {
        width: 72px;
        height: 72px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: transform 0.2s;
    }
    
    .call-action-btn:hover {
        transform: scale(1.1);
    }
    
    .call-action-btn.accept {
        background: #00d95e;
    }
    
    .call-action-btn.reject {
        background: #ff3b30;
    }
    
    .call-action-btn.hangup {
        background: #ff3b30;
    }
    
    .call-action-btn.mute {
        background: rgba(255,255,255,0.2);
    }
    
    .call-action-btn.switch {
        background: rgba(255,255,255,0.2);
    }
    
    .call-action-btn.icon {
        font-size: 32px;
        color: #fff;
    }
    
    .call-small-video {
        position: absolute;
        top: 100px;
        right: 24px;
        width: 160px;
        height: 90px;
        border-radius: 12px;
        background: rgba(0,0,0,0.5);
        overflow: hidden;
        border: 2px solid rgba(255,255,255,0.2);
    }
    
    .call-timer {
        position: absolute;
        top: 60px;
        left: 50%;
        transform: translateX(-50%);
        color: rgba(255,255,255,0.7);
        font-size: 14px;
    }
</style>

<script>
    // 视频通话状态
    let callState = 'idle'; // idle, ringing, connecting, connected, incoming
    let currentCallId = null;
    let callTimer = null;
    let callDuration = 0;
    let callPollTimer = null;
    let incomingPollTimer = null;
    let currentCalleeId = null;
    
    // 页面加载完成后启动来电检查
    document.addEventListener('DOMContentLoaded', function() {
        startIncomingCallPolling();
    });
    
    /**
     * 启动来电检查轮询
     */
    function startIncomingCallPolling() {
        // 每2秒检查一次是否有来电
        incomingPollTimer = setInterval(checkIncomingCall, 2000);
    }
    
    /**
     * 停止来电检查轮询
     */
    function stopIncomingCallPolling() {
        if (incomingPollTimer) {
            clearInterval(incomingPollTimer);
            incomingPollTimer = null;
        }
    }
    
    /**
     * 检查是否有来电
     */
    function checkIncomingCall() {
        // 如果当前正在通话中或有来电，不检查
        if (callState !== 'idle') return;
        
        fetch(baseUrl + '/?r=mobileApi/checkCallStatus')
            .then(r => r.json())
            .then(data => {
                if (data && data.code === 0 && data.data && data.data.has_call && data.data.status === 'incoming') {
                    // 有来电
                    stopIncomingCallPolling();
                    handleIncomingCall(data.data);
                }
            })
            .catch(err => {
                // 忽略错误，继续轮询
            });
    }
    
    /**
     * 发起视频通话
     */
    function startVideoCall() {
        if (callState !== 'idle') return;
        
        callState = 'connecting';
        callDuration = 0;
        
        renderCallInterface('video');
        updateCallStatus('正在连接...');
        
        // 调用后端API发起通话请求
        fetch(baseUrl + '/?r=mobileApi/startCall', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({user_id: partnerId, type: 'video'})
        })
        .then(r => r.json())
        .then(data => {
            if (data && data.code === 0 && data.data) {
                currentCallId = data.data.call_id;
                currentCalleeId = partnerId;
                callState = 'ringing';
                updateCallStatus('正在呼叫...');
                
                // 启动来电检查轮询（对方可能会有来电回复）
                startIncomingCallPolling();
                
                // 轮询检查对方是否接听
                startCallPolling();
            } else {
                showToast(data.message || '呼叫失败');
                endCall();
            }
        })
        .catch(err => {
            showToast('呼叫失败');
            endCall();
        });
    }
    
    /**
     * 发起语音通话
     */
    function startVoiceCall() {
        if (callState !== 'idle') return;
        
        callState = 'connecting';
        callDuration = 0;
        
        renderCallInterface('voice');
        updateCallStatus('正在连接...');
        
        // 调用后端API发起通话请求
        fetch(baseUrl + '/?r=mobileApi/startCall', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({user_id: partnerId, type: 'voice'})
        })
        .then(r => r.json())
        .then(data => {
            if (data && data.code === 0 && data.data) {
                currentCallId = data.data.call_id;
                currentCalleeId = partnerId;
                callState = 'ringing';
                updateCallStatus('正在呼叫...');
                
                // 启动来电检查轮询
                startIncomingCallPolling();
                
                // 轮询检查对方是否接听
                startCallPolling();
            } else {
                showToast(data.message || '呼叫失败');
                endCall();
            }
        })
        .catch(err => {
            showToast('呼叫失败');
            endCall();
        });
    }
    
    /**
     * 启动通话状态轮询
     */
    function startCallPolling() {
        callPollTimer = setInterval(checkCallStatus, 1000);
    }
    
    /**
     * 检查通话状态
     */
    function checkCallStatus() {
        if (callState !== 'ringing' && callState !== 'connected') return;
        
        const url = currentCallId 
            ? baseUrl + '/?r=mobileApi/checkCallStatus&call_id=' + currentCallId
            : baseUrl + '/?r=mobileApi/checkCallStatus';
        
        fetch(url)
            .then(r => r.json())
            .then(data => {
                if (data && data.code === 0 && data.data) {
                    const status = data.data.status;
                    
                    if (status === 'accepted') {
                        // 对方已接听
                        stopCallPolling();
                        callState = 'connected';
                        updateCallStatus('通话中');
                        startCallTimer();
                    } else if (status === 'rejected') {
                        // 对方已拒绝
                        stopCallPolling();
                        stopIncomingCallPolling();
                        showToast('对方已拒绝');
                        endCall();
                    } else if (status === 'ended') {
                        // 通话已结束
                        stopCallPolling();
                        stopIncomingCallPolling();
                        showToast('通话已结束');
                        endCall();
                    } else if (status === 'incoming' && callState === 'ringing') {
                        // 作为被叫方收到了来电（对方也打过来了）
                        stopCallPolling();
                        showToast('对方已接听');
                        callState = 'connected';
                        updateCallStatus('通话中');
                        startCallTimer();
                    }
                }
            })
            .catch(err => {
                // 忽略错误，继续轮询
            });
    }
    
    /**
     * 停止通话状态轮询
     */
    function stopCallPolling() {
        if (callPollTimer) {
            clearInterval(callPollTimer);
            callPollTimer = null;
        }
    }
    
    /**
     * 渲染通话界面
     */
    function renderCallInterface(type) {
        const overlay = document.createElement('div');
        overlay.className = 'call-overlay';
        overlay.id = 'callOverlay';
        
        const avatar = document.getElementById('partnerAvatar')?.src || '';
        const name = document.getElementById('partnerName')?.textContent || partnerName;
        
        overlay.innerHTML = `
            <div class="call-timer" id="callTimer">00:00</div>
            <img class="call-avatar" src="${avatar}" alt="${name}">
            <div class="call-name">${name}</div>
            <div class="call-status" id="callStatus">正在连接...</div>
            ${type === 'video' ? '<div class="call-small-video" id="localVideo"></div>' : ''}
            <div class="call-actions">
                <div class="call-action-btn mute" onclick="toggleMute()">
                    <span class="call-action-btn icon"><span class="iconify" data-icon="mdi:mic-off"></span></span>
                </div>
                ${type === 'video' ? `
                <div class="call-action-btn switch" onclick="switchCamera()">
                    <span class="call-action-btn icon"><span class="iconify" data-icon="mdi:camera-switch"></span></span>
                </div>
                ` : ''}
                <div class="call-action-btn hangup" onclick="endCall()">
                    <span class="call-action-btn icon"><span class="iconify" data-icon="mdi:phone-hangup"></span></span>
                </div>
            </div>
        `;
        
        document.body.appendChild(overlay);
        
        // 加载 iconify
        loadIconify();
    }
    
    /**
     * 更新通话状态
     */
    function updateCallStatus(status) {
        const el = document.getElementById('callStatus');
        if (el) el.textContent = status;
    }
    
    /**
     * 更新通话时间
     */
    function updateCallTimer() {
        const el = document.getElementById('callTimer');
        if (el) {
            const mins = Math.floor(callDuration / 60).toString().padStart(2, '0');
            const secs = (callDuration % 60).toString().padStart(2, '0');
            el.textContent = `${mins}:${secs}`;
        }
    }
    
    /**
     * 启动通话计时器
     */
    function startCallTimer() {
        callTimer = setInterval(() => {
            callDuration++;
            updateCallTimer();
        }, 1000);
    }
    
    /**
     * 停止通话计时器
     */
    function stopCallTimer() {
        if (callTimer) {
            clearInterval(callTimer);
            callTimer = null;
        }
    }
    
    /**
     * 切换静音
     */
    function toggleMute() {
        showToast('静音功能开发中');
    }
    
    /**
     * 切换摄像头
     */
    function switchCamera() {
        showToast('切换摄像头功能开发中');
    }
    
    /**
     * 结束通话
     */
    function endCall() {
        stopCallTimer();
        stopCallPolling();
        stopIncomingCallPolling();
        callState = 'idle';
        
        // 通知后端结束通话
        if (currentCallId) {
            fetch(baseUrl + '/?r=mobileApi/endCall', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({call_id: currentCallId})
            })
            .catch(err => {
                console.error('结束通话失败:', err);
            });
            currentCallId = null;
        }
        
        const overlay = document.getElementById('callOverlay');
        if (overlay) {
            overlay.style.opacity = '0';
            overlay.style.transition = 'opacity 0.3s';
            setTimeout(() => overlay.remove(), 300);
        }
        
        // 延迟后重新启动来电检查
        setTimeout(() => {
            if (callState === 'idle') {
                startIncomingCallPolling();
            }
        }, 1000);
    }
    
    /**
     * 加载 iconify
     */
    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;
        }
    }
    
    /**
     * 处理来电
     */
    function handleIncomingCall(data) {
        if (callState !== 'idle') return;
        
        callState = 'incoming';
        callDuration = 0;
        currentCallId = data.call_id;
        currentCalleeId = data.caller_id;
        
        const overlay = document.createElement('div');
        overlay.className = 'call-overlay';
        overlay.id = 'callOverlay';
        
        const avatarUrl = data.caller_avatar || baseUrl + '/templates/mobile/images/avatar_default.png';
        
        overlay.innerHTML = `
            <div class="call-status" id="callStatus">${data.type === 'video' ? '视频' : '语音'}通话</div>
            <img class="call-avatar" src="${avatarUrl}" alt="${data.caller_name}">
            <div class="call-name">${data.caller_name}</div>
            <div class="call-status" id="callStatus">来电中...</div>
            <div class="call-actions">
                <div class="call-action-btn accept" onclick="acceptCall()">
                    <span class="call-action-btn icon"><span class="iconify" data-icon="mdi:phone"></span></span>
                </div>
                <div class="call-action-btn reject" onclick="rejectCall()">
                    <span class="call-action-btn icon"><span class="iconify" data-icon="mdi:phone-hangup"></span></span>
                </div>
            </div>
        `;
        
        document.body.appendChild(overlay);
        loadIconify();
        
        // 启动轮询监控来电状态变化
        startCallPolling();
    }
    
    /**
     * 接听通话
     */
    function acceptCall() {
        if (!currentCallId) return;
        
        fetch(baseUrl + '/?r=mobileApi/acceptCall', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({call_id: currentCallId})
        })
        .then(r => r.json())
        .then(data => {
            if (data && data.code === 0) {
                stopCallPolling();
                callState = 'connected';
                updateCallStatus('通话中');
                startCallTimer();
            } else {
                showToast('接听失败');
                endCall();
            }
        })
        .catch(err => {
            showToast('接听失败');
            endCall();
        });
    }
    
    /**
     * 拒绝通话
     */
    function rejectCall() {
        if (!currentCallId) return;
        
        fetch(baseUrl + '/?r=mobileApi/rejectCall', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({call_id: currentCallId})
        })
        .then(() => {
            showToast('已拒绝通话');
            endCall();
        })
        .catch(err => {
            endCall();
        });
    }
</script>