<template>
  <div class="map-container">
    <div id="mapContainerComponent" class="map-box"></div>
    <div class="map-control">
      <img
        v-for="(item, index) in nextMapControl"
        :key="index"
        :src="item.icon"
        :title="item.title"
        @click="handlerMapControlClick(item.handler)"
      />
      <img v-show="nextMapControl.length > 0" @click="handlerUnDraw" src="/del.png" title="清除" />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { onMounted, onUnmounted, defineProps, reactive } from 'vue';
  import mapboxgl, { Map } from 'mapbox-gl';
  import U from 'mapbox-gl-utils';
  import 'mapbox-gl/dist/mapbox-gl.css';
  import './src/index.less';
  import { MapboxConfig, MapboxDefaultStyle, MapControlConfig } from './src/config';
  import { MP } from './src/MP';
  import { DrawingType } from '@/enums/mapEnum';

  // map参数类型
  interface MapboxOptionsInterface {
    mapOptions: mapboxgl.MapboxOptions;
    control: DrawingType[];
  }
  const props = defineProps<MapboxOptionsInterface>();

  let nextMapControl: Array<any> = reactive([]);
  nextMapControl = props.control
    ? props.control.map((item) => {
        console.log('item::: ', item);
        return MapControlConfig[item];
      })
    : [];

  // 定义地图容器
  let map: Map;
  let mp: any = null;
  // 定义地图回调emit
  // 地图加载完成回调
  const emit = defineEmits(['mapOnLoad', 'mapDraw']);
  onMounted(() => {
    mapboxgl.accessToken = MapboxConfig.ACCESS_TOKEN;
    map = initMap();
    map.on('load', () => {
      //挂载mapbox-gl-utils
      U.init(map);
      mp = new MP(map);
      emit('mapOnLoad', map);
    });
  });
  // 销毁地图
  // 移除地图实例
  onUnmounted(() => {
    map ? map.remove() : null;
  });
  // 初始化地图
  // 返回地图实例
  const initMap = () => {
    return new mapboxgl.Map({
      container: 'mapContainerComponent',
      language: 'zh-cmn',
      projection: 'equirectangular', // wgs84参考系
      style: MapboxDefaultStyle,
      maxZoom: 22,
      minZoom: 6,
      ...props.mapOptions,
    });
  };

  const handlerMapControlClick = (handler: string) => {
    handler === 'handlerDrawPoint' && handlerDrawPoint();
    handler === 'handlerDrawLineString' && handlerDrawLineString();
    handler === 'handlerDrawPolygon' && handlerDrawPolygon();
  };
  //绘制点
  const handlerDrawPoint = () => {
    mp.draw('Point');
    mp.on('Point', function (e) {
      emit('mapDraw', 'Point', e);
    });
  };
  //绘制线
  const handlerDrawLineString = () => {
    mp.draw('LineString');
    mp.on('LineString', function (e) {
      emit('mapDraw', 'LineString', e);
    });
  };
  //绘制面
  const handlerDrawPolygon = () => {
    mp.draw('Polygon');
    mp.on('Polygon', function (e) {
      emit('mapDraw', 'Polygon', e);
    });
  };
  //删除标记
  const handlerUnDraw = () => {
    mp.deleteDraw();
    emit('mapDraw', 'cancel');
  };
</script>
