<template>
  <div class="all">
    <div class="nineVideo">
      <div class="leftBox">
          <div class="leftBox_top" >
            <div id="player"></div>
          </div>
          <div >
            <div class="leftBox_text">
            <span class="name">分屏</span>
            <span class="splitBtn"
              v-for="(item,index) in splitBtn"
              :class="splitBtnActive==index ? 'isBtnActive':''"
              @click="changeSplit(item.value,index)"
              :key="index">{{item.lable}}</span>
          </div>
          <div class="leftBox_text">
            <span class="name">回放时间</span>
            <el-date-picker
                  v-model="dataTime"
                  style="margin-left: 4px;"
                  placeholder="请选择"
                  type="datetimerange"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
              />
          </div>
          <div class="leftBox_text">
            <span class="name">回放</span>
            <span class="splitBtn"
              @click="chooseMune(item)"
              v-for="(item,index) in hFBtn"
              :key="index">{{item}}</span>
          </div>
          <div class="leftBox_text">
            <span class="name">声音</span>
            <span class="splitBtn"
              @click="chooseMune(item)"
              v-for="(item,index) in syBtn"
              :key="index">{{item}}</span>
          </div>
          </div>
          
        </div>
    </div>
    <VideoInfoList v-if="isShowBox"/>
  </div>
</template>

