<template>
  <Row type="flex" style="min-height: 790px" id="web-full-screen">
    <Col :xl="leftCol" :lg="leftCol" :md="leftCol" style="margin-bottom: 10px; margin-top: 12px; margin-left: 10px">
      <DeviceTree ref="leftTree" @select="onTreeSelect" />
    </Col>
    <div v-if="rightCol === 19" @click="leftSide" class="resize">
      <caret-left-outlined class="resize-side" />
    </div>
    <div v-if="rightCol === 24" @click="rightSide" class="resize">
      <caret-right-outlined class="resize-side" />
    </div>
    <Col :xl="rightCol" :lg="rightCol" :md="rightCol" style="margin-bottom: 10px; margin-top: 12px; margin-right: 10px">
      <div class="rightColDiv">
        <div
          style="
            display: flex;
            justify-content: flex-end;
            align-items: center;
            line-height: 35px;
            height: 35px;
            padding-top: 5px;
          "
        >
          <Tooltip placement="top" title="1分屏">
            <Icon
              :size="18"
              icon="ant-design:border-outlined"
              class="split-screen1"
              :class="{ active: spilt === 1 }"
              @click="spilt = 1"
            />
          </Tooltip>
          <Tooltip placement="top" title="4分屏">
            <Icon
              :size="18"
              icon="ant-design:appstore-outlined"
              class="split-screen"
              :class="{ active: spilt === 4 }"
              @click="spilt = 4"
            />
          </Tooltip>
          <Tooltip placement="top" title="9分屏">
            <Icon
              :size="18"
              icon="ant-design:table-outlined"
              class="split-screen"
              :class="{ active: spilt === 9 }"
              @click="spilt = 9"
            />
          </Tooltip>
          <Tooltip placement="top" title="全屏">
            <Icon :size="18" icon="ant-design:fullscreen-outlined" class="split-screen" @click="fullScreen" />
          </Tooltip>
        </div>
        <!--video-->
        <div style="padding: 0 10px 10px 0; height: calc(100vh - 155px)" id="video_show">
          <div style="width: 100%; height: 100%; display: flex; flex-wrap: wrap; background-color: #000">
            <div
              v-for="i in spilt"
              :key="i"
              class="play-box"
              :style="liveStyle"
              :class="{ redborder: playerIdx === i - 1 }"
              @click="selectPlayer(i - 1)"
            >
              <div v-if="!videoUrl[i - 1]" style="color: #ffffff; font-size: 30px; font-weight: bold">{{ i }}</div>
              <Jessibuca v-else ref="player" :src="videoUrl[i - 1]" fluent autoplay @screenshot="shot" />
            </div>
          </div>
        </div>
      </div>
    </Col>
  </Row>
</template>

