<template>
    <div class="table-page">
        <div class="table-page-content">
            <div class="left-tree">
                <tree-side
                    :customIcon="true"
                    :expand="false"
                    :dataLoading="treeLoading"
                    isDeselect
                    :treeData="treeData"
                    :tabList="['视频巡查点位']"
                    :defaultProps="defaultProps"
                    @currentChange="currentChange"
                    ref="treeSide"
                >
                    <template v-slot:treeIcon="{data}">
                        <img
                            v-if="data.status === 1"
                            src="@/assets/img/patrolAndRescue/videoInspection/video-site-online.png"
                            class="tree-node-icon"
                        />
                        <img
                            v-else
                            src="@/assets/img/patrolAndRescue/videoInspection/video-site-offline.png"
                            class="tree-node-icon"
                        />
                    </template>
                </tree-side>
            </div>
            <div class="right-table">
                <div class="player-wrapper">
                    <el-carousel
                        v-if="initVideo"
                        :loop="true"
                        :autoplay="false"
                        height="100%"
                        arrow="never"
                        ref="carousel"
                        indicator-position="none"
                        @change="changePlayer"
                    >
                        <el-carousel-item
                            v-for="item in videoWrapper"
                            :key="item + videoWrapper"
                        >
                            <video-player
                                @ready="handleReady"
                                :split="split"
                                :index="item"
                                :ref="`videoPlayer${item}`"
                            ></video-player>
                        </el-carousel-item>
                    </el-carousel>
                </div>
                <div class="controler-wrapper">
                    <div class="controler-left">
                        <div>
                            间隔时间：
                            <el-input-number
                                :min="15"
                                :controls="false"
                                style="width: 80px"
                                v-model="intervalTime"
                                @change="changeInterval"
                            >
                            </el-input-number>
                            秒
                        </div>
                        <!-- <div>
                            分屏：
                            <el-select
                                style="width: 80px"
                                v-model="split"
                                @change="handleArrangeWindow"
                            >
                                <el-option
                                    v-for="item in splitOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                >
                                </el-option>
                            </el-select>
                        </div> -->
                    </div>
                    <div>
                        <div>
                            <el-button
                                size="small"
                                type="primary"
                                @click="handlePlay"
                                :title="playing ? '暂停轮播' : '开始轮播'"
                                :icon="
                                    playing
                                        ? 'el-icon-video-pause'
                                        : 'el-icon-video-play'
                                "
                            ></el-button>
                            <el-button
                                title="上一屏"
                                size="small"
                                type="primary"
                                icon="el-icon-d-arrow-left"
                                @click="handleChangePage('prev')"
                            ></el-button>
                            <el-button
                                title="下一屏"
                                size="small"
                                type="primary"
                                icon="el-icon-d-arrow-right"
                                @click="handleChangePage('next')"
                            ></el-button>
                            <!-- <el-button
                                size="small"
                                type="primary"
                                @click="handleCut"
                                title="截图"
                                icon="el-icon-scissors"
                            ></el-button> -->
                            <el-button
                                size="small"
                                type="warning"
                                icon="el-icon-s-opportunity"
                                @click="handleReport"
                                >异常上报</el-button
                            >
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <report-dialog
            ref="reportDialog"
            :isShow.sync="reportDialog"
        ></report-dialog>
    </div>
</template>

<script>
import {refineRequestBody, setQueryValue} from '@/utils/requestWrappers'
import {
    taskDetail,
    previewURLs,
    saveResultBatch,
} from '@/api/patrolAndRescue/videoPatrol/videoInspection'
import PubSub from 'pubsub-js'
import {dictionaryEscape, getDictionaryByCode} from '@/utils/dictionary'
import VideoPlayer from '@/components/VideoPlayer/index.vue'
import treeSide from '@/components/treeSide/index.vue'
import ReportDialog from './components/ReportDialog/index'

