<template>
  <div id="homeMap">
    <div id="container" class="map" />

    <div
      v-if="showModal.show"
      style="
        position: fixed;
        top: 0px;
        left: 50%;
        transform: translateX(-50%);
        z-index: 1000000;
        padding: 40px;
        bottom: 0;
      "
    >
      <div style="background-color: #063586">
        <div
          style="
            display: flex;
            align-items: center;
            background-color: #e2e2e2;
            padding: 5px 10px;
          "
        >
          <videoLine
            style="flex: 1"
            :cameraCode="showModal.data.cameraCode"
          ></videoLine>
          <div
            @click="showModal.show = false"
            style="font-size: 20px; line-height: 1em; margin-left: 10px"
          >
            X
          </div>
        </div>
        <videoPlayer :camera-code="showModal.data.cameraCode" :flay="false" />
      </div>
    </div>
    <warningDispose
      v-if="warningDisposeModal.show"
      :id="warningDisposeModal.id"
      @close="warningDisposeModal.show = false"
      @success="releaseSuccess"
    ></warningDispose>
  </div>
</template>

<script>
import warningDispose from "@/components/warning/warningDispose.vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import flvjs from "flv.js";
import { releaseAlarm } from "@/api/alarmList";
import { homeGetInfo } from "@/api/account/camera";
import { lineDate, invite } from "@/api/video";
import videoPlayer from "@/components/videoPlayer/videoPlayer";
import videoLine from "@/components/videoPlayer/videoLine";
import { formatTime } from "@/utils/utils";
import { getSelectCameraAll } from "@/api/account/camera";

