<template>
    <div class="livePage">
        <div class="live-header"></div>
        <!-- 主画面 -->
        <iframe ref="liveIframe" :src="liveUrl" frameborder="0" allowfullscreen class="main-iframe"></iframe>
        <!-- 插播画面 -->
        <video ref="cameraVideo" :class="{ 'camera-video': true, 'full-screen': isfullScreen }" autoplay></video>
        <!-- 插播声音 -->
        <audio :src="soundUrl" class="sound" ref="welcome" @ended="welcomeEnd"></audio>
        <!-- 隐藏的麦克风播放元素，用于放大麦克风声音 -->
        <audio ref="micAudio" autoplay style="display:none"></audio>

        <!-- 文件悬浮展示区域 - 仅支持图片和视频 -->
        <div class="files-display-overlay" v-if="displayedFiles.length > 0">
            <div class="files-container">
                <div v-for="(file, index) in displayedFiles" :key="index" class="file-display-item">
                    <!-- 关闭按钮 -->
                    <!-- <button class="file-close-btn" @click="removeFileFromDisplay(index)">×</button> -->

                    <!-- 图片文件展示 -->
                    <div v-if="file.type.startsWith('image/')" class="image-display">
                        <img :src="file.data" :alt="file.name" />
                        <!-- <div class="file-name-overlay">{{ file.name }}</div> -->
                    </div>

                    <!-- 视频文件展示 -->
                    <div v-else-if="file.type.startsWith('video/')" class="video-display">
                        <video :src="file.data" controls autoplay muted />
                        <!-- <div class="file-name-overlay">{{ file.name }}</div> -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import { useRoute } from 'vue-router';
// 不再需要音频和文档图标

const route = useRoute();
const isCameraActive = ref(false)
const isfullScreen = ref(false);

// 文件展示状态
const displayedFiles = ref([]);
const userId = ref(null);
const liveUrl = ref("");
const soundUrl = ref("");
const welcome = ref()
const live = ref()
let cameraStream = null
let wasWelcomePlaying = false
const cameraVideo = ref()
const liveIframe = ref(null)
const micAudio = ref(null)
let micStream = null
let prevIframeVideoVolume = 1
let micPlaying = false


function welcomeEnd() {
    welcome.value.autoplay = false
    // 尝试恢复主视频（iframe 内的视频）音量到 1
    try {
        const iframeEl = liveIframe.value
        if (iframeEl && iframeEl.contentWindow) {
            const v = iframeEl.contentWindow.document.querySelector('video')
            if (v && typeof v.volume === 'number') {
                v.volume = 1
            }
        }
    } catch (e) {
    }
}


