<template>
  <VueDragResize
    :w="width"
    :h="height"
    :x="left"
    :y="top"
    :isActive="true"
    :parentLimitation="true"
    @dragging="changeSize"
    @resizing="changeSize"
  >
    <div class="live-preview">
      <div class="preview-title">
        <div class="title-select">
          <div class="title-select-item">
            <span>镜头:</span>
            <a-select
              ref="select"
              v-model:value="selectVal.camera"
              style="width: 60px"
              :options="optionsArr.cameraOptions"
              @change="cameraChange"
            />
          </div>
          <div class="title-select-item">
            <span>分辨率:</span>
            <a-select
              ref="select"
              v-model:value="selectVal.resolution"
              style="width: 80px"
              :options="optionsArr.resolutionOptions"
              @change="resolutionChange"
            />
          </div>
        </div>
        <div class="title-icon">
          <PlayCircleOutlined title="开始直播" @click="startLiveFun" />
          <a-divider type="vertical" style="border-color: #4e5778" />
          <RedoOutlined title="刷新" @click="reloadLive" />
          <!-- <ExpandOutlined /> -->
          <a-divider type="vertical" style="border-color: #4e5778" />
          <PoweroffOutlined title="停止直播" @click="closeLive" />
        </div>
      </div>
      <div class="live-type">{{ cameraType }}</div>
      <div class="player" :style="{ height: height - 60 + 'px' }">
        <video
          id="player-container-id-live"
          :width="width"
          :height="height"
          preload="auto"
          playsinline
          webkit-playsinline
        >
        </video>
      </div>
    </div>
  </VueDragResize>
</template>
<script setup lang="ts">
  import { RedoOutlined, PlayCircleOutlined, PoweroffOutlined } from '@ant-design/icons-vue';
  import { reactive, onMounted, ref, watch, onBeforeUnmount } from 'vue';
  import { buildGUID } from '@/utils/uuid';
  import { getClient, createConnection } from '@/utils/mqtt';
  import {
    startLive,
    endLive,
    setCameraVideo,
    exchangeCamera,
  } from '@/api/workmanagement/airportMaintenance';
  import TCPlayer from 'tcplayer.js';
  import 'tcplayer.js/dist/tcplayer.min.css'; //引入插件和样式文件
  import {
    servicesTopic,
    services_replyTopic,
    errorName,
    setTopic,
  } from '@/utils/debugging/remote';
  import { useMessage } from '@/hooks/web/useMessage';
  import { airPortStore } from '@/store/modules/airport';
  import VueDragResize from 'vue-drag-resize/src';

  const airPortStoreVal = airPortStore();
  const live_info = airPortStoreVal.getLiveInfo;
  const uav = airPortStoreVal.getUAV;
  const { createMessage } = useMessage();
  const emits = defineEmits(['loadLiveStreaming', 'changeCameraType']);
  const props = defineProps({
    msgData: Object,
    uavLive: Boolean,
    airportLiveVisible: Boolean,
    uavStatus: Number,
  });
  const pageHeight = document.documentElement.clientHeight;
  const pageWidth = document.documentElement.clientWidth;
  const width = ref(500);
  const height = ref(348);
  const left = ref(pageWidth - 800);
  const top = ref(pageHeight - 460);
  if (props.airportLiveVisible) {
    top.value = pageHeight - 820;
  }
  let player;
  const liveCode = ref('6');
  watch(
    () => props.airportLiveVisible,
    (val) => {
      if (val) {
        top.value = pageHeight - 820;
      }
    },
  );
  const cameraType = ref('广角');

  const selectVal = reactive({
    camera: 'wide',
    resolution: 3,
  });
  const optionsArr = reactive({
    cameraOptions: [
      {
        label: '红外',
        value: 'ir',
      },
      {
        label: '广角',
        value: 'wide',
      },
      {
        label: '变焦',
        value: 'zoom',
      },
    ],
    resolutionOptions: [
      {
        label: '自适应',
        value: 0,
      },
      {
        label: '流畅',
        value: 1,
      },
      {
        label: '标清',
        value: 2,
      },
      {
        label: '高清',
        value: 3,
      },
      {
        label: '超清',
        value: 4,
      },
    ],
  });
  const startTid = buildGUID();
  const startLiveFun = () => {
    const querys = {
      bid: buildGUID(),
      method: 'live_start_push',
      tid: startTid,
      timestamp: new Date().getTime(),
      data: {
        url_type: 1, // 0 = 自适应；如需 RTMP 改为 1；GB28181 为 3；WebRTC 为 4
        url: live_info.rtmp + liveCode.value,
        video_id: uav.video_id,
        video_quality: selectVal.resolution, // 0=自适应，1=流畅，2=标清，3=高清，4=超清
      },
    };
    servicesTopic(querys);
    services_replyTopic();
  };
  const qualityTid = buildGUID();
  const resolutionChange = (val: any) => {
    const querys = {
      bid: buildGUID(),
      method: 'live_set_quality',
      tid: qualityTid,
      timestamp: new Date().getTime(),
      data: {
        video_id: uav.video_id,
        video_quality: val, // 0=自适应，1=流畅，2=标清，3=高清，4=超清
      },
    };
    servicesTopic(querys);
  };
  const lensTid = buildGUID();
  const cameraChange = (val: any) => {
    optionsArr.cameraOptions.forEach((item) => {
      if (item.value === selectVal.camera) {
        cameraType.value = item.label;
      }
    });
    emits('changeCameraType', val);
    const querys = {
      bid: buildGUID(),
      method: 'live_lens_change',
      tid: lensTid,
      timestamp: new Date().getTime(),
      data: {
        video_id: uav.video_id,
        video_type: val, // 0=自适应，1=流畅，2=标清，3=高清，4=超清
      },
    };
    console.log(querys);
    servicesTopic(querys);
  };
  const data = reactive({
    playedTime: 0,
    currentTime: 0,
    maxTime: 0,
  });
  const playVideo = () => {
    player = TCPlayer('player-container-id-live', {
      sources: [
        {
          src: live_info.url + liveCode.value + '.flv', // 播放地址
        },
      ],
      licenseUrl: live_info.url + liveCode.value + '.flv', // license 地址，必传。参考准备工作部分，在视立方控制台申请 license 后可获得 licenseUrl
    });
  };
  const stopTid = buildGUID();
  const closeLive = () => {
    const querys = {
      bid: buildGUID(),
      method: 'live_stop_push',
      tid: stopTid,
      timestamp: new Date().getTime(),
      data: {
        video_id: uav.video_id,
      },
    };
    servicesTopic(querys);
    emits('loadLiveStreaming');
  };
  const reloadLive = () => {
    player.src(live_info.url + liveCode.value + '.flv');
    player.play();
  };
  onMounted(() => {
    console.log(props.uavStatus);
    if (props.uavStatus == 0) {
      const querys = {
        bid: buildGUID(),
        tid: buildGUID(),
        timestamp: new Date().getTime(),
        data: {
          sub_device: {
            device_online_status: 1,
          },
        },
      };
      console.log(querys);
      setTopic(querys);
    }
    setTimeout(() => {
      // startLiveFun();
      playVideo();
      getClient().on('message', (topic, message) => {
        const rs = JSON.parse(message);
        if (rs.method == 'live_start_push' && rs.tid == startTid) {
          if (rs.data.result == 0) {
            createMessage.success('无人机开始直播成功');
            player.src(live_info.url + liveCode.value + '.flv');
            player.play();
          } else if (rs.data.result == 513003) {
            createMessage.success('无人机直播已开启');
            player.src(live_info.url + liveCode.value + '.flv');
            player.play();
          } else {
            createMessage.error('开始直播失败，' + errorName(rs.data.result));
          }
        } else if (rs.method == 'live_stop_push' && rs.tid == stopTid) {
          if (rs.data.result == 0) {
            createMessage.success('无人机停止直播成功');
            if (player) {
              // player.dispose();
            }
          } else {
            createMessage.error('无人机停止直播失败，' + errorName(rs.data.result));
          }
        } else if (rs.method == 'live_set_quality' && rs.tid == qualityTid) {
          if (rs.data.result == 0) {
            createMessage.success('无人机设置清晰度成功');
            player.src(live_info.url + '4.flv');
            player.play();
          } else {
            createMessage.error('无人机设置清晰度失败，' + errorName(rs.data.result));
          }
        } else if (rs.method == 'live_lens_change' && rs.tid == lensTid) {
          if (rs.data.result == 0) {
            createMessage.success('无人机设置直播镜头成功');
            player.src(live_info.url + liveCode.value + '.flv');
            player.play();
          } else {
            createMessage.error('无人机设置直播镜头失败，' + errorName(rs.data.result));
          }
        }
      });
    }, 2000);
  });
  const changeSize = (newRect) => {
    width.value = newRect.width;
    height.value = newRect.height;
  };
  // 销毁视频控件
  onBeforeUnmount(() => {
    if (player) {
      player.dispose();
      player = null;
    }
  });
