<template>
  <div class="vmap">
    <div id="map" class="map-animation"></div>
  </div>
</template>
<script setup lang="js">
import './map.scss';
import { icons, MapDefaultData } from './constants.js';
import { onMounted } from 'vue';
import { deviceManageList } from '#/api/sis/deviceManage/index.js';
import { deviceChannelList } from '#/api/sis/deviceChannel/index.js';
import mpegts from 'mpegts.js';
import { message } from 'ant-design-vue';
import {
  addFFmpegMediaStreamProxy,
  addMediaStreamProxy,
} from '#/api/sis/stream/index.js';
import { checkHEVCSupport } from '#/utils/video.js';

// 地图全局对象
let map = null;
let currentPlayer;
let videoElement;
let isSupportH265 = false;
onMounted(() => {
  // 检测浏览器是否支持h265
  isSupportH265 = checkHEVCSupport();
  mapFn.intiMap();
  // 加载设备信息
  loadCameraData();
  // 增加视频追帧操作
  setInterval(catchUp, 10000);
});

function catchUp() {
  if (currentPlayer) {
    const end = currentPlayer.buffered.end(player.buffered.length - 1);
    const diff = end - videoElement.currentTime;
    if (diff > 2) {
      // 如果延迟超过2秒
      videoElement.currentTime = end - 0.5; // 跳转到接近直播点
    }
  }
}

function loadCameraData() {
  deviceManageList({ deviceType: 1 }).then(({ rows = [], total = 0 }) => {
    if (total > 0) {
      // 渲染设备点位信息
      let items = rows.map((item) => {
        return {
          icon: 'camera',
          data: item,
          lon: item.lon,
          lat: item.lat,
        };
      });
      mapFn.renderOverLayersData(items, function (marker, data) {
        // 渲染设备点击事件
        marker.addEventListener('click', () => {
          // 查询当前设备的通道信息
          const params = {
            deviceIp: data.deviceIp,
            pageNum: 1,
            pageSize: 10,
          };
          deviceChannelList({ deviceIp: data.deviceIp }).then(
            ({ total, rows }) => {
              console.log(data);
              const deviceData = { ...data };
              if (total > 0) {
                //渲染设备播放列表
                const deviceName = deviceData.deviceName;
                const html = [
                  '<div class="video-wrap" style="width: 530px;height: 330px;padding-top:50px">',
                  `<div class="wrap-title" style="margin-top: -35px;">${deviceName}</div>`,
                  `<div class="close" onclick="pageEvent.closeInfoWindow()">X</div>`,
                  `<div class="wrap-content">`,
                  `<div class="content-left" style="height: 260px">`,
                  '<video id="video-player" ref="player1" muted autoplay></video>',
                  `</div>`,
                  `</div>`,
                  `</div>`,
                ];
                const infoWindow = new BMap.InfoWindow(html.join(''), {
                  width: 530,
                  height: 350,
                  enableCloseOnClick: false,
                });
                map.openInfoWindow(infoWindow, marker.point);
                const data = rows[0];
                const params = {};
                if (data.nvrIp) {
                  params.deviceIp = data.nvrIp;
                  params.channelNo = data.nvrChannelNo;
                } else {
                  params.deviceIp = data.deviceIp;
                  params.channelNo = data.channelNo;
                }
                doPlayer(params);
              }
            },
          );
        });
      });
    }
  });
}

/**
 * 开始播放视频流
 * @param nodeData 播放的节点数据
 */
function doPlayer(nodeData) {
  if (mpegts.isSupported()) {
    streamProxy(nodeData, (res) => {
      const url = res.flv;
      // 将url 绑定到 nodeData
      nodeData.url = url;
      closeVideo(currentPlayer);
      const videoConfig = {
        type: 'flv',
        url: url,
        isLive: true,
        hasAudio: false,
        hasVideo: true,
        enableWorker: true, // 启用分离的线程进行转码
        enableStashBuffer: false, // 关闭IO隐藏缓冲区
        stashInitialSize: 256, // 减少首帧显示等待时长
      };
      const playerConfig = {
        enableErrorRecover: true, // 启用错误恢复
        autoCleanupMaxBackwardDuration: 30,
        autoCleanupMinBackwardDuration: 10,
      };
      const player = mpegts.createPlayer(videoConfig, playerConfig);
      const videoElement = document.getElementById('video-player');
      if (videoElement) {
        player.attachMediaElement(videoElement);
        player.load();
        player.play();
      } else {
        console.log('视频播放元素获取异常');
      }
    });
  } else {
    message.error('浏览器不支持播放');
  }
}

function streamProxy(params, cb) {
  if (isSupportH265) {
    addMediaStreamProxy(params).then((res) => cb(res));
  } else {
    // addMediaStreamProxy(params).then((res) => cb(res));
    addFFmpegMediaStreamProxy(params).then((res) => cb(res));
  }
}

// 当前页面播放的对象
window.pageEvent = {
  closeInfoWindow() {
    map.closeInfoWindow();
    closeVideo(currentPlayer);
    currentPlayer = null;
  },
};

function closeVideo(player) {
  if (player) {
    try {
      player.pause();
      player.unload();
      player.destroy();
    } catch (e) {
      console.log(e);
    }
  }
}

/* 地图相关方法 */
const mapFn = {
  renderOverLayersData(data, cb, clear = true) {
    // 清楚地图上的图层
    if (clear) {
      mapFn.clearLayers();
    }
    data.forEach((v) => {
      const { lon, lat, data, icon } = v;
      const marker = new BMap.Marker(new BMap.Point(lon, lat), {
        icon: icons[icon],
      });
      // 将数据放入marker
      marker.data = data;
      marker.setTop(true, 100);
      // 保存自定义信息到marker对象中
      map.addOverlay(marker);
      if (cb) {
        cb(marker, data);
      }
    });
  },
  /**
   * 清除地图上的所有图层
   */
  clearLayers: () => map.clearOverlays(),

  /**
   * 初始化地图
   * @param cb 地图初始化的回调函数
   */
  intiMap: function (cb) {
    // 创建地图实例
    map = new BMap.Map('map', { enableMapClick: false });
    // 设置地图中心和初始层级
    map.centerAndZoom(
      new BMap.Point(MapDefaultData.center[0], MapDefaultData.center[1]),
      MapDefaultData.zoom,
    );
    // 设置地图样式
    map.setMapStyleV2({
      styleId: 'bbb822feddbffbb4dc419fc6c37f2e4e',
    });
    // 开启滚轮缩放
    map.enableScrollWheelZoom(true);
    map.clearOverlays();
    if (cb) {
      cb();
    }
  },
};
</script>
