<template>
  <div
    id="allmap"
    :style="{ width: width + 'px', height: height + 'px' }"
  ></div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { isEmpty, cloneDeep } from 'src/common/utils';
interface Props {
  id: string;
  width: number;
  height: number;
  bMapPoint?: Array<number>; // 中心点坐标
  mapLevel?: number; // 地图级别
  navigationControl?: boolean; // 平移缩放控件
  overviewMapControl?: boolean; // 缩略地图控件
  scrollWheelZoom?: boolean; // 开启鼠标滚轮缩放
  scaleControl?: boolean; // 比例尺控件
}
const props = withDefaults(defineProps<Props>(), {
  id: 'map',
  width: 100,
  height: 100,
  bMapPoint: () => [],
  mapLevel: 12,
  navigationControl: false,
  overviewMapControl: false,
  scrollWheelZoom: false,
  scaleControl: false,
});

const bMapApi = ref(null);

const state = reactive({
  bMapPoint: cloneDeep(props.bMapPoint),
});

onMounted(async () => {
  let map = new (window as any).BMap.Map(props.id); // 创建Map实例
  bMapApi.value = map;

  let p = new Promise<void>(function (resolve) {
    if (isEmpty(props.bMapPoint)) {
      let myCity = new (window as any).BMap.LocalCity();
      myCity.get((res: any) => {
        state.bMapPoint.push(res.center.lng);
        state.bMapPoint.push(res.center.lat);
        resolve();
      });
    } else {
      resolve();
    }
  });
  p.then(() => {
    map.centerAndZoom(
      new (window as any).BMap.Point(state.bMapPoint[0], state.bMapPoint[1]),
      props.mapLevel
    );
  });
  if (props.navigationControl) {
    map.addControl(new (window as any).BMap.NavigationControl());
  }
  if (props.overviewMapControl) {
    map.addControl(new (window as any).BMap.OverviewMapControl());
  }
  if (props.scaleControl) {
    map.addControl(new (window as any).BMap.ScaleControl());
  }
  if (props.scrollWheelZoom) {
    map.enableScrollWheelZoom(true);
  }
  // 添加地图类型控件
  //   map.addControl(
  //     new window.BMap.MapTypeControl({
  //       mapTypes: [window.BMAP_NORMAL_MAP, window.BMAP_HYBRID_MAP],
  //     })
  //   );
  // map.setCurrentCity('成都'); // 设置地图显示的城市 仅当设置城市信息时，MapTypeControl的切换功能才能可用
});
defineExpose({
  bMapApi,
});
</script>

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