<template>
  <div :id="mapId" :style="`position: ${position}; top: 0px; left: 0px; width: ${width}; height: ${height}; z-index: ${zIndex} `"></div>
</template>

<script setup lang="ts">
  import { defineProps, ref, onMounted, onUnmounted, defineEmits, computed } from 'vue';
  import { v4 as uuidv4 } from 'uuid';
  import mapboxgl, { Map } from 'mapbox-gl';
  import { MapboxConfig, MapboxDefaultStyle } from '@/components/MapboxMaps/src/config.ts';

  const props = defineProps(['width', 'height', 'zIndex', 'position', 'center']);
  const emits = defineEmits(['getMap']);
  const { center } = props;
  const width = computed(() => {
    return props.width;
  });
  const height = computed(() => {
    return props.height;
  });
  const zIndex = computed(() => {
    return props.zIndex;
  });
  const position = computed(() => {
    return props.position;
  });

  const mapId = `modal-map-${uuidv4()}`;
  let map: Map;
  onMounted(() => {
    mapboxgl.accessToken = MapboxConfig.ACCESS_TOKEN;
    map = initMap();
    map.on('load', () => {
      emits('getMap', map);
    });
  });
  const initMap = () => {
    return new mapboxgl.Map({
      container: mapId,
      language: 'zh-cmn',
      projection: 'equirectangular', // wgs84参考系
      style: MapboxDefaultStyle,
      maxZoom: 22,
      minZoom: 6,
      zoom: 15,
      // ...props.mapOptions,
      center: props.center
        ? getCenter(JSON.parse(`[${props.center[0].fourpoint}]`))
        : [117.984425, 35.270654],
    });
  };

  // 移动位置
  function getCenter(fourpoint) {
    let x = 0;
    let y = 0;
    let length = fourpoint.length;
    for (let i = 0; i < fourpoint.length; i++) {
      x = x + fourpoint[i][0];
      y = y + fourpoint[i][1];
    }
    x = x / length;
    y = y / length;
    return [x, y];
  }

  onUnmounted(() => {
    map && map.remove();
  });
</script>

<style lang="scss" scoped></style>
