<template>
    <el-row style="height: 100%;">
        <el-card style="width: 100%;border-radius: 12px;height: 100%;">
            <div style="display: flex;width: 100%;justify-content: flex-end;align-items: center;padding-bottom: 15px;">
                <TitleComponent title="实时视频监控" subtitle="查看所有已完成的巡检记录，跟进巡检报告" />
                <span style="color: rgba(24, 109, 245, 1);display: flex;align-items: center; cursor: pointer;">
                    <span>
                        2025/06/30 12:00
                        刷新数据
                    </span>
                    <el-icon>
                        <Refresh />
                    </el-icon>
                </span>
            </div>
            <div class="video-container">
                <el-row :gutter="20">
                    <!-- 扩展布局：左侧大视频 + 右侧小视频列 -->
                    <template v-if="isExpanded">
                        <!-- 左侧大视频（占 16 列） -->
                        <el-col :span="16" class="video-wrapper">
                            <div class="item large" @click="() => { isExpanded = false; }" ref="bigVideoRef"
                                :id="`bigVideo`">
                                <div class="title" v-if="isExpanded"
                                    style="display: flex;justify-content: space-between;">
                                    <div class="text">
                                        {{ videoList[activeIndex].name }}
                                    </div>
                                    <div class="tools">
                                        <img src="/assets/svg/huanyuan.svg" alt=""></img>
                                        <img src="/assets/svg/quanpin.svg" alt=""></img>
                                        <img src="/assets/svg/jietu.svg" alt="">
                                    </div>
                                </div>
                            </div>
                            <!-- 大视频的切换视图按钮 -->
                            <div class="video-action-btn">
                                <el-button type="primary" @click.stop="() => {
                                    isExpanded = false;
                                }">切换视图</el-button>
                            </div>
                        </el-col>
                        <!-- 右侧小视频列（占 8 列） -->
                        <el-col :span="8">
                            <el-row :gutter="20">
                                <el-col :span="24" v-for="i in 3" :key="i" class="video-wrapper">
                                    <div class="item small" @click="() => {
                                        // 计算要显示的视频索引 - 按照当前视频后面三个排序
                                        const displayIndex = (activeIndex + i) % videoList.length;
                                        activeIndex = displayIndex;
                                    }" :id="`smallVideo-expanded-${i}`">
                                        <div class="title">{{ videoList[(activeIndex + i) % videoList.length].name }}
                                        </div>
                                    </div>
                                    <!-- 小视频的两个按钮：切换视图和查看视频 -->
                                    <div class="video-action-btn expanded">

                                        <el-button type="success" size="small" @click.stop="() => {
                                            const displayIndex = (activeIndex + i) % videoList.length;
                                            activeIndex = displayIndex;
                                            // 不需要改变isExpanded，因为已经在扩展布局
                                        }">查看视频</el-button>
                                    </div>
                                </el-col>
                            </el-row>
                        </el-col>
                    </template>

                    <!-- 普通布局：所有视频均匀排列 -->
                    <template v-else>
                        <el-col :span="8" v-for="(item, index) in videoList" :key="index" class="video-wrapper">
                            <!-- 视频容器 -->
                            <div class="item" :id="`smallVideo-${index + 1}`" ref="smallVideoRef">
                                <div class="title">{{ item.name }}</div>
                            </div>
                            <!-- 按钮放在最外层，与视频容器同级 -->
                            <div class="video-action-btn">
                                <el-button type="primary" @click.stop="() => {
                                    activeIndex = index;
                                    isExpanded = true;
                                }">切换视图</el-button>
                            </div>
                        </el-col>
                    </template>
                </el-row>
                <el-row v-if="!isExpanded">
                    <div class="pagination" v-if="activeTab !== 'record'">
                        <el-pagination layout="prev, pager, next, jumper, sizes" :total="totalRecords"
                            v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[20, 50, 100]"
                            @current-change="handlePageChange" @size-change="handleSizeChange"></el-pagination>
                    </div>
                </el-row>
            </div>
        </el-card>
    </el-row>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick, onUnmounted } from 'vue';
import { Refresh } from '@element-plus/icons-vue';
import EZUIKit from 'ezuikit-js';
import TitleComponent from '@/components/TitleComponent';
import { getToken } from '@/api/securitySurveillance/index.js';
const activeIndex = ref(0); // 初始选中第一个视频
const isExpanded = ref(true); // 初始为普通布局
const pageSize = ref(20);
const totalRecords = ref(100);
const accessToken = ref('')
const currentPage = ref(1);
const activeTab = ref('live');
const bigVideoRef = ref<HTMLDivElement>(null);
const smallVideoRef = ref<HTMLDivElement>(null);

const videoList = ref([
    {
        name: 'A区d厂',
        url: 'https://img.js.design/assets/img/68c144e8ba276a0e8a4a55c2.jpeg#bab7e2e06aae943525cacb13bd63e30d'
    },
    {
        name: 'A区d厂',
        url: 'https://img.js.design/assets/img/68c144efb5e8b987e5ca6462.jpeg#5523cf094b2f8c3a79ea4eb330c99a30'
    },
    {
        name: 'A区d厂',
        url: 'https://img.js.design/assets/img/68c144fbbad414f81995e90c.webp#230d8ca5ca39982518439db26e0ea899'
    },
    {
        name: 'A区d厂',
        url: 'https://img.js.design/assets/img/68c1450640d5d2a02e2540b2.webp#adad2379a0b04d6968364e4fb1133f77'
    },
    {
        name: 'A区d厂',
        url: 'https://img.js.design/assets/img/68c14543d56431f9d6f6808e.webp#16f0a0d8fab4f8ff3b39b04bfabac054'
    },
    {
        name: 'A区d厂',
        url: 'https://img.js.design/assets/img/68c14578d56431f9d6f68981.jpg#e77150417f28a971be4846eb0be90373'
    },
    {
        name: 'A区d厂',
        url: 'https://img.js.design/assets/img/68c145e03f22157da619a7ce.png#546ff44289a22bf175e1eca1f69cd8f9'
    },
    {
        name: 'A区d厂',
        url: 'https://img.js.design/assets/img/68c1461fb5e8b987e5caa293.jpeg#870e4d2b88b487ecb8f2f0b956c45c08'
    },
    {
        name: 'A区d厂',
        url: 'https://img.js.design/assets/img/68c1462dcbf9ed2271880b95.webp#ae7ae94ca84ce980e2d2281869335f06'
    }
]);

