<!--大屏显示组件-->

<template>
    <div>
        <draggable
                element="div"
                v-model="signalPreList"
                :options="dragOptions2"
                @change="log"
                v-for="item in currentBigshow"
                :class="['split_screen', splitScreenStatus === 0 ? 'split_screen_one' : splitScreenStatus === 1 ? 'split_screen_four' : splitScreenStatus === 2 ? 'split_screen_nine' : 'split_screen_sixteen']"
                :style="{
                    float:'left',
                    width:item.Width*bigScale + 'px',
                    height:item.Height*bigScale + 'px',
                    left:item.Left*bigScale+'px',
                    top:item.Top*bigScale+'px',
                    zIndex:item.ZIndex,
                    display:item.IsVisibility ? 'black' : 'none',
                }"
                id="bigscreen"
        >
            <VueDragResize
                    v-for="itemV in signalPreList" :key="itemV.Id" class="sitem"
                    :w="item.Width*bigScale/itemV.splitScreenStatus" :h="item.Height*bigScale/itemV.splitScreenStatus" :parentLimitation="false"
                    :x="itemV.left" :y="itemV.top"
                    @dragstop="(obj) => dragStop(obj,itemV)"
                    @resizestop="(obj) => reSizeSignal(obj,itemV)"
            >
                <div ref="signal">
                    {{itemV.deviceID}}
                    <!--<video-player
                               ref="videoPlayer"
                               :options="playerOptions"
                               :playsinline="true"
                       >
                    </video-player>-->
                    <div class="closeBtn" @click.stop="closeSignal(itemV)">×</div>
                </div>
            </VueDragResize>

            <div v-for="itemD in bindList" :key="itemD" class="sitem2">
                {{itemD}}
            </div>
        </draggable>
    </div>
</template>

