<template>
  <div ref="mapRef" class="map"> </div>
</template>
<script lang="ts" setup>
  import { unref, ref } from 'vue';
  import { useScript } from '/@/hooks/useScript';
  import { onMounted } from 'vue';

  const A_MAP_URL = 'https://webapi.amap.com/maps?v=2.0&key=e661b00bdf2c44cccf71ef6070ef41b8';
  const { toPromise } = useScript({ src: A_MAP_URL });
  const mapRef = ref<HTMLDivElement | null>(null);
  const initMap = async () => {
    await toPromise();
    console.log('mapRef', unref(mapRef));
    const AMap = (window as any).AMap;
    console.log('AMap', AMap);
    // const center = [120.262337, 30.178285]
    const map = new AMap.Map(unref(mapRef), {
      zoom: 15,
      resizeEnable: true,
      // center: center,
      // viewMode: '3D',
      // resizeEnable: true,
      // floorControl: true,
      // showIndoorMap: true
    });
    AMap.plugin(
      [
        'AMap.Scale',
        'AMap.Geocoder',
        'AMap.Toolbar',
        'AMap.AutoComplete',
        'AMap.PlaceSearch',
        'AMap.Geolocation',
      ],
      function () {
        const autoOptions = {
          city: '珠海',
          input: 'location',
        };
        const autocomplete = new AMap.Autocomplete(autoOptions);
        const placeSearch = new AMap.PlaceSearch({
          city: '珠海', // 默认城市，一定要有，不然没有放大效果
          map: map, // 地图，选中会有放大功能，绑定上面创建的地图即可
        });
        AMap.Event.addListener(autocomplete, 'select', function (e: any) {
          placeSearch.search(e.poi.name);
          console.log('location', e.poi.location); // 获取选中的的地址的经纬度
        });
        var geolocation = new AMap.Geolocation({
          // 是否使用高精度定位，默认：true
          enableHighAccuracy: true,
          // 设置定位超时时间，默认：无穷大
          timeout: 10000,
          // 定位按钮的停靠位置的偏移量，默认：Pixel(10, 20)
          buttonOffset: new AMap.Pixel(10, 20),
          //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
          zoomToAccuracy: true,
          //  定位按钮的排放位置,  RB表示右下
          buttonPosition: 'RB',
        });

        geolocation.getCurrentPosition();
        AMap.Event.addListener(geolocation, 'complete', onComplete);
        AMap.Event.addListener(geolocation, 'error', onError);

        function onComplete(data: any) {
          console.log('data', data);
          // data是具体的定位信息
        }

        function onError(data: any) {
          console.log('data', data);
          // 定位出错
        }
      },
    );
  };
  onMounted(() => {
    initMap();
  });
</script>
<style lang="scss" scoped>
  .map {
    width: 100%;
    height: 100%;
    padding-bottom: -80px;
  }
</style>