// 文件展示相关函数
const formatFileSize = (bytes) => {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 处理展示文件的请求 - 仅支持图片和视频
const handleShowFilesDisplay = (_event, data) => {
    console.log('收到文件展示请求:', data);
    const files = data.files || [];

    // 过滤并处理文件数据，仅保留图片和视频文件
    const processedFiles = files
        .filter(file => {
            const isImage = file.type.startsWith('image/');
            const isVideo = file.type.startsWith('video/');
            console.log(`文件过滤: ${file.name} (${file.type}) - ${isImage || isVideo ? '保留' : '过滤掉'}`);
            return isImage || isVideo;
        })
        .map(file => {
            console.log(`处理文件: ${file.name}, 路径: ${file.path}, URL: ${file.url}`);

            if (file.url || file.path) {
                // 如果有文件路径，直接使用路径
                const fileUrl = file.url || `file://${file.path.replace(/\\/g, '/')}`;
                console.log(`使用文件路径: ${fileUrl}`);
                return {
                    ...file,
                    data: fileUrl
                };
            } else if (file.data && typeof file.data === 'string') {
                // 如果没有路径但有base64数据，确保格式正确
                const base64Data = file.data.includes('base64,') ? file.data : `data:${file.type};base64,${file.data}`;
                console.log(`使用base64数据: ${base64Data.substring(0, 100)}...`);
                return {
                    ...file,
                    data: base64Data
                };
            }
            return file;
        });

    displayedFiles.value = processedFiles;
    console.log('处理后的文件数量:', displayedFiles.value.length);
    console.log('文件详情:', processedFiles.map(f => ({
        name: f.name,
        type: f.type,
        hasData: !!f.data,
        hasPath: !!f.path,
        hasUrl: !!f.url,
        data: f.data ? f.data.substring(0, 100) : 'no-data' // 显示前100个字符
    })));
};

// 移除文件展示
const removeFileFromDisplay = (index) => {
    const removedFile = displayedFiles.value[index];
    displayedFiles.value.splice(index, 1);

    // 通知主进程文件已被移除
    window.electron.ipcRenderer.send('file-display-removed', {
        index,
        fileName: removedFile?.name,
        timestamp: new Date().toISOString()
    });
};

// 处理移除文件展示的请求
const handleRemoveFileDisplay = (_event, data) => {
    console.log('收到移除文件展示请求:', data);
    const { index } = data;
    if (index >= 0 && index < displayedFiles.value.length) {
        displayedFiles.value.splice(index, 1);
    }
};

// 处理清空所有文件展示的请求
const handleClearAllFilesDisplay = (_event, data) => {
    console.log('收到清空文件展示请求:', data);
    displayedFiles.value = [];
};

onMounted(() => {
    startLive()
    window.electron.ipcRenderer.on('insert-camera-video', handleInsertCameraVideo)
    window.electron.ipcRenderer.on('insert-video-audio', handleInsertVideoAudio)
    window.electron.ipcRenderer.on('toggle-camera-insert', handleToggleCameraInsert)
    window.electron.ipcRenderer.on('force-cleanup-media', handleForceCleanup)

    // 文件展示相关事件
    window.electron.ipcRenderer.on('show-files-display', handleShowFilesDisplay)
    window.electron.ipcRenderer.on('remove-file-display', handleRemoveFileDisplay)
    window.electron.ipcRenderer.on('clear-all-files-display', handleClearAllFilesDisplay)
})

onBeforeUnmount(() => {
    window.electron.ipcRenderer.off('insert-camera-video', handleInsertCameraVideo)
    window.electron.ipcRenderer.off('insert-video-audio', handleInsertVideoAudio)
    window.electron.ipcRenderer.off('toggle-camera-insert', handleToggleCameraInsert)
    window.electron.ipcRenderer.off('force-cleanup-media', handleForceCleanup)

    // 清理文件展示相关事件
    window.electron.ipcRenderer.off('show-files-display', handleShowFilesDisplay)
    window.electron.ipcRenderer.off('remove-file-display', handleRemoveFileDisplay)
    window.electron.ipcRenderer.off('clear-all-files-display', handleClearAllFilesDisplay)

    // 清理媒体资源
    forceCleanupMedia()
})

function startLive() {
    const paramsUserId = route.query.userId;
    console.log(paramsUserId)
    if (paramsUserId) {
        userId.value = paramsUserId
        console.log(userId.value)
        // 直播数字人 正式地址
        liveUrl.value = `https://dmdemo.hx.cn/dashboard.html?userId=${userId.value}`;
        // 测试地址
        // liveUrl.value = "https://www.baidu.com/"
    }
}

async function handleInsertCameraVideo() {
    if (isCameraActive.value) {
        stopCamera()
    } else {
        await startCamera()
    }
}

async function handleToggleCameraInsert() {
    if (isCameraActive.value) {
        // 停止摄像头
        stopCamera()
        if (wasWelcomePlaying) {
            welcome.value.play()
        }
        isfullScreen.value = false
    } else {
        // 暂停原视频
        // 暂停欢迎音频
        if (!welcome.value.paused) {
            welcome.value.pause()
            wasWelcomePlaying = true
        } else {
            wasWelcomePlaying = false
        }
        isfullScreen.value = true
        // 启动摄像头
        await startCamera()
    }
}

// 插入/切换视频音频：把 iframe 内视频声音放小，并放大麦克风声音
async function handleInsertVideoAudio(param = {}) {
    // param 可选字段：{ videoVolume: number (0-1), micVolume: number (0-2), restore: boolean }
    const videoVolume = typeof param.videoVolume === 'number' ? param.videoVolume : 0.2
    const micVolume = typeof param.micVolume === 'number' ? param.micVolume : 1.0
    const restore = !!param.restore

    // 如果请求恢复或已在播放麦克风，则恢复原始音量并停止麦克风
    if (restore || micPlaying) {
        try {
            const iframeEl = liveIframe.value
            if (iframeEl && iframeEl.contentWindow) {
                const v = iframeEl.contentWindow.document.querySelector('video')
                if (v && typeof v.volume === 'number') {
                    v.volume = prevIframeVideoVolume ?? 1
                }
            }
        } catch (e) {
            console.warn('无法访问 iframe 内的视频（可能是跨域），无法恢复音量')
        }

        // 停止麦克风流
        if (micStream) {
            micStream.getTracks().forEach(t => t.stop())
            micStream = null
        }
        if (micAudio.value) {
            try { micAudio.value.pause() } catch (e) { }
            micAudio.value.srcObject = null
        }
        micPlaying = false
        return
    }

    // 降低 iframe 内视频音量（尝试）
    try {
        const iframeEl = liveIframe.value
        if (iframeEl && iframeEl.contentWindow) {
            const v = iframeEl.contentWindow.document.querySelector('video')
            if (v && typeof v.volume === 'number') {
                prevIframeVideoVolume = v.volume
                v.volume = videoVolume
            }
        }
    } catch (e) {
        console.warn('无法访问 iframe 内的视频（可能是跨域），无法调整其音量')
    }

    // 获取并播放麦克风流（如果已经有 cameraStream 的音频轨道则复用）
    try {
        if (cameraStream && cameraStream.getAudioTracks && cameraStream.getAudioTracks().length > 0) {
            // 如果摄像头流已经包含音频（少见），直接用 cameraVideo 元素来放大声音
            if (cameraVideo.value) {
                cameraVideo.value.volume = micVolume
                micPlaying = true
            }
        } else {
            // 请求麦克风权限并播放到隐藏的 audio 元素
            micStream = await navigator.mediaDevices.getUserMedia({ audio: true })
            if (micAudio.value) {
                micAudio.value.srcObject = micStream
                micAudio.value.volume = micVolume
                try { await micAudio.value.play() } catch (e) { console.warn('micAudio play failed', e) }
                micPlaying = true
            }
        }
    } catch (error) {
        console.error('获取麦克风失败：', error)
    }
}


// 停止摄像头
function stopCamera() {
    if (cameraStream) {
        cameraStream.getTracks().forEach(track => track.stop())
        cameraStream = null
    }
    if (cameraVideo.value) {
        cameraVideo.value.srcObject = null
    }
    isCameraActive.value = false
}

// 启动摄像头
async function startCamera() {
    try {
        cameraStream = await navigator.mediaDevices.getUserMedia({ video: true })
        cameraVideo.value.srcObject = cameraStream
        isCameraActive.value = true
    } catch (error) {
        console.error('Error accessing camera:', error)
    }
}

// 强制清理所有媒体资源
function forceCleanupMedia() {
    try {
        console.log('强制清理所有媒体资源...');

        // 停止摄像头
        stopCamera();

        // 停止麦克风
        if (micStream) {
            try {
                micStream.getTracks().forEach(track => track.stop());
            } catch (e) { console.warn('停止麦克风流失败:', e); }
            micStream = null;
        }

        // 清理麦克风音频
        if (micAudio.value) {
            try {
                micAudio.value.pause();
                micAudio.value.srcObject = null;
            } catch (e) { console.warn('清理麦克风音频失败:', e); }
        }

        // 清理欢迎音频
        if (welcome.value) {
            try {
                welcome.value.pause();
                welcome.value.currentTime = 0;
            } catch (e) { console.warn('清理欢迎音频失败:', e); }
        }

        // 恢复iframe内视频音量
        try {
            const iframeEl = liveIframe.value;
            if (iframeEl && iframeEl.contentWindow) {
                const v = iframeEl.contentWindow.document.querySelector('video');
                if (v && typeof v.volume === 'number') {
                    v.volume = 1;
                }
            }
        } catch (e) { console.warn('恢复iframe音量失败:', e); }

        // 重置状态
        isCameraActive.value = false;
        isfullScreen.value = false;
        micPlaying = false;
        wasWelcomePlaying = false;

        console.log('媒体资源清理完成');
    } catch (error) {
        console.error('强制清理媒体资源出错:', error);
    }
}

// 处理强制清理指令
function handleForceCleanup() {
    console.log('收到强制清理指令');
    forceCleanupMedia();
}</script>

<style lang="scss" scoped>
.livePage {
    width: 100vw;
    height: 100vh;
    overflow: hidden;

    .sound {
        display: none;
    }

    video {
        width: 100vw;
        height: 100vh;
        // object-fit: cover;
    }

    .main-iframe {
        position: absolute;
        top: 0;
        left: 0;
        width: 100vw;
        height: 100vh;
        z-index: 1;
        overflow: hidden;
    }

    .camera-video {
        position: absolute;
        bottom: 20px;
        right: 20px;
        width: 200px;
        height: 150px;
        // border: 2px solid #fff;
        z-index: 100;
        /* object-fit: cover; */
    }

    .full-screen {
        bottom: 0;
        right: 0;
        width: 100vw;
        height: 100vh;
        object-fit: cover;
    }

    /* 文件悬浮展示样式 */
    .files-display-overlay {
        position: absolute;
        bottom: 40px;
        left: 20px;
        z-index: 1000;
        max-width: 80vw;
        max-height: 80vh;
        overflow: hidden;
    }

    .files-container {
        display: flex;
        flex-wrap: wrap;
        gap: 5px;
        padding: 5px;
        background: rgba(255, 255, 255, 0.95);
        border-radius: 12px;
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
        backdrop-filter: blur(10px);
        border: 1px solid rgba(255, 255, 255, 0.2);
    }

    .file-display-item {
        position: relative;
        border-radius: 8px;
        overflow: hidden;
        background: white;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        transition: transform 0.3s ease, box-shadow 0.3s ease;
    }

    .file-display-item:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
    }

    .file-close-btn {
        position: absolute;
        top: 8px;
        right: 8px;
        width: 28px;
        height: 28px;
        border: none;
        background: rgba(255, 255, 255, 0.9);
        border-radius: 50%;
        color: #ff4d4f;
        font-size: 18px;
        font-weight: bold;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 10;
        transition: all 0.3s ease;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    }

    .file-close-btn:hover {
        background: #ff4d4f;
        color: white;
        transform: scale(1.1);
    }

    /* 图片展示 */
    .image-display {
        max-width: 300px;
        max-height: 600px;
    }

    .image-display img {
        width: 100%;
        height: 100%;
        object-fit: contain;
        display: block;
    }

    /* 视频展示 */
    .video-display {
        max-width: 300px;
        max-height: 200px;
    }

    .video-display video {
        width: 100%;
        height: 100%;
        object-fit: contain;
        display: block;
    }

    /* 已移除音频、PDF和其他文档类型的展示样式 */

    /* 文件名覆盖层 */
    .file-name-overlay {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0, 0, 0, 0.7);
        color: white;
        padding: 8px 12px;
        font-size: 12px;
        font-weight: 500;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        backdrop-filter: blur(5px);
    }

    .file-name {
        font-weight: 600;
        margin-bottom: 4px;
        font-size: 14px;
        word-break: break-word;
    }

    .file-size {
        font-size: 12px;
        opacity: 0.8;
    }
}

.live-header {
    height: 44px;
    width: 100%;
    -webkit-app-region: drag;
}
</style>