<template>
  <div>
    <div :id="mapId" class="container"></div>
    <el-dialog v-model="mediaModal" :title="modalTitle" destroy-on-close>
      <el-image
        v-if="modalType == 1"
        style="height: 60vh; display: flex"
        fit="contain"
        :src="currentUrl"
        :preview-src-list="modalPreview"
      ></el-image>
      <video
        v-else
        autoplay
        controls
        style="width: 100%; height: 60vh"
        :src="currentUrl"
      ></video>
    </el-dialog>
  </div>
</template>
<script setup>
import { onMounted, onUnmounted, ref } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import router from "../router";
import { useRoute } from "vue-router";
const route = useRoute();
const props = defineProps({
  longitude: {
    type: Number,
    default: 120.498409,
  },
  latitude: {
    type: Number,
    default: 32.039665,
  },
  ships: {
    type: Array,
    default: [],
  },
  medias: {
    type: Array,
    default: [],
  },
  coordinates: {
    type: Array,
    default: [],
  },
  showLabel: {
    type: Boolean,
    default: false,
  },
  handleAble: {
    type: Boolean,
    default: false,
  },
  loadPorts: {
    type: Array,
    default: [],
  },
  dischargePorts: {
    type: Array,
    default: [],
  },
  mapId: {
    type: String,
    default: "container",
  },
  zoomEnable: {
    type: Boolean,
    default: true,
  },
  dragEnable: {
    type: Boolean,
    default: true,
  },
  ToolBar: {
    type: Boolean,
    default: true,
  },
  HawkEye: {
    type: Boolean,
    default: true,
  },
});
const mapId = ref(props.mapId);
const map = ref({});
function initMap() {
  AMapLoader.load({
    key: "0b84075e96d01623f704867a601139bb", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
  })
    .then((AMap) => {
      map.value = new AMap.Map(props.mapId, {
        zoom: 12, // 初始化地图级别
        center: [props.longitude, props.latitude], // 初始化地图中心点位置
        mapStyle: "amap://styles/f48d96805f5fa7f5aada657c5ee37017",
        zoomEnable: props.zoomEnable,
        dragEnable: props.dragEnable,
      });
      if (props.ToolBar || props.HawkEye) {
        map.value.plugin(["AMap.ToolBar", "AMap.HawkEye"], function () {
          if (props.ToolBar) {
            let ToolBar = new AMap.ToolBar({
              position: {
                top: "40px",
                right: "40px",
              },
            });
            map.value.addControl(ToolBar);
          }

          if (props.HawkEye) {
            let HawkEye = new AMap.HawkEye({
              opened: false,
            });

            map.value.addControl(HawkEye);
          }
        });
      }
    })
    .catch((e) => {
      console.log(e);
    });
}

function generateMarker({
  id = 0,
  longitude = 120.498409,
  latitude = 32.039665,
  offsetX = -15,
  offsetY = -25,
  zIndex = 1,
  label = "",
  handleType = "",
  viewUrl = "",
  content = `<div>
          <img src='https://hhd-pat-1255802371.cos.ap-shanghai.myqcloud.com/frontend/ship-red-icon.png' style='display:block;width:20px;height:20px;margin:6px auto'/
        </div>`,
}) {
  let marker = new AMap.Marker({
    content,
    zIndex,
    position: new AMap.LngLat(longitude, latitude),
    offset: new AMap.Pixel(offsetX, offsetY),
  });
  if (label) {
    marker.setLabel({
      direction: "top",
      offset: new AMap.Pixel(0, 0), //设置文本标注偏移量
      content: label, //设置文本标注内容
      style: "",
    });
  }
  if (handleType === "route") {
    marker.on("click", () => {
      goTo("/voyage/voyageDetail", {
        id,
      });
    });
  }

  if (handleType === "media") {
    marker.on("click", () => {
      openMediaModal(viewUrl, 1, "航次图片");
    });
  }

  return marker;
}
//ship-orange-icon
function generateMarkers(points, type) {
  let markers = [];
  for (let i of points) {
    let config = {
      longitude: i.longitude,
      latitude: i.latitude,
    };
    switch (type) {
      case "ships": {
        config.label = i.shipName;
        config.id = i.voyageId;
        config.handleType = "route";
        if (route.path === "/index") {
          config.content = `<div>
          <img src='https://frontend-1255802371.cos.ap-shanghai.myqcloud.com/ship-orange-icon.png' style='display:block;width:30px;height:30px;margin:6px auto'/
        </div>`;
        }
        break;
      }
      case "loadPorts": {
        config.content = `<div>
          <img src='https://hhd-pat-1255802371.cos.ap-shanghai.myqcloud.com/frontend/port-green.png' style='display:block;width:30px;height:30px;margin:6px auto'/
        </div>`;
        config.label = "装货港";
        break;
      }
      case "dischargePorts": {
        config.content = `<div>
          <img src='https://hhd-pat-1255802371.cos.ap-shanghai.myqcloud.com/frontend/port-red.png' style='display:block;width:30px;height:30px;margin:6px auto'/
        </div>`;
        config.label = "卸货港";
        break;
      }
      case "medias": {
        config.content = `<div style='width:160px'>
        ${
          i.audit == 1
            ? `<img id='img${i.id}' style='width:160px;height:160px;object-fit:contain;' src='${i.viewUrl}'/>`
            : ``
        }
        <img src='https://hhd-pat-1255802371.cos.ap-shanghai.myqcloud.com/frontend/ship-red-icon.png' style='display:block;width:20px;height:20px;margin:6px auto'/
      </div>`;
        config.offsetX = -80;
        config.offsetY = i.audit == 1 ? -185 : -20;
        config.zIndex = 15;
        config.handleType = "media";
        config.viewUrl = i.viewUrl;
        break;
      }
      case "coordinates": {
        config.content = `<div>
          <img src='https://frontend-1255802371.cos.ap-shanghai.myqcloud.com/green-circle.png' style='display:block;width:20px;height:20px;margin:6px auto'/
        </div>`;
        config.offsetX = -10;
        config.offsetY = -17;
        break;
      }
    }
    markers.push(generateMarker(config));
  }
  return markers;
}

function drawMarkers() {
  let markers = [
    ...generateMarkers(props.ships, "ships"),
    ...generateMarkers(props.loadPorts, "loadPorts"),
    ...generateMarkers(props.dischargePorts, "dischargePorts"),
    ...generateMarkers(props.medias, "medias"),
    ...generateMarkers(props.coordinates, "coordinates"),
  ];

  let overlayGroups = new AMap.OverlayGroup(markers);
  map.value.add(overlayGroups);
  setFitView(markers);
}

function setFitView(markers = [], zoom = 9) {
  map.value.setFitView(markers, true, [150, 50, 100, 100], zoom);
}

function clearMap() {
  map.value.clearMap();
}

function goTo(path = "/voyage/voyageDetail", query = {}) {
  router.push({
    path,
    query,
  });
}

let currentUrl = ref("");
let mediaModal = ref(false);
let modalType = ref(1);
let modalTitle = ref("");
let modalPreview = ref([]);
function openMediaModal(url, type, title, item = {}) {
  modalPreview.value = [url];
  modalTitle.value = title;
  modalType.value = type;
  currentUrl.value = url;
  mediaModal.value = true;
}

onMounted(() => {
  initMap();
});

defineExpose({
  clearMap,
  drawMarkers,
  initMap,
});

onUnmounted(() => {
  map.value.destroy();
});
</script>

<style scoped>
#container {
  width: 100%;
}

.container {
  width: 100%;
  height: 100%;
}
</style>
