<template>
  <div style="width:100%;height: 100%;">
    <a-row>
      <a-col :span="4">
        <a-menu
          v-model:openKeys="openKeys"
          v-model:selectedKeys="selectedKeys"
          style="overflow: hidden;overflow-y:scroll"
          :style="{ height: `calc(100vh - ${topWidth})`, borderRight: 0 }"
          mode="inline"
        >
          <a-menu-item v-for="(item, index) of leftList" :key="index" @click="(e) => titleClick(e,item)" :title="`${item.jsmc}-${item.xm}`">
            {{ item.jsmc }}-{{ item.xm }}
          </a-menu-item>
        </a-menu>
        <!-- document.querySelector('.ant-layout .jeecg-default-layout-main > div').style.height -->
      </a-col>
      <a-col :span="20">
        <!-- <a-row> -->
          <!-- <a-col :span="12" v-if="currentItem?.child?.录播主机">
            <div>{{ currentItem?.child?.录播主机?.xm }}</div>
            <bVideo :ref="el=> bVideoRefs['main']=el" :videoOption="{ autoPlay: true }" :videoKey="'main'"/>
          </a-col> -->
          <!-- <a-col :span="12">
            <a-row>
              <a-col v-for="(item,index) of calcOtherVideo()" :span="12">
                <div>{{ index }}</div>
                <bVideo :ref="el=> bVideoRefs[index]=el" :videoOption="{ autoPlay: true }" :videoKey="'other-'+item.id"/>
              </a-col>
            </a-row>
          </a-col> -->
          <!-- <a-col v-for="(item,index) of calcOtherVideo()" :span="4">
          </a-col> -->
          <!-- <a-col :span="4"> -->
            <!-- <bVideo ref="bVideoLeftRef" :videoOption="{ autoPlay: true }" :videoKey="'left-'+currentItem?.child?.学生定位?.id"/> -->
          <!-- </a-col> -->
        <!-- </a-row> -->
        <div>
          <a-card :title="mainVideoCardBoxTitle" class="videoCardMain">
            <video id="mainVideo" v-bind="videoOption" style="width:100%" @click.prevent.stop></video>
          </a-card>
        </div>
        <div style="display: flex;flex-direction: row;flex-wrap: nowrap;overflow-x: scroll;">
          <div v-for="(item,index) of calcOtherVideo()" class="videoMax">
            <a-card :title="item?.xm" style="width: 300px" class="videoCardMain">
              <bVideo :ref="el=> bVideoRefs[index]=el" :videoOption="{ autoPlay: true, onClick: bVideoClick }" :videoKey="'other-'+item.id"/>
            </a-card>
          </div>
        </div>
      </a-col>
    </a-row>
  </div>
  <!-- <a-layout>
    <a-layout-sider width="200" style="background: #fff">
      <a-menu
        v-model:openKeys="openKeys"
        v-model:selectedKeys="selectedKeys"
        :style="{ height: '100%', borderRight: 0 }"
        mode="inline"
      >
        <a-menu-item v-for="(item, index) of leftList" :key="index" @click="(e) => titleClick(e,item)" :title="`${item.xq}-${item.jsmc}-${item.xm}`">
          {{ item.xq }}-{{ item.jsmc }}-{{ item.xm }}
        </a-menu-item>
      </a-menu>

    </a-layout-sider>
    <a-layout>
      <a-layout-content> -->
        <!-- {{ currentItem }} -->
        <!-- <bVideo ref="bVideoMainRef" :videoOption="{ autoPlay: true }" :videoKey="'main'+currentItem.id"/> -->
        <!-- <a-row>
          <a-col :span="12">
            <bVideo ref="bVideoMainRef" :videoOption="{ autoPlay: true }" :videoKey="'main'+currentItem.id"/>
          </a-col>
          <a-col :span="12">
            <bVideo ref="bVideoLeftRef" :videoOption="{ autoPlay: true }" :videoKey="'main2'+currentItem.id"/>
          </a-col>
        </a-row> -->
      <!-- </a-layout-content>
    </a-layout> -->
  <!-- </a-layout> -->
</template>
<script lang="ts" setup name="zhihuijiaoshiIndexPage">
import type { MenuProps } from 'ant-design-vue';
import { defHttp } from '/@/utils/http/axios';
import { useMessage } from "/@/hooks/web/useMessage";
import { ref, onMounted, onBeforeUnmount, reactive, computed, VideoHTMLAttributes } from 'vue';
import bVideo from '/@/views/site/common/webRTC/video.vue';
import { nextTick } from 'vue';

const bVideoRefs = <any>ref([]);
const _document = window.document;
// const bVideoLeftRef = ref();

const leftList = <any>ref([]);
const currentItem = <any>ref({});
const topWidth = <any>ref('0');
const mainVideoCardBoxTitle = <any>ref('');

const videoOption = reactive({
  // width: '800', //播放器高度
  // height: '450', //播放器高度
  color: "#409eff", //主题色
  title: '', //视频名称
  //src: "https://go.dreamwq.com/videos/IronMan.mp4", //视频源
  muted: true, //静音
  playsinline: true,
  webFullScreen: false,
  // speedRate: ["0.75", "1.0", "1.25", "1.5", "2.0"], //播放倍速
  autoPlay: false, //自动播放
  loop: false, //循环播放
  mirror: false, //镜像画面
  ligthOff: false,  //关灯模式
  volume: 0.3, //默认音量大小
  controls: true, //是否显示控制器
});