const StructureEZUIKitPlayer = (item: any, index: number, isBig = false) => {
    const containerId = isBig ? 'bigVideo' : isExpanded.value ? `smallVideo-expanded-${index + 1}` : `smallVideo-${index + 1}`;
    const container = document.getElementById(containerId);

    // 先销毁旧的播放器实例（如果存在）
    if (item.player) {
        try {
            item.player.destroy();
        } catch (error) {
            console.error('销毁播放器失败:', error);
        }
        item.player = null;
    }

    if (container) {
        item.player = new EZUIKit.EZUIKitPlayer({
            audio: '0',
            id: containerId,
            accessToken: accessToken.value,
            url: "ezopen://open.ys7.com/GA1044316/1.hd.live",
            template: "pcLive",
            width: container.clientWidth,
            height: container.clientHeight,
            plugin: ['talk']
        });
    }
};

// 获取萤石云Token
const getTokenData = async () => {
    const { data } = await getToken()
    accessToken.value = data
    initVideo()
}

const getData = async () => {
    await getTokenData()
}

const initVideo = () => {
    // 先清理所有视频容器的内容，避免残留
    if (bigVideoRef.value) {
        bigVideoRef.value.innerHTML = '';
    }

    if (isExpanded.value) {
        // 扩展布局：初始化大视频和右侧3个小视频
        StructureEZUIKitPlayer(videoList.value[activeIndex.value], 0, true);
        for (let i = 0; i < 3; i++) {
            const displayIndex = (activeIndex.value + i + 1) % videoList.value.length;
            StructureEZUIKitPlayer(videoList.value[displayIndex], i);
        }
    } else {
        // 普通布局：初始化所有视频
        videoList.value.forEach((item, index) => {
            StructureEZUIKitPlayer(item, index);
        });
    }
}

const handlePageChange = (page: number) => {
    currentPage.value = page;
    // 这里可以添加分页逻辑
}

const handleSizeChange = (size: number) => {
    pageSize.value = size;
    currentPage.value = 1;
    // 这里可以添加分页逻辑
}

// 清理所有播放器实例
const cleanupPlayers = () => {
    videoList.value.forEach(item => {
        console.log(item);

        if (item.player) {
            try {
                item.player.destroy();
            } catch (error) {
                console.error('销毁播放器失败:', error);
            }
            item.player = null;
        }
    });
}

// 监听isExpanded变化，重新初始化视频
watch(isExpanded, async (newValue, oldValue) => {
    // 确保DOM已经更新
    await nextTick();
    // 重新初始化视频，确保在切换布局时正确显示
    initVideo();
});

watch(activeIndex, (newIndex) => {
    if (isExpanded.value) {
        // 当activeIndex变化时，重新初始化扩展布局中的视频
        initVideo();
    }
});

onMounted(() => {
    getData()
});

// 组件卸载时销毁所有播放器
onUnmounted(() => {
    cleanupPlayers();
});
</script>

<style scoped lang="scss">
.el-col {
    margin-bottom: 20px;
}

// 视频包装器样式
.video-wrapper {
    position: relative;
    // 确保按钮在视频容器上方
}

.video-container {
    .item {
        height: 220px;
        margin-bottom: 20px;
        position: relative;
        border: 2px solid rgba(45, 119, 249, 1);
        cursor: pointer;
        // 确保子元素正确定位
        overflow: hidden;

        img {
            width: 100%;
            height: 100%;
            display: block;
        }

        .title {
            position: absolute;
            padding: 5px 0;
            padding-left: 10px;
            font-size: 14px;
            border-radius: 8px 8px 0px 0px;
            background: linear-gradient(180deg, rgba(0, 0, 0, 0.73) 0%, rgba(0, 0, 0, 0.33) 100%);
            width: 100%;
            bottom: 0;
            color: #fff;
            z-index: 15;
        }
    }

    // 视频动作按钮样式（放在最外层）
    .video-action-btn {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        opacity: 0;
        transition: opacity 0.3s ease;
        z-index: 20;
        pointer-events: none; // 防止按钮阻止鼠标悬停事件
    }

    // 右侧小视频的按钮容器样式
    .video-action-btn.expanded {
        display: flex;
        gap: 10px;
    }

    // 鼠标悬停在视频包装器上时显示按钮
    .video-wrapper:hover .video-action-btn {
        opacity: 1;
    }

    // 鼠标悬停在视频上时添加半透明背景效果
    .video-wrapper:hover .item::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.2);
        z-index: 5;
    }

    // 按钮本身需要有点击事件
    .video-action-btn button {
        pointer-events: auto;
    }

    // 大视频样式（高度与右侧三个小视频总高度对齐，考虑间距）
    .large {
        height: calc(220px * 3 + 20px * 2 + 40px); // 高度为3个小视频高度加上2个间距

        .tools {
            display: flex;

            img {
                width: 20px;
                height: 20px;
                display: block;
                margin: 0 10px;
            }
        }
    }

    // 小视频样式（保持原高度，适配右侧单列）
    .small {
        height: 235px;
    }
}
</style>