<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="pageStart" 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 { Refresh } from '@element-plus/icons-vue';
import EZUIKit from 'ezuikit-js';
// import TitleComponent from '@/components/TitleComponent';
import { getToken, getMonitoringList } from '@/api/securitySurveillance/index.js';
import { ref, onMounted, watch, nextTick, onUnmounted } from 'vue';

const activeIndex = ref(0); // 初始选中第一个视频
const isExpanded = ref(true); // 初始为扩展
const accessToken = ref('')
const pageStart = ref(1);
const pageSize = ref(4); // 默认请求4个视频（扩展布局）
const totalRecords = ref(0);
const activeTab = ref('live');
const bigVideoRef = ref<HTMLDivElement>(null);
const smallVideoRef = ref<HTMLDivElement>(null);

const videoList = ref([]);
// 存储第二页的数据，用于处理扩展视图右边视频不足的情况
const nextPageVideoList = ref([]);
// 标记是否已经使用了下一页的数据
const hasUsedNextPageData = ref(false);

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/${item.deviceSerial}/1.hd.live`,
            template: "pcLive",
            width: container.clientWidth,
            height: container.clientHeight,
            plugin: ['talk']
        });

    }
};

// 获取萤石云Token
const getTokenData = async () => {
    const { data } = await getToken()
    accessToken.value = data
}
// 获取摄像头列表
const getMonitoringListData = async () => {
    // 根据当前视图类型设置请求数量
    const currentPageSize = isExpanded.value ? 4 : 9;
    const { data } = await getMonitoringList({
        pageStart: pageStart.value,
        pageSize: currentPageSize
    })
    // totalRecords.value = data.total
    videoList.value = data
}

// 获取下一页视频数据
const getNextPageData = async () => {
    const { data } = await getMonitoringList({
        pageStart: pageStart.value + 1,
        pageSize: 3 // 只需要3个视频
    })
    nextPageVideoList.value = data;
    // 标记已经使用了下一页的数据
    hasUsedNextPageData.value = true;
}

const getData = async () => {
    // 先清理所有播放器
    cleanupPlayers();
    // 不再每次都获取token，token只在组件挂载时获取一次
    await getMonitoringListData()
    // 不再重置activeIndex，保留用户之前选择的视频索引
    // 等待DOM更新后初始化视频
    await nextTick();
    initVideo()
}

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

    if (isExpanded.value) {
        // 扩展布局：初始化大视频和右侧3个小视频
        StructureEZUIKitPlayer(videoList.value[activeIndex.value], 0, true);

        // 检查当前视频后面是否有足够的视频
        const remainingVideos = videoList.value.length - activeIndex.value - 1;

        if (remainingVideos >= 3) {
            // 当前页后面有足够的视频，直接使用当前页的数据
            for (let i = 0; i < 3; i++) {
                const displayIndex = activeIndex.value + i + 1;
                StructureEZUIKitPlayer(videoList.value[displayIndex], i);
            }
            // 重置已使用下一页数据的标记
            hasUsedNextPageData.value = false;
        } else {
            // 当前页后面视频不足3个，需要获取下一页的数据
            await getNextPageData();
            // 使用当前页后面的视频和下一页的前几个视频
            let displayCount = 0;

            // 先显示当前页后面的视频
            for (let i = activeIndex.value + 1; i < videoList.value.length && displayCount < 3; i++) {
                StructureEZUIKitPlayer(videoList.value[i], displayCount);
                displayCount++;
            }

            // 再显示下一页的视频补充到3个
            for (let i = 0; i < nextPageVideoList.value.length && displayCount < 3; i++) {
                StructureEZUIKitPlayer(nextPageVideoList.value[i], displayCount);
                displayCount++;
            }
        }
    } else {
        // 普通布局：如果之前在扩展视图中使用了下一页数据，现在需要更新页码
        if (hasUsedNextPageData.value) {
            pageStart.value += 1;
            // 重新获取第二页的9个视频数据
            await getMonitoringListData();
            hasUsedNextPageData.value = false;
        }
        // 初始化所有视频
        videoList.value.forEach((item, index) => {
            StructureEZUIKitPlayer(item, index);
        });
    }
}

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

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

// 清理所有播放器实例
const cleanupPlayers = () => {
    videoList.value.forEach(item => {
        if (item.player) {
            try {
                item.player.destroy();
            }
            catch (error) {
                console.error('销毁播放器失败:', error);
            }
            item.player = null;
        }
    });

    // 清理下一页视频的播放器
    nextPageVideoList.value.forEach(item => {
        if (item.player) {
            try {
                item.player.destroy();
            }
            catch (error) {
                console.error('销毁下一页视频播放器失败:', error);
            }
            item.player = null;
        }
    });
}

// 监听isExpanded变化，根据不同情况处理数据请求
watch(isExpanded, async (newValue, oldValue) => {
    // 保存当前activeIndex的值
    const currentActiveIndex = activeIndex.value;

    // 从扩展视图切换到普通视图，需要重新请求9个视频
    if (newValue === false && oldValue === true) {
        // 重新请求9个视频数据
        await getData();
        // 恢复保存的activeIndex值
        activeIndex.value = currentActiveIndex;
    }
    // 从普通视图切换到扩展视图，不需要重新请求数据
    else if (newValue === true && oldValue === false) {
        // 但是需要重新初始化视频布局
        await nextTick();
        initVideo();
    }
});

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

onMounted(() => {
    // 组件挂载时获取一次token
    getTokenData().then(() => {
        // token获取成功后，获取视频数据
        getData();
    }).catch(error => {
        console.error('获取token失败:', error);
    });
});

// 组件卸载时销毁所有播放器
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>