<template>
    <div class="camera-page">
        <div class="nav">双预防视频监控平台</div>    
        <div class="camera-container">
            <!-- flv-video -->
            <!-- <div  class="flv video-container" v-for="(item,key) in flvsItem" :key="'flv-'+key"  @click.stop="showflvModel(item)" :class="flv.id===item.id?'fixed':'121'">
                <div class="flv-camera-box">
                    <div class="title">
                        <div class="name">{{ item.name }}</div>                                                                 
                        <div class="close" @click.stop="closeflv">X</div>
                    </div>               
                    <video class="flv-video" :id="item.id"  style="width:100%;height:100%;" controls autoplay muted></video>             
                </div>
            </div>         -->
            <div class="video-container" v-for="(item,key) in items" :key="key" >
                <div class="name">{{ item.deviceName }}</div>   
                <div :id="`video-`+item.deviceSerial"  style="width:100%;height:100%;" v-if="key<18"></div>  
                <iframe width="210" height="160" allowfullscreen :src="getIframeSrc(item.deviceSerial)" v-if="key>17"></iframe>   
                <div class="camera-show-handle" @click.stop="showModel(item,2)"  v-if="key>17"></div>
                <div class="camera-show-handle" @click.stop="showModel(item)"  v-if="key<18"></div>
            </div>
            <div id="camera-model" v-show="device.model">
                <div id="camera-box">
                    <div class="title">                        
                        <a :href="'https://open.ys7.com/ezopen/h5/iframe?url=ezopen://open.ys7.com/'+device.deviceSerial+'/1.rec&autoplay=1&accessToken='+accessToken" target="_blank"><span>{{ device.deviceName }}</span></a>
                        【<span style="padding: 10px;color:#000;cursor: pointer;" @click="showRecView">{{devicePlayIsRec?'录像':"查看录像"}}</span> 】                     
                        <div class="close" @click="close">X</div>
                    </div>           
                    <div id="camera-deviceSerial"></div>     
                </div>
            </div>           
        </div>    
    </div>
