<template>
  <div class="mapcontainer">
    <gis-map :config="config" @load="handleLoad">
      <template v-if="mapLoaded">
        <TempWeatherLayer
          v-if="weathterList && weathterList.length > 0"
          :data="weathterList"
        />
        <EventLayer
          v-if="eventList && eventList.length > 0"
          :data="eventList"
          @layerClick="onEventLayerClick"
          @clusterLayerClick="onEventClusterLayerClick"
        />
        <HoverPopup :layer-ids="interactiveLayerIds">
          <template #default="{ layerId, data, feature }">
            <TempWeatherPopupContent
              v-if="layerId === 'tempWeather'"
              :data="data"
            />

            <!-- <TempWeatherClusterPopupContent
              v-else-if="layerId === 'tempWeatherCluster'"
              :data="data"
            /> -->

            <EventClusterPopupContent
              v-else-if="layerId === 'eventCluster'"
              :data="data"
              :feature="feature"
            />
            <!-- <EventPopupContent v-else-if="layerId === 'event'" :data="data" /> -->
          </template>
        </HoverPopup>
        <Popup
          v-if="eventSelected && eventSelected.lat && eventSelected.lng"
          key="eventSelectedPopup"
          :position="[eventSelected.lng, eventSelected.lat]"
          :options="{
            closeOnClick: true,
            closeButton: false,
          }"
          @close="onSelectedEventPopupClose"
        >
          <EventPopupContent
            :data="eventSelected"
            showCamera
            @cameraClick="onCameraClick"
          />
        </Popup>
      </template>
    </gis-map>
    <el-dialog
      title=""
      v-model="cameraPlayerDialogVisible"
      width="730px"
      :destroy-on-close="true"
    >
      <template #title></template>
      <div style="height: 20px"></div>
      <div>
        <div class="player" v-if="cameraUrl" style="height: 510px">
          <videoPlayer ref="videoplayer"></videoPlayer>
        </div>
        <div v-else style="width: 700px; height: 500px">
          <div class="offlinediv">当前监控设备暂时无法预览</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapState, mapMutations } from "vuex";
import { getVideoUrl } from "@/api/operation";
import { getKilometrePointWeathe } from "@/api/weather";
import GisMap from "@/components/GisMap/index.vue";
import Popup from "@/components/GisMap/Popup/index.vue";
import HoverPopup from "@/components/GisMap/HoverPopup/index.vue";
import EventLayer from "@/components/GisMap/layers/EventLayer.vue";
import EventClusterPopupContent from "@/components/GisMap/popups/EventClusterPopupContent.vue";
import EventPopupContent from "@/components/GisMap/popups/EventPopupContent.vue";
import VideoPlayerDialog from "@/components/VideoPlayerDialog/index.vue";
import { eventColor, eventIcon, eventTypeKey } from "./config";
import TempWeatherLayer from "./Weather/TempWeatherLayer.vue";
import TempWeatherPopupContent from "./Weather/TempWeatherPopupContent.vue";
import TempWeatherClusterPopupContent from "./Weather/TempWeatherClusterPopupContent.vue";
import videoPlayer from "@/views/videoSurveillance/newLayerContrl/components/videoPlayer.vue";

