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

<template>
    <div>
        <draggable
                v-for="item in currentBigshow"
                element="div"
                v-model="bigScreenObj[item.ID].signalArr"
                :options="dragOptions2"
                @change="log"
                :class="['split_screen', bigScreenObj[item.ID].splitStatus === 0 ? 'split_screen_one' : bigScreenObj[item.ID].splitStatus === 1 ? 'split_screen_four' : bigScreenObj[item.ID].splitStatus === 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 bigScreenObj[item.ID].signalArr" :key="itemV.Id" class="sitem"
                    :w="item.Width*bigScale/(bigScreenObj[item.ID].splitStatus+1)" :h="item.Height*bigScale/(bigScreenObj[item.ID].splitStatus+1)" :parentLimitation="false"
                    :x="itemV.left" :y="itemV.top"
                    @dragstop="(obj) => dragStop(obj,itemV)"
                    @resizestop="(obj) => reSizeSignal(obj,itemV)"
            >
                <div ref="signal">
                    {{itemV.deviceID}}
                    <!--<VideoPlayer
                               ref="videoPlayer"
                               :options="playerOptions"
                               :playsinline="true"
                       />-->
                    <div class="closeBtn" @click.stop="closeSignal(itemV)">×</div>
                </div>
            </VueDragResize>

            <div v-for="itemD in bigScreenObj[item.ID].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} from "../../utils/tools"
    import {reqRefreshView} from "../api"
    import VideoPlayer from "./player.vue"

    export default {
        data() {
            return {
                streamWindows:[], // 传递出去的信号源位置信息
                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,
            VideoPlayer
        },

        async beforeCreate() {
            const bigScreenJson = await getStaticFile('EnityBigScreen.Data')
            this.currentBigshow = bigScreenJson.filter(item => item.IsVisibility === true)

            // 给大屏对象进行初始化显示
            const obj = {}
            this.currentBigshow.forEach(item => {
                obj[item.ID] = {
                    bindList:[],
                    splitStatus:0,
                    signalArr:[]
                }
                const num = item.BindList.length
                // 拼接屏数量
                for(let i=0;i<num;i++){
                    obj[item.ID].bindList.push(i+1)
                }
                // 根据拼接屏数量得到分屏状态
                obj[item.ID].splitStatus = Math.floor(Math.sqrt(num)-1)
            })
            this.$store.dispatch('updateBigscreenObj',obj)

            /*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)
            }
            console.log(this.screenPosition)
            
            const bigscreenObj = this.$store.state.bigScreenObj
            console.log(bigscreenObj)
        },

        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','bigScreenObj']),

            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: {
            // 监视大屏对象的变化(深度监视)
            bigScreenObj: {
                handler: function (val, oldVal) { 
                    // console.log(val,oldVal)
                },
                deep: true
            },

            // 监视大屏中的信号源，只要变动，就调用回调函数
            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>