</template>
<script>
  import "@/assets/js/ezuikit.js"
  import cameras from '@/assets/js/cameras.js';
  import axios from 'axios';
    export default {
        data() {
            return {
                items:[],
                flvsItem:[],
                flv:{
                    name:"",
                    id:""
                },
                accessToken:undefined,
                devicePlayIsRec:false,
                device:{
                    model:false,
                    deviceName:""
                },
                timer:null
            }
        },
        mounted() {
           this.init() 
           setTimeout(()=>{
            window.location.reload()
           },1000*60*30)
        },
        methods: {
            init(){
                axios({
                    url:'https://open.ys7.com/api/lapp/token/get',
                    method:"POST",
                    params:{
                        appKey:"edbf9171037f4908abdaa5c8215c0b06",
                        appSecret:"3c271fe7e2d0c13a03b2acc297ff146f"
                    }
                }).then((res)=>{
                    this.accessToken=res.data.data.accessToken
                    this.getData()
                    // this.getDevicelist()
                })
                // this.renderflvitems()
            },
            showModel(item,type){
                if(type!==2){
                    var destroyPromise = item.player.destroy();
                    destroyPromise.then((data) => {
                        console.log("销毁-promise 获取 数据", data)
                    })  
                    event.stopPropagation()
                }
                let device={
                    ...item,
                    model:true,
                    id:"camera-deviceSerial",
                    width:900,
                    height:700
                }
                this.device=device
                this.render(device)
            },
            close(){
                this.device.player.destroy()
                this.device.player.stop()
                this.device={}  
                this.devicePlayIsRec=false; 
                document.getElementById('camera-deviceSerial').innerHTML=""         
            },
            changePlayUrl(){
                let type=this.devicePlayIsRec?'live':'rec'
                this.device.player.changePlayUrl({
                    url: `ezopen://open.ys7.com/${this.device.deviceSerial}/1.${type}`,
                }).then(()=>{
                    this.devicePlayIsRec=!this.devicePlayIsRec 
                }) 
            },
            showRecView(){
                if(this.devicePlayIsRec)return
                this.device.player.changePlayUrl({
                    url: `ezopen://open.ys7.com/${this.device.deviceSerial}/1.rec`,
                }).then(()=>{
                    this.devicePlayIsRec=true
                }) 
            },     
            async getDevicelist(){
                var devicelist=[]
                const pageSize=20//最大50
                const res=await axios({
                    url:'https://open.ys7.com/api/lapp/device/list',
                    method:"POST",
                    params:{
                        accessToken:this.accessToken,
                        pageSize
                    }
                })
                devicelist=devicelist.concat(res.data.data)
                let total=res.data.page.total-pageSize
                for(let i=0;i<total/pageSize;i++){
                    let  result= await axios({
                        url:'https://open.ys7.com/api/lapp/device/list',
                        method:"POST",
                        params:{
                            accessToken:this.accessToken,
                            pageStart:i+1,
                            pageSize
                        }
                    })
                    devicelist=devicelist.concat(result.data.data)
                } 
                let online=devicelist.filter((item)=>item.status===1)
                let offline=devicelist.filter((item)=>item.status===0)
                let items=online.concat(offline)
                this.items=items
                for(let i=0;i<20;i++){
                    await this.sleep(300)
                    this.$nextTick(()=>{
                        delete items[i].id
                        this.render(items[i],function(item){
                            if(i<21){
                                setTimeout(()=>{
                                    item.player.capturePicture('default',function(data){
                                        item.file=data                              
                                    })
                                },1500)
                            }
                        })                      
                    }) 
                }                            
            },
            // 固定数据渲染处理 根据老板需求相同名字的放在一起 等一系列特殊需求
            async getData(){
                let items=[]
                for(let i=0;i<cameras.length;i++){  
                    items.push({
                        ...cameras[i]
                    })
                }
                this.items=items
                for(let i=0;i<18;i++){
                    await this.sleep(500)
                    this.$nextTick(()=>{
                        this.render(items[i],function(item){
                            setTimeout(()=>{
                                item.player.capturePicture('default',function(data){
                                    item.file=data                                                                        
                                })
                            },3000)
                        })                      
                    }) 
                }                
            },
            getIframeSrc(deviceSerial){
                return `https://open.ys7.com/ezopen/h5/iframe?url=ezopen://open.ys7.com/${deviceSerial}/1.live&autoplay=1&accessToken=${this.accessToken}`
            },
            sleep(time=1000){
                return new Promise((resolve)=>{
                    setTimeout(resolve,time)                                        
                })
            },
            render(item={},callback){
                let accessToken=this.accessToken;
                let type=item.type==='rec'?'rec':'live'
                item.player =  new EZUIKit.EZUIKitPlayer({
                    id: item.id||`video-${item.deviceSerial}`,
                    // autoplay: false,
                    url: `ezopen://open.ys7.com/${item.deviceSerial}/1.${type}`,
                    accessToken: accessToken,
                    plugin: ['talk'],  
                    width: item.width||210,
                    height: item.height||160,
                    audio:0,
                    // useHardDev: true, //开启高性能模式
                    themeData:{
                        "autoFocus": 5,
                        "poster":item.deviceCover||"https://resource.eziot.com/group1/M00/00/89/CtwQEmLl8r-AZU7wAAETKlvgerU237.png",
                        "header": {
                            "color": "#1890ff",
                            "activeColor": "#FFFFFF",
                            "backgroundColor": "#000000",
                            "btnList": []
                        },
                        "footer": {
                            "color": "#FFFFFF",
                            "activeColor": "#1890FF",
                            "backgroundColor": "#00000021",
                            "btnList": [
                                {
                                    "iconId": "play",
                                    "part": "left",
                                    "defaultActive": 1,
                                    "memo": "播放",
                                    "isrender": 0
                                },
                                {
                                    "iconId": "sound",
                                    "part": "left",
                                    "defaultActive": 0,
                                    "memo": "声音按钮",
                                    "isrender": 1
                                },
                                {
                                    "iconId": "pantile",
                                    "part": "left",
                                    "defaultActive": 1,
                                    "memo": "云台控制按钮",
                                    "isrender": 1
                                },
                                {
                                    "iconId": "talk",
                                    "part": "left",
                                    "defaultActive": 0,
                                    "memo": "对讲按钮",
                                    "isrender": 1
                                }, 
                                {
                                    "iconId": "expend",
                                    "part": "right",
                                    "defaultActive": 0,
                                    "memo": "全局全屏按钮",
                                    "isrender": 1
                                }
                            ]
                        }
                    },
                    handleError: (res)=> {
                        console.log('捕获到错误', res)
                        if(res.retcode!==5404){
                            item.player.stop()
                            item.player.destroy();
                            item.player.play()
                        }                       
                    },
                    handleSuccess: function() {
                        console.log("播放成功回调函数，此处可执行播放成功后续动作");
                        if(callback){
                            callback(item)
                        }
                    },
                    capturePictureCallBack: function(data){     
                        item.player.play()           
                        item.player.setPoster(item.file.base64)
                        // item.player.stop()
                        // item.player.destroy();
                        // document.getElementById(data.id).innerHTML=`<img src="${item.file.base64}" style="width:100%;height:100%;display:block;">`    
                    }
                });
                // item.player.play()
            },
            renderflvitems(){
                function initVideo({id,url}){
                    const video = document.getElementById(id);
                    var flvPlayer = flvjs.createPlayer({
                        type: 'flv', // 媒体类型，默认是 flv,
                        isLive: true, // 是否是直播流
                        // hasAudio: ture, // 是否有音频
                        // hanVideo: ture, // 是否有视频
                        url // 流地址
                    },{
                        // 其他的配置项可以根据项目实际情况参考 api 去配置
                        autoCleanupMinBackwardDuration: true, // 清除缓存 对 SourceBuffer 进行自动清理
                    })
                    flvPlayer.attachMediaElement(video);
                    flvPlayer.load();
                    flvPlayer.play();
                    return flvPlayer;
                }              
                let flvs=[
                    {
                      id:"flv-video-1",
                      name:"尧柏室外" , 
                      url:  'https://rtmp01open.ys7.com:9188/v3/openlive/D17867806_1_1.flv?expire=1727866323&id=631202165163040768&t=b38d44dd320b261cbd4b49714d3bc5c77dce2f941cc749ef5d7cba1305ada9f8&ev=100'
                    },
                    {
                        id:"flv-video-2",
                        name:'尧柏室内',
                        url:'https://rtmp01open.ys7.com:9188/v3/openlive/D21357992_1_1.flv?expire=1727866347&id=631202266972758016&t=213001a96c71218df4eb35a3ccfcc3e4e0477ebd88dd1277ce6de864325bd758&ev=100'
                    }                 
                ]
                this.flvsItem=flvs
                this.$nextTick(()=>{
                    for(let i=0;i<flvs.length;i++){
                        this.flvsItem[i].player=initVideo({
                            id:flvs[i].id,
                            url:flvs[i].url
                        }) 
                        
                    }
                })
            },
            showflvModel(item){
                debugger
                this.flv={
                    model:true,
                    name:item.name,
                    id:item.id
                }
            },
            closeflv(){
                this.flv={
                    model:false,
                    name:"",
                    id:undefined
                }
                // window.location.reload()
            },
            flv_destroy(flvPlayer) {
                if (flvPlayer) {
                    flvPlayer.pause();
                    flvPlayer.unload();
                    flvPlayer.detachMediaElement();
                    flvPlayer.destroy();
                    flvPlayer = null;
                }
            }            
        },
        destroyed() {
            this.items.map(item=>{
                if(item.player&&item.player.destroy){
                    var destroyPromise = item.player.destroy();
                    destroyPromise.then((data) => {
                        console.log("promise 获取 数据", data)
                    })                    
                }
            })
            for(let i=0;i<this.flvsItem.length;i++){               
                this.flv_destroy(this.flvsItem[i].player)
            }
        },
    }