export default {
  components: {
    GisMap,
    Popup,
    HoverPopup,
    EventLayer,
    TempWeatherLayer,
    EventClusterPopupContent,
    EventPopupContent,
    TempWeatherPopupContent,
    TempWeatherClusterPopupContent,
    VideoPlayerDialog,
    videoPlayer,
  },
  data() {
    return {
      selectedMarker: null, // 选中事件标记图层
      selectedMarkerType: "", // 选中事件类型
      defaultZoom: 5,
      defaultCenter: ["105.8239515869493", "29.262943891582296"],
      realTimeEventMarker: [], // 实时事件marker
      provinceMarker: [
        {
          zb: [107.569855, 30.367095],
          id: "CQ",
          zoom: 6.8,
        },
        {
          zb: [102.928995, 30.52487],
          id: "SC",
          zoom: 5.8,
        },
        {
          zb: [101.593103, 25.353375],
          id: "YN",
          zoom: 6,
        },
        {
          zb: [106.641243, 27.10797],
          id: "GZ",
          zoom: 6.5,
        },
        {
          zb: [117.229929, 32.325398],
          id: "AH",
          zoom: 6.5,
        },
      ],
      mapLoaded: false,
      weathterList: null, // 当前查询的天气列表
      cameraPlayerDialogVisible: false,
      cameraUrl: null,
    };
  },
  computed: {
    ...mapState({
      map: (state) => state.map.map,
      config: (state) => state.map.config,
      selectRoadId: (state) => state.road.selectRoadId,
      eventSelected: (state) => state.monitor.eventSelected,
      eventList: (state) => state.monitor.eventList,
      boundaryLineFace: (state) => state.map.boundaryLineFace,
      selectedCameraId: (state) => state.monitor.selectedCameraId,
    }),
    interactiveLayerIds() {
      return ["tempWeather", "tempWeatherCluster", "event", "eventCluster"];
    },
  },
  watch: {
    // 选中路段切换 路段居中
    selectRoadId(newVal) {
      this.getChangeRoads(newVal[0]);
    },
    // 添加选中事件标记
    eventSelected(newVal) {
      this.$nextTick(() => {
        if (newVal && newVal.lng && newVal.lat) {
          let selectedCenter = [newVal.lng, newVal.lat];
          // this.addSelectedMarker(newVal);
          this.map.flyTo({
            center: selectedCenter,
            zoom: 14,
          });
        } else {
          // this.removeSelectedMarker();
          //   if (!this.selectedCameraId) {
          //     this.map.flyTo({
          //       center: this.defaultCenter,
          //       zoom: this.defaultZoom,
          //     });
          //   }
        }
      });
    },
    // 实时事件更新 更新地图marker
    // eventList() {
    //   this.map && this.addRealTimeEventMarker();
    // },
  },
  created() {
    this.$store.dispatch("map/getMapConfig");
  },
  async mounted() {
    const res = await getKilometrePointWeathe();
    if (res && res.result) {
      this.weathterList = Object.freeze(
        res.result.reduce((acc, curr) => {
          return acc.concat(curr.weathers);
        }, [])
      );
    }
  },
  methods: {
    ...mapMutations("monitor", ["setEventSelected", "setEventList"]),
    // 路段切换
    getChangeRoads(name) {
      if (!this.map) {
        return;
      }
      if (name) {
        this.provinceClick(name);
      } else {
        //高亮所有省份
        // this.map.setZoom(4.8);
        // this.map.setCenter([107.85585, 28.465908]);
        this.map.setZoom(5.2);
        this.map.setCenter([104.07751, 28.55365]);
        this.boundaryLineFace.forEach((el) => {
          this.map.setLayoutProperty(el.layerIdl, "visibility", "visible");
          this.map.setLayoutProperty(el.layerIdf, "visibility", "visible");
        });
        const qmz = JSON.parse(localStorage.getItem("mapCLkmz"));
        this.map.setLayoutProperty(qmz.ROUTE, "visibility", "none");
      }
    },
    // 单独高亮某个省份
    provinceClick(name) {
      this.provinceMarker.forEach((el) => {
        if (name === el.id) {
          this.$nextTick(() => {
            this.map.flyTo({
              center: el.zb,
              zoom: el.zoom,
            });
          });
        }
      });
      this.boundaryLineFace.forEach((el) => {
        const state = name == el.code ? "visible" : "none";
        this.map.setLayoutProperty(el.layerIdl, "visibility", state);
        this.map.setLayoutProperty(el.layerIdf, "visibility", state);
      });
      const qmz = JSON.parse(localStorage.getItem("mapCLkmz"));
      this.map.setLayoutProperty(qmz.ROUTE, "visibility", "none"); //所有路段
    },
    // gis地图加载
    handleLoad(data) {
      this.mapLoaded = true;
      this.$store.commit("map/setMap", data.map);
      this.getChangeRoads(this.selectRoadId[0]);
      //   this.addRealTimeEventMarker();
      // setTimeout(() => {
      //   const params = {
      //     lng: this.provinceMarker[0].zb[0],
      //     lat: this.provinceMarker[0].zb[1],
      //     eventType: 'realTimeEvent',
      //     seventKind: '交通事故',
      //   }
      //   this.setEventSelected(params)
      // }, 1000)
      // setTimeout(() => {
      //   // this.setEventSelected({})
      //   this.setEventList([])
      // }, 5000)
    },
    // 删除地图marker
    removeMarker(data) {
      data.map((layer) => {
        layer.remove();
      });
    },
    // 事件地图标记
    addRealTimeEventMarker() {
      this.removeMarker(this.realTimeEventMarker);
      this.realTimeEventMarker = [];
      this.selectedMarkerType === "realTimeEvent" && this.setEventSelected({});
      this.eventList.forEach((item, index) => {
        // if (!item.lng && !item.lat) {
        //   item.lng = this.provinceMarker[index] ? this.provinceMarker[index].zb[0] : ''
        //   item.lat = this.provinceMarker[index] ? this.provinceMarker[index].zb[1] : ''
        // }
        if (!item.lng || !item.lat) {
          return;
        }
        let marker = this.createMarker({ ...item, eventType: "realTimeEvent" });
        let popup = this.createPopup(item);
        marker.setPopup(popup).addTo(this.map);
        this.realTimeEventMarker.push(marker);
      });
    },
    bottomIcon(colorType) {
      return `./images/eventtype/bottom/bottom-${colorType}.png`;
    },
    circleIcon(colorType) {
      return `./images/eventtype/circle/circle-${colorType}.png`;
    },
    eventIcon(eventType) {
      return `./images/eventtype/${eventType}.png`;
    },
    // 创建marker
    createMarker(params = {}, options = {}) {
      let { eventType, lng, lat } = params;
      let { rotating } = options;
      let typeKey = params[eventTypeKey[eventType]];
      let color = eventColor[eventType] || "red";
      let iconType = eventIcon[typeKey] || eventIcon[`${color}Default`];
      // 容器
      let el = document.createElement("div");
      el.className = "marker";
      // 顶部
      let top = document.createElement("div");
      top.className = "top";
      let circleImg = document.createElement("img");
      circleImg.className = rotating ? "circleImg rotating" : "circleImg";
      circleImg.src = this.circleIcon(color);
      // 圆
      let circle = document.createElement("div");
      circle.className = "circle";
      // 事件图标
      let icon = document.createElement("div");
      icon.className = "icon";
      icon.style.backgroundImage = `url(${this.eventIcon(iconType)})`;
      // 底部
      let bottom = document.createElement("div");
      bottom.className = "bottom";
      bottom.style.backgroundImage = `url(${this.bottomIcon(color)})`;
      // 加入元素
      el.appendChild(top);
      el.appendChild(bottom);
      top.appendChild(circleImg);
      top.appendChild(circle);
      circle.appendChild(icon);
      return new minemap.Marker(el, { offset: [-19, -60] }).setLngLat([
        lng,
        lat,
      ]);
    },
    // 创建事件marker弹框
    createPopup(data) {
      const {
        comments,
        roadname,
        stake,
        eventDesc,
        eventHappenDt,
        eventEndDt,
        direction,
      } = data;
      var el = document.createElement("div");
      el.className = "custom-popup-class";
      var d1 = document.createElement("div");
      d1.style.cssText = "max-width:200px;";
      d1.innerHTML = `<div>桩号：${stake}</div><div>发生时间：${eventHappenDt}</div><div>事件详情：${eventDesc}</div>`;
      el.appendChild(d1);

      var popup = new minemap.Popup({
        closeOnClick: true,
        closeButton: true,
        offset: [0, -70],
      }).setDOMContent(el);
      return popup;
    },
    // 添加选中事件标记
    addSelectedMarker(params) {
      this.selectedMarker && this.removeSelectedMarker();
      let marker = this.createMarker(params, { rotating: true });
      marker.addTo(this.map);
      this.selectedMarker = marker;
      this.selectedMarkerType = params.eventType;
    },
    // 删除选中事件标记
    removeSelectedMarker() {
      this.selectedMarker && this.selectedMarker.remove();
      this.selectedMarker = null;
      this.selectedMarkerType = "";
    },

    onEventLayerClick(evt) {
      const { properties } = evt.features[0];
      properties &&
        this.$store.dispatch("monitor/setEventSelected", {
          ...properties,
          eventType: "realTimeEvent",
        });
    },
    onEventClusterLayerClick(evt) {
      console.log("onEventClusterLayerClick", evt);
    },
    onSelectedEventPopupClose() {
      this.setEventSelected(null);
    },
    onCameraClick(evt) {
      console.log("111111111onCameraClick", evt);
      const { id: camearId } = evt.camera;
      if (!camearId) {
        return;
      }
      this.playCameraVideo(camearId);
    },
    async playCameraVideo(camearId) {
      const res = await getVideoUrl(camearId);
      if (res?.data) {
        this.cameraUrl = res.data;
      } else {
        this.cameraUrl = null;
      }
      this.cameraPlayerDialogVisible = true;
      this.$nextTick(() => {
        this.$refs.videoplayer.createPlayer(this.cameraUrl, camearId);
      });
    },
  },
};
</script>
<style lang="postcss" scoped>
.mapcontainer {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
}
::v-deep(.custom-popup-class) {
  color: #fff !important;
  padding: 10px;
}
::v-deep(.selectedMarker) {
  width: 58px;
  height: 72px;
  background-size: cover;
}
::v-deep(.top) {
  width: 38px;
  height: 38px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-repeat: no-repeat;
  position: relative;
}
::v-deep(.circleImg) {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}
::v-deep(.circle) {
  width: 28px;
  height: 28px;
  background: #fff;
  border-radius: 50%;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}
::v-deep(.icon) {
  width: 18px;
  height: 18px;
  background-size: cover;
  position: absolute;
  z-index: 2;
}
::v-deep(.bottom) {
  width: 38px;
  height: 22px;
  background-position: center center;
  background-repeat: no-repeat;
  margin-top: 2px;
}
::v-deep(.rotating) {
  animation: run 2s linear infinite;
}
@keyframes run {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

::v-deep(.el-dialog__header) {
  padding: 0;
}
::v-deep(.el-dialog__body) {
  background-image: url("@/assets/images/expressway/popbg.png") !important;
  background-size: 100% 100% !important;
}
.offlinediv {
  position: absolute;
  top: 45%;
  left: 0;
  width: 100%;
  text-align: center;
  font-size: 16px;
}
</style>