export default {
    name: 'TablePage',
    components: {
        treeSide,
        VideoPlayer,
        ReportDialog,
    },
    data() {
        return {
            pubSub: null,
            treeData: [],
            treeLoading: false,
            treeItem: {}, // 树形节点选中对象
            defaultProps: {
                children: 'children',
                label: 'name',
            },
            initVideo: false,
            intervalTime: 15,
            split: 2,
            playing: false,
            splitOptions: [
                {
                    label: '1X1',
                    value: 1,
                },
                {
                    label: '2X2',
                    value: 2,
                },
            ],
            videoWrapper: 0,
            readyCount: 0,
            timer: null,
            reportDialog: false,
            taskData: null,
            urlList: [], // 播放地址
            tempRankList: [], // 基于上次查看结果重组的播放顺序
            querys: [], // 分屏大于1的 每屏请求参数
        }
    },
    created() {},
    mounted() {
        this.pubSub = PubSub.subscribe('VideoPage', (_, data) => {
            this.loadTree(data?.taskData || {})
        })
    },
    methods: {
        dictionaryEscape,

        currentChange() {},

        preloadVideoUrl() {
            if (
                this.taskData.rank === 0 ||
                this.taskData.rank === this.treeData.length - 1
            ) {
                this.tempData = [...this.treeData]
            } else {
                const tempBefore = this.treeData.slice(this.taskData.rank + 1)
                const tempAfter = this.treeData.slice(0, this.taskData.rank + 1)
                this.tempData = [...tempBefore, ...tempAfter]
            }

            if (this.split > 1) {
                let split = this.split * this.split
                this.querys = this.chunkArray(this.tempData, split)
            }
            this.getUrl()
        },

        // 分屏大于1  拆分数据分离每屏请求数量
        chunkArray(array, chunkSize) {
            if (array.length === 0) {
                return []
            }
            const chunks = []
            let i = 0
            while (i < array.length) {
                chunks.push(array.slice(i, i + chunkSize))
                i += chunkSize
            }
            return chunks
        },

        getUrl() {
            if (this.split > 1) {
                this.querys.forEach(async (siteArr, arrIndex) => {
                    try {
                        let ids = {
                            monitorPointInfoIds: siteArr.map((i) => i.id),
                        }
                        const {value} = await previewURLs(ids)
                        if (value && value.length) {
                            let urls = []
                            value.forEach((item, i) => {
                                urls.push(item.url)
                                this.$refs[
                                    `videoPlayer${arrIndex + 1}`
                                ][0].realplay(item.url, i)
                            })
                            this.urlList[arrIndex] = urls
                        }
                    } catch {
                    } finally {
                    }
                })
                console.log(this.querys, 'this.querys')
            } else {
                try {
                } catch {
                } finally {
                }
            }
        },

        // 视频播放器全部准备状态更新
        handleReady() {
            this.readyCount += 1
            if (this.readyCount === this.videoWrapper) {
                this.playerReady = true

                // 不自动播放，为获取资源保留时间间隔
                // this.startPlay()
                // this.playing = true
            }
        },
        // 计算屏幕数量
        countWrapper() {
            this.videoWrapper = Math.ceil(
                this.treeData.length / (this.split * this.split)
            )
            this.initVideo = true
        },

        // 开启、暂停轮播
        handlePlay() {
            this.playing = !this.playing
            if (this.playing) {
                // this.$refs.carousel.next()
                this.startPlay()
            } else {
                if (this.timer) {
                    clearInterval(this.timer)
                }
            }
        },

        playerStart() {
            if (this.split > 1) {
                this.$nextTick(() => {
                    this.urlList.forEach((urlArr, playerindex) => {
                        urlArr.forEach((url, urlindex) => {
                            if (
                                this.$refs[
                                    `videoPlayer${playerindex + 1}`
                                ][0] &&
                                this.$refs[`videoPlayer${playerindex + 1}`][0]
                                    .realplay
                            ) {
                                this.$refs[
                                    `videoPlayer${playerindex + 1}`
                                ][0].realplay(url, urlindex)
                            }
                        })
                    })
                })
            }
        },

        handleArrangeWindow(val) {
            this.split = val
            this.initVideo = false
            this.countWrapper()
            this.$nextTick(() => {
                console.log(this.videoWrapper, this.$refs)
                for (let i = 1; i < this.videoWrapper; i++) {
                    if (
                        this.$refs[`videoPlayer${i}`] &&
                        this.$refs[`videoPlayer${i}`].arrangeWindow
                    ) {
                        this.$refs[`videoPlayer${i}`].arrangeWindow(val)
                    }
                }
                this.startPlay()
            })
        },

        stopAll() {
            this.$nextTick(() => {
                for (let i = 1; i < this.videoWrapper; i++) {
                    if (
                        this.$refs[`videoPlayer${i}`] &&
                        this.$refs[`videoPlayer${i}`].stopAllPlay
                    ) {
                        this.$refs[`videoPlayer${i}`].stopAllPlay()
                    }
                }
            })
        },
        changeInterval() {
            this.startPlay()
            this.$message.success('设置事件间隔成功')
        },
        // 开始轮询
        startPlay() {
            this.timer && clearInterval(this.timer)
            this.timer = null
            this.timer = setInterval(() => {
                this.$refs?.carousel?.next()
            }, this.intervalTime * 1000)
        },

        // 切换屏幕时默认上报正常
        changePlayer(newIndex, oldIndex) {
            this.uploadStatus(oldIndex) // 默认上报正常
        },

        async uploadStatus(oldIndex) {
            if (this.split > 1) {
                try {
                    let target = this.querys[oldIndex]
                    let query = []
                    target.forEach((item) => {
                        query.push({
                            inspecetStatus: 0, //0 正常
                            rank: item.rank,
                            videoId: item.id,
                            taskId: this.taskData.id,
                        })
                    })

                    // const data = await saveResultBatch()
                } catch {}
            } else {
            }
        },

        // 切换
        handleChangePage(type) {
            this.$refs.carousel[type]()
        },

        handleReport() {
            if (this.playing) this.handlePlay()
            this.reportDialog = true
        },

        handleCut() {},

        //获取数据
        async loadTree(taskData) {
            if (!taskData.id) return
            try {
                this.treeLoading = true
                const data = await taskDetail(taskData.id)
                this.taskData = data
                this.treeData = data.taskVideo || []
                this.treeLoading = false
                this.preloadVideoUrl()
                this.countWrapper()
            } catch (err) {
                console.log(err)
            }
        },

        // 改变页面
        changePage(pageName = '', row = {}) {
            if (!pageName) return
            this.clear()
            this.$emit(
                'changePage',
                pageName,
                (_) => {
                    PubSub.publish(pageName, row)
                },
                row.id ? '编辑' : '添加'
            )
        },
        clear() {
            this.initVideo = false
            this.playing = false
            this.readyCount = 0
            this.timer && clearInterval(this.timer)
            this.timer = null
            this.taskData = null
            this.stopAll()
        },
    },
    beforeDestroy() {
        this.clear()
        // 在组件销毁之前 清除订阅消息
        PubSub.unsubscribe(this.pubSub)
    },
}
</script>

<style lang="scss" scoped>
.table-page {
    .basis {
        min-width: 400px !important;
    }
    .left-tree{
        width: 360px!important;
    }
    .right-table{
        margin: 16px;
        
    }
    .player-wrapper{
        width: 100%;
        height: calc(100% - 60px);
        background-color: rgb(0, 0,0);
        overflow: hidden;
        .el-carousel{
            width: 100%;
            height: 100%;
        }
    }
    .controler-wrapper{
        height: 60px;
        width: 100%;
        padding: 0 20px;
        box-sizing: border-box;
        background-color: rgb(17, 64, 102);
        border-radius:0 0 8px 8px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 20px;
        .controler-left{
            display: flex;
            gap: 26px;
        }
        div {
            font-size: 15px;
        }
        
        ::v-deep .el-button{
            i{
                font-size: 18px!important;
            }
        }
        
    }
    ::v-deep .tree-node-icon {
        width: 15px;
        height: 15px;
    }
}
</style>
