<template>
  <div class="monitoringMap" id="mapcontainer"></div>
  <div :style="{ display: 'none' }">
    <InfoWindow class="infoBox" :value="locationInfo" @close="InfoWin.close()" />
  </div>
</template>
<script lang="ts" setup>
import { locateRecord } from "@/api";
import { format } from "@/utils";
import { MapCustom } from "@/utils/mapCustom";
import { onMounted, ref, watch } from "vue";
import InfoWindow from "@/components/InfoWindow.vue";
import ViaMarker from "@/assets/img/via-marker.png";
import endMarker from "@/assets/img/end-marker.png";
import startMarker from "@/assets/img/start-marker.png";

let InfoWin = null;
let newMap = null;
let locationInfo = ref({});

const props = defineProps({
  deviceId: {
    type: String || Number,
    default: "",
  },
});

watch(
  () => props.deviceId,
  (newVal) => {
    if (newVal) {
      getLocateRecord();
    }
  }
);

const getLocateRecord = () => {
  let d = new Date();
  locateRecord({
    deviceId: props.deviceId,
    startDate: `${format(d, "YYYY-MM-DD")} 00:00:00`,
    endDate: `${format(d, "YYYY-MM-DD")} 23:59:59`,
  }).then((res) => {
    if (res && res.length) {
      let list = res;
      newMap.clearMap();
      newMap.setCenter([list[0].lng, list[0].lat]);
      newMap.polyline(list);
      let startIcon = newMap.newIcon({
        image: startMarker,
        size: [20, 29],
      });
      let endIcon = newMap.newIcon({
        image: endMarker,
        size: [20, 29],
      });
      let ViaIcon = newMap.newIcon({
        image: ViaMarker,
        size: [20, 29],
      });

      list.forEach((item, index) => {
        let marker: any = "";
        if (index == 0) {
          marker = newMap.marker({ icon: startIcon, position: [item.lng, item.lat] });
        } else if (index == list.length - 1) {
          marker = newMap.marker({ icon: endIcon, position: [item.lng, item.lat] });
        } else {
          marker = newMap.marker({ icon: ViaIcon, position: [item.lng, item.lat] });
        }
        marker.setMap(newMap.map);
        marker.on("click", () => {
          locationInfo.value = item;
          InfoWin = newMap.infoWindow();
          InfoWin.open(newMap.map, marker.getPosition());
        });
      });
    }
  });
};
onMounted(() => {
  newMap = new MapCustom({ dom: "mapcontainer" });
  getLocateRecord();
});
</script>
<style scoped lang="less">
.monitoringMap {
  width: 100%;
  height: 400px;
  flex-shrink: 0;
}
</style>