// homeMap
export default {
  name: "HomeMap",
  components: { videoPlayer, videoLine, warningDispose },
  data() {
    return {
      warningDisposeModal: {
        show: false,
        id: "",
      },
      isLoad: false,
      showModal: {
        show: false,
        data: {
          cameraCode: "",
          line: "",
          mileagePosition: "",
          electricQuantity: "",
          cameraCoding: "",
          cameraCode: "",
        },
      },
      AMap: "",
      map: "",
      markerList: [],
      markers: [],
      player: "",
      infoWindow: null, // 窗口控制器
    };
  },
  watch: {
    markerList() {
      this.markerListChange("watch");
    },
  },
  mounted() {
    this.getData();
  },
  beforeUnmount() {},
  methods: {
    getData() {
      getSelectCameraAll().then((data) => {
        this.markerList = data.data;
        if (this.AMap) {
          this.markerListChange();
        } else {
          this.initMap();
        }
      });
    },
    // 地图初始化
    initMap() {
      AMapLoader.load({
        key: "374b34c9c0cc57951f2006c96bdd0a89", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.ToolBar", "AMap.Driving"], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
        .then((AMap) => {
          this.AMap = AMap;
          this.map = new AMap.Map("container", {
            // 设置地图容器id
            // viewMode:"3D",    //是否为3D地图模式
            resizeEnable: true,
            zoom: 12, // 初始化地图级别
            zooms: [4, 18], // 设置地图级别范围
            mapStyle: "amap://styles/darkblue", // 设置地图的显示样式
            // center: [116.405285, 39.904989] // 中心点通过marker设置，也可以给一个默认的
          });

          this.isLoad = true;
          this.markerListChange("init");
        })
        .catch((e) => {
          console.log(e);
        });
    },
    // marker点发生变化
    markerListChange(type) {
      if (this.isLoad === false) return false;

      if (this.markers.length > 0) this.map.remove(this.markers);

      if (this.infoWindow) {
        this.infoWindow.close();
        this.infoWindow = null;
      }

      const AMap = this.AMap;
      this.markers = [];

      console.log("点列表", this.markerList);

      this.markerList.forEach((item) => {
        if (item.isLock == null) return false;

        let img = item.isLock === 1 ? "/icon1.png" : "/icon2.png";

        const startIcon = new this.AMap.Icon({
          size: new AMap.Size(60, 60),
          image: img,
          imageSize: new AMap.Size(60, 60),
          imageOffset: new AMap.Pixel(-9, -3),
        });

        const marker = new AMap.Marker({
          map: this.map,
          size: new AMap.Size(60, 60),
          icon: startIcon,
          position: [
            parseFloat(item.installLongitude),
            parseFloat(item.installLatitude),
          ],
          offset: new AMap.Pixel(-13, -30),
        });

        // 鼠标点击marker弹出自定义的信息窗体
        marker.on("click", () => {
          console.log("打开窗口", item);

          homeGetInfo({
            id: item.id,
            isLock: item.isLock,
            cameraCode: item.cameraCode,
          }).then((res) => {
            this.infoWindowShow(marker, res.data, item.isLock);
          });
        });

        this.markers.push(marker);
      });

      if (type == "init") {
        this.map.setFitView(null, false, [150, 60, 100, 60]);
        this.map.getCenter();
      }
    },
    infoWindowShow(marker, item, isLock) {
      console.log("打开窗口", marker, item, isLock);

      const AMap = this.AMap;
      this.infoWindow = new AMap.InfoWindow({
        isCustom: true, // 使用自定义窗体
        content:
          isLock == 1
            ? this.createInfoWindowOne(item)
            : this.createInfoWindowTwo(item),
        offset: new this.AMap.Pixel(0, -30),
      });

      this.infoWindow.open(this.map, marker.getPosition());

      setTimeout(() => {
        // 关闭按钮
        const videoClose = document.getElementById(`map-close-${item.id}`);
        videoClose.onclick = () => {
          this.infoWindow.close();
          this.infoWindow = null;
          this.videoClose();
        };

        if (isLock == 1) {
          const openvideo = document.getElementById(`map-openvideo-${item.id}`);
          openvideo.onclick = () => {
            this.showModal.data.cameraCode = item.cameraCode;
            this.showModal.show = true;
          };
          return false;
        }

        // 模式2 关闭事件/去详情事件/解除事件
        const toDetails = document.getElementById(`map-details-${item.id}`);
        const toRelease = document.getElementById(`map-release-${item.id}`);
        const button1 = document.getElementById(`map-button1-${item.id}`);
        const button2 = document.getElementById(`map-button2-${item.id}`);
        const video = document.getElementById(`map-video-${item.id}`);
        const image = document.getElementById(`map-image-${item.id}`);

        button1.onclick = () => {
          button1.style.backgroundColor = "#20a0ff";
          button1.style.color = "#fff";
          image.style.display = "block";

          this.videoClose();
          button2.style.backgroundColor = "#fff";
          button2.style.color = "#000";
          video.style.display = "none";
        };

        button2.onclick = () => {
          invite(item.alarmId).then((res) => {
            this.$router.push({
              path: `/alarmDetail?cameraCode=${
                item.cameraCode
              }&alarmId=${item.alarmId}&startTime=${formatTime(
                new Date(item.alarmTime).getTime() / 1000 - 60 * 10,
                "Y-M-D h:m:s"
              )}&entTime=${formatTime(
                new Date().getTime() / 1000,
                "Y-M-D h:m:s"
              )}`,
            });
          });
        };

        toDetails.onclick = () => {
          this.toDetails(item);
        };

        toRelease.onclick = () => {
          this.release(item, toRelease);
        };
      }, 1000);
    },
    createInfoWindowOne(info) {
      const html = `
        <div style="background-color: #blue;width: 300px;height:200px;font-size: 16px;padding:10px;background: linear-gradient(0deg, rgba(17,43,86,0.5), rgba(26,75,149,0.5));box-shadow: 0px 0px 5px #20a0ff">
          <div style="font-size: 16px;display:flex;justify-content: space-between;align-items: center;color:#fff"><div>${info.railwayName}</div> <div id="map-close-${info.id}" style="flex-shrink: 0;">X</div></div>
          <div style="width: 100%;height: 1px;background-color: #2766dd;margin-top:5px"></div>
          <div style="margin-top: 10px;font-size:14px">
            <div style="display: flex;margin-top: 10px;color:#ccc"><div>里程位置:</div><div style="margin-left:10px">${info.installMiles}</div></div>
            <div style="display: flex;margin-top: 10px;color:#ccc"><div>里程范围:</div><div style="margin-left:10px">${info.beginMiles}～${info.endMiles}</div></div>
            <div style="display: flex;margin-top: 10px;color:#ccc"><div>经纬度:</div><div style="margin-left:10px">${info.installLongitude}，${info.installLatitude}</div></div>
          </div>
          <div style="margin-top: 40px;margin-right: 20px;display: flex;justify-content: flex-end;">
            <div class="queryVideo" id="map-openvideo-${info.id}" style="padding: 3px 5px;border-radius:2px ;font-size:12px;cursor: pointer;background-color: #2866dd;color: #fff;line-height:1em;" >查看视频</div>
          </div>
      </div>`;

      return html;
    },
    // 构建自定义信息窗体
    createInfoWindowTwo(info) {
      let isLockText = info.isLock == 1 ? "已解除" : "未解除";
      let alarmTypeText = info.alarmType == 1 ? "泥石流" : "未配置类型";

      const html = `
        <div style="background-color: #ffffff;width: 250px;font-size: 13px;padding: 10px;">
          <div style="font-size: 16px;display:flex;justify-content: space-between;align-items: center;"><div>${info.railwayName}线路</div> <div id="map-close-${info.id}" style="flex-shrink: 0;">X</div></div>
          <div style="width: 100%;height: 1px;background-color: #d2d2d2;"></div>
          <div style="display: flex;justify-content: space-between;margin-top: 10px;color: red;"><div>${alarmTypeText}</div><div>${isLockText}</div></div>
          <video id="map-video-${info.id}" autoplay controls muted preload="auto" style="display:none; width: 100%;height: 100px;margin-top: 10px;"  type="rtmp/flv" >
            <source src="">
          </video>
          <img id="map-image-${info.id}" src="${info.imageUrls[0]}" style="width: 100%;height: 100px;margin-top: 10px;">
          <div style="display:flex;justify-content:flex-end;margin-top:5px;">
            <div id="map-button1-${info.id}" style="padding:4px 6px;line-height:1em;margin-right:4px;background-color:#20a0ff;color:#fff;">图片</div>
            <div id="map-button2-${info.id}" style="padding:4px 6px;line-height:1em;">视频</div>
          </div>
          <div>报告详细信息</div>
          <div style="margin-top: 10px;">
            <div style="display: flex;justify-content: space-between;margin-top: 5px;"><div>里程位置</div><div>${info.alarmMile}</div></div>
            <div style="display: flex;justify-content: space-between;margin-top: 5px;"><div>里程范围</div><div>${info.beginMile}</div></div>
            <div style="display: flex;justify-content: space-between;margin-top: 5px;"><div>经纬度</div><div>${info.installLongitude}</div></div>
            <div style="display: flex;justify-content: space-between;margin-top: 5px;"><div>时间</div><div>${info.alarmTime}</div></div>
          </div>
          <div style="margin-top: 20px;display: flex;justify-content: center;">
            <div id="map-release-${info.id}" style="display: flex;align-items: center;justify-content: center;border:solid 1px #20a0ff;border-radius: 4px;width: 70px;padding: 4px 0px;">解除</div>
            <div id="map-details-${info.id}" style="display: flex;align-items: center;justify-content: center;border:solid 1px #20a0ff;border-radius: 4px;width: 70px;padding: 4px 0px;margin-left: 10px;">查看详情</div>
          </div>
      </div>`;

      return html;
    },
    videoPlay(info, videoUrl) {
      if (videoUrl) {
        this.videoPlayStart(info, videoUrl);
      } else {
        records(this.cameraCode).then((res) => {
          this.videoPlayStart(info, res.data);
        });
      }
    },
    videoPlayStart(info, url) {
      // 检查视频是否已经存在
      if (flvjs.isSupported()) {
        this.videoClose();

        const videoElement = document.getElementById(`map-video-${info.id}`);

        this.player = flvjs.createPlayer(
          {
            type: "flv",
            url: url, // 你的url地址
            isLive: true, // 数据源是否为直播流
            hasAudio: true, // 数据源是否包含有音频
            hasVideo: true, // 数据源是否包含有视频
            enableStashBuffer: true, // 是否启用缓存区
          },
          {
            enableWorker: false, // 不启用分离线程
            enableStashBuffer: false, // 关闭IO隐藏缓冲区
            autoCleanupSourceBuffer: true, // 自动清除缓存
            lazyLoad: false,
          }
        );

        this.player.attachMediaElement(videoElement);
        this.player.load();
        this.player.play();

        this.player.on(flvjs.LOADING_COMPLETE, () => {
          console.log("bofangweanc");
        });
      }
    },
    videoClose() {
      if (this.player) {
        this.player.pause();
        this.player.unload();
        this.player.detachMediaElement();
        this.player.destroy();
        this.player = null;
      }
    },
    toDetails(info) {
      this.$router.push({
        path: "/alarmDetail",
        query: { id: info.id, cameraCode: info.cameraCode },
      });
    },
    release(info) {
      this.warningDisposeModal.id = info.id;
      this.warningDisposeModal.show = true;
    },
    releaseSuccess() {
      console.log("解除成功");
      this.warningDisposeModal.id = "";
      this.warningDisposeModal.show = false;
      this.getData();
    },
  },
};
</script>

<style scoped lang="scss">
.map {
  width: 100%;
  height: 100%;
  padding: 0px;
  margin: 0px;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 0;

  .queryVideo:hover {
    background: #4d85f4;
  }
}

#homeMap {
  ::v-deep .yes.xgplayer {
    width: auto !important;
    height: auto !important;
    max-width: auto !important;
    padding-top: 0px !important;
  }

  ::v-deep .xgplayer video {
    position: static !important;
    width: auto !important;
    height: 85vh !important;
    outline: none !important;
  }
}
</style>