</script>
<style lang="less" scoped>
  .video-js {
    width: 100%;
    height: 100%;
  }
  #live {
    width: 500px;
    height: 348px;
  }
  .live-preview {
    width: 100%;
    height: 100%;
    padding: 10px;
    background: #0d0e15;
    box-shadow:
      0px 10px 30px 0px rgba(0, 0, 6, 0.15),
      inset 0px 0px 36px 0px rgba(58, 87, 232, 0.73);
    border-radius: 6px;
    backdrop-filter: blur(3px);
    color: #fff;
    margin-top: 10px;
    .preview-title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .title-select {
        font-size: 12px;
        display: flex;
        align-items: center;
        .title-select-item {
          border: 1px solid #3a57e8;
          background: #0d0e15;
          box-shadow:
            0px 10px 30px 0px rgba(0, 0, 6, 0.15),
            inset 0px 0px 36px 0px rgba(58, 87, 232, 0.73);
          border-radius: 2px;
          padding-left: 4px;
          height: 38px;
          border-radius: 4px;
          display: flex;
          align-items: center;
          cursor: pointer;
          font-size: 12px;
          ::v-deep .ant-select-selector {
            background: none;
            border: none;
            color: #f4ba19;
            font-size: 12px;
            padding: 0 0 0 2px;
            .ant-select-selection-placeholder {
              color: #fff;
            }
          }
          ::v-deep .ant-select-selection-item {
            padding: 0;
          }
          ::v-deep .ant-select-arrow {
            color: #fff;
          }
          &:last-child {
            margin-left: 4px;
          }
        }
      }
      .title-icon {
        padding: 4px 6px;
        background: #0d0e15;
        box-shadow:
          0px 10px 30px 0px rgba(0, 0, 6, 0.15),
          inset 0px 0px 36px 0px rgba(58, 87, 232, 0.73);
        border-radius: 2px;
        border: 1px solid #3a57e8;
      }
    }
    .live-type {
      width: 40px;
      height: 40px;
      background: #0a99eb;
      box-shadow: 0px 10px 30px 0px rgba(0, 0, 6, 0.15);
      border-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      position: absolute;
      left: 0;
      top: 100px;
      z-index: 3;
    }
    .player {
      #player-container-id-live {
        height: 100%;
      }
    }
  }
</style>