<script>
    import {mapState} from 'vuex'
    import draggable from 'vuedraggable'
    import VueDragResize from 'vue-drag-resize'

    import '../assets/less/splitscreen.less'
    import {elePosition, getElementLeft, getElementTop, getStaticFile, guId, throttleFunc} from "../../utils/tools"
    import {reqRefreshView} from "../api"
    import VideoPlayer from "./player.vue"

    export default {
        data() {
            return {
                isDragging: false, // 是否可拖动标志
                bindList:[], // 拼接屏的数量
                streamWindows:[], // 传递出去的信号源位置信息
                bigScreenJson:[], // 大屏配置json文件
                currentBigshow:[], // 当前大屏
                playerOptions: { // rtmp视频流配置
                    sources: [
                        {
                            "src": "rtmp://58.200.131.2:1935/livetv/hunantv",
                            "type": "rtmp/flv"
                        }
                    ],
                    techOrder: ['flash'],
                    autoplay: true,
                    controls: false,
                    fluid:true,
                    aspectRatio: '200:93',
                    preload: 'auto',
                    notSupportedMessage: '此视频暂无法播放，请稍后再试',
                },
                screenPosition:{}, // 大屏在视口中的位置
                newIndex: 1, // 开窗拖到第几个格子中
            }
        },

        components: {
            draggable,
            VueDragResize,
            "video-player": VideoPlayer
        },

        async beforeCreate() {
            this.bigScreenJson = await getStaticFile('EnityBigScreen.Data')
            this.currentBigshow = this.bigScreenJson.filter(item => item.IsVisibility === true)
            const num = this.currentBigshow[0].BindList.length
            for(let i=0;i<num;i++){
                this.$data.bindList.push(i+1)
            }
            this.$store.dispatch('splitScreen', Math.sqrt(num)-1)
        },

        updated() {
            // 获取大屏在视口中的位置
            const screenDiv = document.getElementById('bigscreen')
            this.screenPosition = {
                top:getElementTop(screenDiv),
                left:getElementLeft(screenDiv)
            }
        },

        methods: {
            // 改变信号源
            log() {
                this.newIndex = this.$store.state.positionNum
            },

            // 大屏开窗接口提交
            reqRefreshBigScreen(arr) {
                const streamWindows = []
                setTimeout(async () => {
                    const elementArr = this.$refs.signal ? this.$refs.signal.filter(item => item.clientWidth !== 0) : []
                    if(elementArr){
                        elementArr.forEach((item,index) => {
                            // 获取元素绝对位置的横坐标和纵坐标
                            const left = getElementLeft(item)
                            const top = getElementTop(item)
                            streamWindows.push({
                                left,
                                top,
                                width:arr[index].width,
                                height:arr[index].height,
                                id:0,
                                sourceId:arr[index].sourceId,
                                widthScale:arr[index].width/(this.currentBigshow[0].Width*this.$store.state.bigScale),
                                heightScale:arr[index].height/(this.currentBigshow[0].Height*this.$store.state.bigScale),
                                orginRect:{}
                            })
                        })
                        const data = {
                            bigScreenId:this.currentBigshow[0].ID,
                            streamWindows
                        }
                        this.streamWindows = streamWindows
                        // 调用大屏开窗接口
                        await reqRefreshView(data)
                    }
                })
            },

            // 拖动结束
            dragStop(obj,item) {
                /*const arr = this.$store.state.signalPreList.filter(a => a.Id !== item.Id)
                item.top = this.screenPosition.top + obj.top
                item.left = this.screenPosition.left + obj.left
                this.$store.dispatch('updateSignalPreList',[...arr,item])*/

                const arr2 = this.$store.state.signalPreList
                this.reqRefreshBigScreen(arr2)
            },

            // 放大缩小信号源(缩放结束事件)
            async reSizeSignal(obj,itemV) {
                const arr = this.$data.streamWindows
                // 找出当前改动的信号源
                const currentItem = arr.filter(item => item.sourceId === itemV.sourceId)
                currentItem[0].width = obj.width
                currentItem[0].height = obj.height
                currentItem[0].widthScale = obj.width/(this.currentBigshow[0].Width*this.$store.state.bigScale)
                currentItem[0].heightScale = obj.height/(this.currentBigshow[0].Height*this.$store.state.bigScale)
                const otherItems = arr.filter(item => item.sourceId !== itemV.sourceId)
                const newStreamWindows = [...currentItem,...otherItems]
                this.streamWindows = newStreamWindows
                this.reqRefreshBigScreen(newStreamWindows)
            },

            // 关闭信号源
            closeSignal(signal) {
                const signalPreList = this.$store.state.signalPreList
                const newSignalPreList = signalPreList.filter(item => item.Id !== signal.Id)
                this.$store.dispatch('updateSignalPreList',newSignalPreList)
            }
        },

        computed: {
            ...mapState(['splitScreenStatus', 'bigScale','positionNum']),

            signalPreList: {
                get() {
                    return this.$store.state.signalPreList
                },

                set(arr) {
                    let len = arr.length
                    if(len>0){
                        // 对监视的信号源数组进行深度克隆，解决赋加Id一样的问题
                        const arr2 = []
                        arr.forEach(item => {arr2.push(JSON.parse(JSON.stringify(item)))})
                        // 删除数据的最后一项，重新赋值再添加
                        arr2.pop()

                        // 给新增的信号源进行赋值
                        const signalObj = arr[len-1]
                        signalObj.Id = guId()
                        signalObj.splitScreenStatus = this.$store.state.splitScreenStatus + 1
                        signalObj.width = this.currentBigshow[0].Width * this.$store.state.bigScale / (this.$store.state.splitScreenStatus+1)
                        signalObj.height = this.currentBigshow[0].Height * this.$store.state.bigScale / (this.$store.state.splitScreenStatus+1)
                        signalObj.widthScale = signalObj.width / (this.currentBigshow[0].Width * this.$store.state.bigScale)
                        signalObj.heightScale = signalObj.height / (this.currentBigshow[0].Height * this.$store.state.bigScale)
                        signalObj.isFixed = true // 是否使用固定定位
                        this.$store.dispatch('updateSignalPreList', [...arr2,signalObj])

                        // 添加定时器是为了得到最新的newIndex
                        setTimeout(() => {
                            let width = this.currentBigshow[0].Width*this.$store.state.bigScale/(signalObj.splitScreenStatus)
                            let height = this.currentBigshow[0].Height*this.$store.state.bigScale/(signalObj.splitScreenStatus)
                            const res = elePosition(width,height,this.newIndex,this.screenPosition.top,this.screenPosition.left,this.$store.state.splitScreenStatus+1)
                            signalObj.top = res.top - this.screenPosition.top
                            signalObj.left = res.left - this.screenPosition.left
                            this.$store.dispatch('updateSignalPreList', [...arr2,signalObj])
                        })
                    }else {
                        this.$store.dispatch('updateSignalPreList', arr)
                    }
                }
            },

            dragOptions1() {
                return {
                    animation: 0,
                    group: {
                        name: "description",
                        pull: 'clone',
                        put: false
                    },
                    ghostClass: "ghost",
                }
            },
            dragOptions2() {
                return {
                    animation: 0,
                    group: "description",
                    disabled:false,
                    sort:false,
                }
            },

            player() {
                return this.$refs.videoPlayer.player
            }
        },

        watch: {
            // 监视大屏中的信号源，只要变动，就调用回调函数
            signalPreList: function (arr) {
                this.reqRefreshBigScreen(arr)
            },

            // 监视分屏的状态
            splitScreenStatus: function(num) {
                this.$data.bindList = []
                for (let i=0;i<(num+1)*(num+1);i++){
                    this.$data.bindList.push(i+1)
                }
                this.reqRefreshBigScreen(this.$data.streamWindows)
            }
        }
    }
</script>