<script setup>
  import VideoInfoList from "./videoInfoList.vue";
  import {dateFormat} from "@/utils/auth";
  import { http } from "@/api/service";
  import { getVideoUrl , getReplayUrl} from "@/api/dpApi/otherApi";
  import emitter from "@/utils/eventBus.js";
  const { LocaleProvider, locales } = window.antd
  moment.locale('./static/js/zh-cn.js')
  const MSE_IS_SUPPORT = !!window.MediaSource // 是否支持mse
  moment.locale('./static/js/zh-cn.js')
  import { ref, onMounted, onUnmounted,reactive,computed,getCurrentInstance} from "vue";
  const isShowVideo = ref(false)
  const player = ref(null);
  const splitNum = ref(1)
  const splitBtnActive = ref(-1)
  const { proxy } = getCurrentInstance();
  const splitBtn = reactive([
    {lable:'整体全屏',value:'all'},
    {lable:'单窗口全屏',value:'alone'},
  ])
  const isShowBox = ref(true)
  // '慢放','快放'
  const hFBtn = reactive(['开始回放','暂停','恢复','停止回放'])
  const syBtn = reactive(['开启','关闭'])
  const sbbh = ref(null)
  const data = ref(null)
  const videoUrl = ref(null)
  const zh_CN = ref('zh-cn')
  const dataTime = ref([
    dateFormat(new Date(), "YY-MM-DD")+' 00:00:00',
    dateFormat(new Date(), "YY-MM-DD")+' 23:59:59',
    ])
  const urls =ref ({
    realplay: '',
    talk: '',
    playback: ''
  })
  const playback =ref ({
    startTime: new Date(dataTime.value[0]),
    endTime: new Date(dataTime.value[1]),
    valueFormat: moment.HTML5_FMT.DATETIME_LOCAL_SECONDS,
    seekStart: new Date('2022-08-29 12:00:00'),
    rate: ''
  })

  const muted = ref(true)
  const time = ref(null)
  const sxtzList = ref([]) //摄像头组列表
  const sxtzLength = ref(0) //摄像头组个数
  const timer = ref(null)
  const num = ref(0)


  onMounted(()=>{
    init()
    createPlayer()
    // 事件中心的视频列表投屏
    let list = JSON.parse(sessionStorage.getItem('videdoList'))
    if(list && list.data.length > 0){
      list.data.forEach((element,index) => {
          splitNum.value = 2
          sbbh.value = element.sbbh
          changeSplit(splitNum.value,-1)
          getUrl(element,index)
      });
    }

    // 视频巡防
    let videoArr = JSON.parse(sessionStorage.getItem('XLFAVIDEO'))
    if(videoArr){
      isShowBox.value = false
      time.value = 1000*60*(parseInt(videoArr.jgsj)) //间隔时间
      sxtzList.value = videoArr.sxtzList[0].sxtList //摄像头组列表
      sxtzLength.value = videoArr.sxtzList[0].sxtList.length //摄像头组个数
      splitNum.value = Math.sqrt(parseInt(videoArr.fps))
      changeSplit(splitNum.value,-1)
      sxtzList.value.forEach((v,index)=>{
        v.sbbh = v.sxtid
        sbbh.value = v.sbbh
        getUrl(v,index)
      })
    }
  })

  onUnmounted(() => {
    clearInterval(timer.value)
  });

  function getUrl(item,index){
    if(item.sbbh){
      http.previewURLs({ sbbh: item.sbbh,protocol:'ws'}).then((res) => {
        let data = JSON.parse(res);
        if(data.data.url){
          urls.value.realplay = data.data.url
          realplay()
          changeSplit(splitNum.value,-1)
        }else{
          proxy.$message({
            message: "获取不到视频流，播放失败!!!",
            grouping:true,
            type: "info"
          });
          isShowVideo.value = false
        }
      })
    }else{
      proxy.$message({
        message: "获取不到视频流，播放失败!!!",
        grouping:true,
        type: "info"
      });
      isShowVideo.value = false
    }
  }

  /* 预览&对讲 */
  function realplay(val) {
    let index = null
    if(val){
      index = val
    }else{
      index = player.value.currentWindowIndex
    }
    
    let playURL = urls.value.realplay
    let mode = 1
    player.value.JS_Play(playURL, { playURL,mode }, index).then(
      () => {  },
      e => {
        proxy.$message({
          message: "该视频无法播放!!!",
          grouping:true,
          type: "info"
        });
        isShowVideo.value = false
      }
    )
  }

  function init() {
    // 设置播放容器的宽高并监听窗口大小变化
    window.addEventListener('resize', () => {
      player.value.JS_Resize()
    })
  }

  function createPlayer(){
    player.value = new window.JSPlugin({
      szId: 'player',
      iWidth: 1400,
      iHeight: 780,
      szBasePath: "./h5player/h5player.min.js",
      iMaxSplit: 4,
      iCurrentSplit: splitNum.value,
      openDebug: true,
      oStyle: {
        borderSelect:'#FFCC00',
      }
    })
  }

  // 切换分屏
  function changeSplit(val,index){
    splitBtnActive.value = index
    if(val == 'alone'){
      // 单个全屏
      player.value.JS_FullScreenSingle(player.value.currentWindowIndex).then(
        () => { },
        e => {  }
      )

    }else if(val == 'all'){
      // 所有全屏
      player.value.JS_FullScreenDisplay(true).then(
        () => {
        },
        e => {  }
      )
    }else{
      // 3*3的屏幕
      let splitNum = val
      player.value.JS_ArrangeWindow(splitNum).then(
        () => { },
        e => {  }
      )
    }
  }

  // 选择回放模块按钮
  function chooseMune(item){
    switch(item){
        case "开始回放": {
          playbackStart()
          break
        }
        case "暂停": {
            playbackPause()
            break
        }
        case "恢复": {
            playbackResume()
            break
        }
        case "停止回放": {
            stopPlay()
            break
        }
        case "慢放": {
            playbackSlow()
            break
        }
        case "快放": {
            playbackFast()
            break
        }
        case "开启": {
            openSound()
            break
        }
        case "关闭": {
            closeSound()
            break
        }
    }
  }
  /* 回放 */
  function playbackStart() {
    let params = {
        beginTime:new Date(dataTime.value[0]),
        endTime:new Date(dataTime.value[1]),
        sbbh: sbbh.value,
        protocol:'ws'
      }
     http.rebackURLs(params).then((res) => {
       let data = JSON.parse(res)
       if(data && data.data){
          urls.value.playback = data.data.url
          let index = player.value.currentWindowIndex
          let playURL = data.data.url
          let startTime = dataTime.value[0]
          let endTime = dataTime.value[1]
          startTime = startTime.replace(' ','T')
          endTime = endTime.replace(' ','T')
          startTime += 'Z'
          endTime += 'Z'
          let mode = 1;
          player.value.JS_Play(playURL, { playURL, mode }, index, startTime,endTime).then(
            () => {
              playback.value.rate = 1
            },
            e => {
              console.error(e) }
          )
          }else{
          proxy.$message({
            message: "获取不到视频流，回放失败!!!",
            grouping:true,
            type: "info"
          });
          isShowVideo.value = false

        }
    })
  }

  // 暂停
  function  playbackPause() {
    player.value.JS_Pause(player.value.currentWindowIndex).then(() => {
    },
      e => { console.error(e) }
    )
  }
  // 恢复
  function playbackResume() {
    player.value.JS_Resume().then(() => {
    },
    e => { console.error(e) }
    )
  }
  //停止回放
  function stopPlay() {
    player.value.JS_Stop().then(
      () => {
        playback.value.rate = 0;
        // getUrl({sbbh:sbbh.value})
        realplay()
        changeSplit(splitNum.value,-1)
      },
      e => { console.error(e) }
    )
  }
  //快放
  function playbackFast() {
    player.value.JS_Fast().then(
      rate => {
        playback.value.rate = rate
      },
      e => { console.error(e) }
    )
  }

  //慢放
  function playbackSlow() {
    player.value.JS_Slow().then(
      rate => {
        playback.value.rate = rate
      },
      e => { console.error(e) }
    )
  }

  /* 声音、抓图、录像 */
  function openSound() {
    player.value.JS_OpenSound().then(
      () => {
        muted.value = false
      },
      e => { console.error(e) }
    )
  }

  // 声音关闭
  function  closeSound() {
    player.value.JS_CloseSound().then(
      () => {
        muted.value = true
      },
      e => { console.error(e) }
    )
  }
</script>

<style lang="scss" scoped>
@import "@/assets/css/largeScreen.scss";
  .leftBox{
    display: flex;
    flex-wrap: wrap;
    .leftBox_top{
      margin-right: 20px;
      #player{
        background:#000;
      }
    }
    .leftBox_text{
      color: #fff;
      margin-top: 10px;
      .name{
        font-size: 16px;
      }
    }
  }
  .splitBtn{
    display: inline-block;
    padding: 4px 14px;
    border: 1px solid #e5e5e5;
    border-radius: 4px;
    margin-left: 4px;
    margin-bottom: 6px;
    color: #fff;
    font-size: 16px;
  }
  .isBtnActive{
    border: 1px solid #FFCC00;
  }
 
</style>