onMounted(() => {
  list({ pageSize: -1, sfyx: '0' }).then(res => {
    let list = (res?.records) ?? [];
    //聚合
    let map = {};
    list.forEach(x => {
      let item = map[x.jsmc];
      if(item){
        item.child[x.xm] = x;
      }else{
        let child = {};
        child[x.xm] = x;
        map[x.jsmc] = {
          ...x,
          child
        };
      }
    });

    leftList.value = Object.values(map);
    topWidth.value = _document?.querySelector('.ant-layout .jeecg-default-layout-main > div')?.style?.height?? '0';
    // console.log(_document?.querySelector('.ant-layout .jeecg-default-layout-main > div')?.style?.height?? '0')
  });
});

// const topWidthCalc = computed(() => {
//   return  _document?.querySelector('.ant-layout .jeecg-default-layout-main > div')?.style?.height?? '0';
// });
// xxx = document.querySelector('.ant-layout .jeecg-default-layout-main > div').style.height
//
enum Api {
  list = '/jiaoshi/kcZhihuijiaoshi/list',
}
/**
 * 列表接口
 * @param params
 */
const list = (params) => defHttp.get({ url: Api.list, params });


const selectedKeys = ref<string[]>(['1']);
const openKeys = ref<string[]>(['sub1']);
const titleClick = (e: Event, item: any) => {
  console.log('titleClick ->', e, item);
  currentItem.value = item;
  playerVideo(item);
};

function playerVideo(item){
  nextTick(() => {

    //changshang == 奥威亚
    // bVideoMainRef.value.connectFn(item.ip);
    //bVideoMainRef.value.connectFn('rtsp://176.139.87.16/axis-media/media.amp','external');
    // bVideoLeftRef.value.connectFn('rtsp://176.139.87.16/axis-media/media.amp','external');

    //rtsp://admin:admin@10.250.116.235:8554/live
    console.log('bVideoRefs ->',bVideoRefs,Object.values(bVideoRefs.value));

    (Object.keys(bVideoRefs.value)).forEach((key) => {
      console.log(`🚀 ~ file: index.vue:180 ~ key:`, key)
      // x.connectFn('rtsp://admin:admin@10.250.116.235:8554/live','external')
      // if(Number(Number(Math.random()).toFixed(1))*10 >= 5){
      //   x.connectFn('rtsp://127.0.0.1:8554/video','external');
      // }else{
      //   x.connectFn(`rtsp://${x.ip}/live`,'external')
      // }
      // return;
      let videoRef = bVideoRefs.value[key];
      console.log(`🚀 ~ file: index.vue:187 ~ videoRef:`, videoRef)
      
      let childItem = currentItem.value.child[key];
      console.log(`🚀 ~ file: index.vue:189 ~ childItem:`, childItem)
      if(!childItem){
        console.log('无法找到视频链接对象，currentItem.value.child[key] ->',currentItem,key);
        return;
      }
      if(childItem.changshang == '奥威亚'){
        videoRef.connectFn(`rtsp://${childItem.ip}/stream/0?config.login=web`,'external')
      }else if(childItem.changshang == '卓智'){
        videoRef.connectFn(`rtsp://${childItem.ip}/live`,'external')
      }else{
        videoRef.connectFn(`rtsp://${childItem.ip}/stream/0?config.login=web`,'external')
      }

    });

    // (Object.values(bVideoRefs.value)).forEach((videoRef: any) => {

    //   console.log(`🚀 ~ file: index.vue:148 ~ playerVideo ~ videoRef:`, videoRef);
    // });
    setTimeout(() => {
      switchVideoToMain();
    },1000);
  })
  //bVideoRefs['main'].connectFn('rtsp://admin:admin@10.250.116.235:8554/live','external');
}

function calcOtherVideo() :any{
  if(!currentItem.value.child) return {};
  let map = {};
  Object.keys(currentItem.value.child).forEach(key => {
    // if(key != '录播主机' && key.indexOf('音频处理器') ==-1){
      map[key] = currentItem.value.child[key];
    // }
  });
  return map;
}

function switchVideoToMain(){
  console.log(`🚀 ~ file: index.vue:188 ~ switchVideoToMain ~ switchVideoToMain: 自动切换第一个子界面到主界面`);
  nextTick(() => {
    let firstBox = <HTMLVideoElement> document.querySelector('.videoMax');
    let titleBox = <HTMLVideoElement> firstBox?.querySelector('.ant-card-head-title');
    let title = titleBox?.textContent;

    mainVideoCardBoxTitle.value = title;

    let mainVideo = <HTMLVideoElement> document.querySelector('#mainVideo');
    let firstVideo = <HTMLVideoElement> firstBox.querySelector('video');
    mainVideo.srcObject = firstVideo.srcObject
    mainVideo.play();
  });
}

function bVideoClick(e){
  console.log(`bVideoClick: 切换至主界面`);
  let mainVideo = <HTMLVideoElement> document.querySelector('#mainVideo');
  let currentVideo = <HTMLVideoElement> e.srcElement;

  let title = currentVideo?.parentElement?.parentElement?.querySelector('.ant-card-head-title')?.textContent
  mainVideoCardBoxTitle.value = title;
  console.log(`🚀 --------------------------------------------------------------------🚀`);
  console.log(`🚀 ~ file: index.vue:238 ~ bVideoClick ~ currentVideo:`, currentVideo);
  console.log(`🚀 --------------------------------------------------------------------🚀`);

  mainVideo.srcObject = currentVideo.srcObject
  mainVideo.play();
}


//页面销毁时销毁webRtc
onBeforeUnmount(() => {
  bVideoRefs.value.forEach(x => {
    x.closeWebRtcStreamerFn();
  });
})


</script>
<style lang="less" scoped>
.videoMax{
  width: 300px;
}
.videoCardMain {
  :deep(.ant-card-body) {
    padding: 0;
  }
}
/* 隐藏video 进度条 */
video::-webkit-media-controls-timeline {
    display: none;
}
</style>