</script>
<style>
.flv-video{
    object-fit:fill;
    background-color: #ccc;
}
.camera-page{
    width: 100%;
    min-height: 100vh;
    background-color: #042B5A;
}
.nav{
    height: 50px;
    background-image: url('../../assets/images/head.png');
    background-size: 100% 100%;
    text-align: center;
    color: #fff;
    line-height: 35px;
    font-size: 24px;
    font-weight: 600;
    letter-spacing: 8px;
}
.camera-container{
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-wrap: wrap;
    padding: 10px;
    box-sizing: border-box;
}
.video-container{
    width:210px;
    height: 170px;
    box-sizing: border-box;
    margin: 6px;
    position: relative;
    overflow: hidden;
    cursor: pointer;
}
.video-container iframe{
    border: 0;
    box-sizing: border-box;
    display: block;
}
.video-container .name{
    color: #fff;
    padding: 3px 0;
    background-color: rgba(0,0,0,0.6);
    text-indent: 14px;
    font-size: 14px;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
}
.video-container .camera-show-handle{
    position: absolute;
    width: 100%;
    height: 100%;
    bottom: 36px;
    left: 0;
    z-index: 999;
}
.footer-controls{
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 28px;
}
#camera-model,#flv-camera-model{
    position: fixed;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    background-color: rgba(0,0,0,0.6);
    z-index: 9999;
}
#camera-box,#flv-camera-box{
    width: 900px;
    height: 750px;
    max-width: 100%;
    background-color: #fff;
    margin: 50px auto;
    border-radius: 10px;
    box-shadow: 1px 1px 6px rgba(0,0,0,0.6);
    overflow: hidden;
    padding: 10px;
}
#camera-box .title,#flv-camera-box .title{
    widows: 100%;
    height: 50px;
    line-height: 50px;
    font-weight: 600;
    font-size: 20px;
    background-color: #fff;
    color: #333;
    border-bottom: 1px solid #eaeaea;
    position: relative;
    text-align: center;
}
#camera-box .title .close,#flv-camera-box .title .close{
    width: 50px;
    height: 50px;
    color: #6e6c6c;
    text-align: center;
    line-height: 50px;
    position: absolute;
    right: 0;
    top: 0;
    cursor: pointer;
    font-size: 30px;
}
#camera-deviceSerial,#flv-camera-deviceSerial{
    width: 900px;
    height: 700px;  
    background-color: #3333;
}
.flv.video-container.fixed{
    position: fixed;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    background-color: rgba(0,0,0,0.6);
    z-index: 9998;
}
.flv.video-container .title .close{
    display: none;
}
.flv-camera-box{
    width: 100%;
    height: 100%
}
.fixed .flv-camera-box{
    width: 900px;
    height: 750px;
    max-width: 100%;
    background-color: #fff;
    margin: 50px auto;
    border-radius: 10px;
    box-shadow: 1px 1px 6px rgba(0,0,0,0.6);
    overflow: hidden;
    padding: 10px;
    display: flex;
    flex-direction: column;
}
.fixed .flv-camera-box .title{
    width: 100%;
    height: 50px;
    line-height: 50px;
    font-weight: 600;
    font-size: 20px;
    background-color: #fff;
    color: #333;
    border-bottom: 1px solid #eaeaea;
    position: relative;
    text-align: center;
}
.fixed .flv-camera-box .title .name{
    font-weight: 600;
    font-size: 20px;
    background-color: #fff;
    color: #333;
}
.fixed .flv-camera-box .title .close{
    width: 50px;
    height: 50px;
    color: #6e6c6c;
    text-align: center;
    line-height: 50px;
    position: absolute;
    right: 0;
    top: 0;
    cursor: pointer;
    font-size: 30px;
    display: block !important;
    z-index: 9999;
}
.fixed .flv-camera-box video{
    flex: 1;
    border: 1px solid #eaeaea;
    box-sizing: border-box;
}
.flv.video-container .title{
    width: 100%;
}
</style>