<script lang="ts" setup>
  import { ref, computed, watch, nextTick, onMounted } from 'vue';
  import DeviceTree from './deviceTree.vue';
  import { Jessibuca } from '@jdlinker/ui';
  import { CaretLeftOutlined, CaretRightOutlined } from '@ant-design/icons-vue';
  import { playStart } from './DeviceService';
  import { onlyMessage } from '@jdlinker/utils';
  import { Row, Col, Tooltip } from 'ant-design-vue';

  const leftCol = ref(5);
  const rightCol = ref(19);
  const videoUrl = ref<any>([]);
  const spilt = ref(1); //分屏
  const playerIdx = ref(0); //激活播放器
  const player = ref();
  const loading = ref(true); //channel
  const liveStyle = computed(() => {
    let style = { width: '100%', height: '100%' };
    switch (spilt.value) {
      case 4:
        style = { width: '50%', height: '50%' };
        break;
      case 9:
        style = { width: '33.33%', height: '33.33%' };
        break;
    }
    return style;
  });

  watch(
    () => spilt.value,
    (newValue) => {
      for (let i = 1; i <= newValue; i++) {
        if (!player['player' + i]) {
          continue;
        }
        nextTick(() => {
          if (player['player' + i] instanceof Array) {
            player['player' + i][0].resize();
          } else {
            player['player' + i].resize();
          }
        });
      }
    }
  );
  // 左侧树选择后触发
  function onTreeSelect(data, basicData, isCatalog) {
    if (basicData.channelId && !isCatalog) {
      if (data.online === 0) {
        onlyMessage('设备离线!不允许点播', 'error');
      } else {
        sendDevicePush(data);
      }
    }
  }

  //通知设备上传媒体流
  function sendDevicePush(itemData) {
    // 测试播放示例
    // if (spilt.value === 1) {
    //   videoUrl.value[0] = itemData.basicData.ipAddress;
    // } else {
    //   if (playerIdx.value === videoUrl.value.length - 1) {
    //     playerIdx.value += 1;
    //   }
    //   videoUrl.value[playerIdx.value] = itemData.basicData.ipAddress;
    //   if (videoUrl.value.length === spilt.value) {
    //     playerIdx.value = 0;
    //   } else {
    //     playerIdx.value += 1;
    //   }
    // }

    loading.value = true;
    let deviceId = itemData.deviceId;
    if (!itemData.basicData.channelId) return;
    let channelId = itemData.basicData.channelId;
    playStart(deviceId, channelId)
      .then(function (res) {
        if (res) {
          itemData.playUrl = res.https_flv;
          let playUrl = location.protocol == 'https:' ? res.wss_flv : res.ws_flv;
          setPlayUrl(playUrl);
        } else {
          onlyMessage('error', 'error');
        }
      })
      .catch(function () {})
      .finally(() => {
        loading.value = false;
      });
  }

  function setPlayUrl(url) {
    if (spilt.value === 1) {
      videoUrl.value[0] = url;
    } else {
      if (playerIdx.value === videoUrl.value.length - 1) {
        playerIdx.value += 1;
      }
      videoUrl.value[playerIdx.value] = url;
      if (videoUrl.value.length === spilt.value) {
        playerIdx.value = 0;
      } else {
        playerIdx.value += 1;
      }
    }
  }

  function shot(e) {
    var base64ToBlob = function (code) {
      let parts = code.split(';base64,');
      let contentType = parts[0].split(':')[1];
      let raw = window.atob(parts[1]);
      let rawLength = raw.length;
      let uInt8Array = new Uint8Array(rawLength);
      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
      }
      return new Blob([uInt8Array], {
        type: contentType
      });
    };
    let aLink = document.createElement('a');
    let blob = base64ToBlob(e); //new Blob([content]);
    let evt = document.createEvent('HTMLEvents');
    evt.initEvent('click', true, true); //initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
    aLink.download = '截图';
    aLink.href = URL.createObjectURL(blob);
    aLink.click();
  }

  function leftSide() {
    leftCol.value = 0;
    rightCol.value = 24;
  }
  function rightSide() {
    leftCol.value = 5;
    rightCol.value = 19;
  }
  function fullScreen() {
    let dom = document.getElementById('video_show');
    if (dom?.requestFullscreen) {
      dom.style.padding = '0';
      dom.requestFullscreen();
    }
  }

  const checkFull = () => {
    let isFull = !!document.fullscreenElement;
    if (isFull === undefined || isFull === null) isFull = false;
    return isFull;
  };
  const selectPlayer = (data) => {
    playerIdx.value = data;
  };

  onMounted(() => {
    window.addEventListener('fullscreenchange', () => {
      // 监听到屏幕变化，在回调中判断是否已退出全屏
      if (!checkFull()) {
        const dom: any = document.getElementById('video_show');
        dom.style.padding = '0 10px 10px 0';
      }
    });
  });
</script>
<style lang="less" scoped>
  .ant-row {
    flex-flow: row nowrap;
  }
  .resize {
    cursor: pointer;
    position: relative;
    top: 45%;
    background-color: #d6d6d6;
    border-radius: 10px 0 0 10px;
    margin: auto 0;
    width: 10px;
    height: 50px;
    color: white;
    span.anticon:not(.app-iconify) {
      font-size: 12px;
      vertical-align: -9px !important;
    }
  }

  .bottom-icon {
    font-size: 20px;
    display: flex;
    margin-right: 8px;
  }
  .split-screen1 {
    display: flex;
    margin-right: 12px;
  }
  .split-screen {
    display: flex;
    margin-right: 12px;
  }
  .btn {
    margin: 0 10px;
  }
  .active {
    color: #3259de;
  }
  .btn:hover {
    color: #3259de;
  }

  .btn.active {
    color: #409eff;
  }

  .redborder {
    border: 0.5px solid #3259de !important;
  }

  .play-box {
    background-color: #000000;
    border: 0.5px solid #505050;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .rightColDiv {
    height: 100%;
    background-color: white;
    padding: 0 20px 0 10px;
  }
  [data-theme='dark'] .rightColDiv {
    background-color: #151515;
  }
</style>
