<template>
  <div class="map-wrapper">
    <div id="mapcontainer"></div>
  </div>
</template>

<script setup>
  import { shallowRef, computed, onMounted, ref, watch, nextTick } from 'vue'
  import AMapLoader from '@amap/amap-jsapi-loader'
  import { cloneWith } from 'lodash'
  window._AMapSecurityConfig = {
    securityJsCode: 'c18396f675a1469441ec75a190c70ee7',
  }
  const props = defineProps({
    modelValue: {
      type: Object,
      default() {
        return {}
      },
    },
  })
  const emit = defineEmits(['update:modelValue'])
  const map = shallowRef(null)
  // 地点
  const location = computed({
    get() {
      return props.modelValue
    },
    set(val) {
      emit('update:modelValue', val)
    },
  })
  watch(location, (val) => {
    if (val.longitude && val.latitude) {
      nextTick(() => {
        drawMarker(val.longitude, val.latitude)
      })
    }
  })
  let placeSearch, AMapObj, marker, geocoder
  function initMap() {
    AMapLoader.load({
      key: '98a4438e9a1e86bc285783f68656f7b5', // 申请好的Web端Key，首次调用 load 时必填
      version: '2.0',
    }).then((AMap) => {
      AMapObj = AMap
      map.value = new AMap.Map('mapcontainer', {
        center: [104.739928, 29.484215], //中心点坐标
        zoom: 5, //级别
      })
      // 添加点击事件
      map.value.on('click', onMapClick)
      if (location?.value?.longitude) {
        drawMarker(location?.value?.longitude, location?.value?.latitude)
      }
      AMap.plugin(
        ['AMap.ToolBar', 'AMap.Scale', 'AMap.Geolocation', 'AMap.PlaceSearch', 'AMap.Geocoder'],

        () => {
          geocoder = new AMap.Geocoder({
            city: '全国',
          })
        },
      )
    })
  }
  onMounted(() => {
    initMap()
  })

  // 点击地图
  function onMapClick(e) {
    const { lng, lat } = e.lnglat
    drawMarker(lng, lat)
    // 逆地理编码
    geocoder.getAddress([lng, lat], (status, result) => {
      if (status === 'complete' && result.info === 'OK') {
        const { addressComponent, formattedAddress } = result.regeocode
        let { city, province, district } = addressComponent
        if (!city) {
          // 直辖市
          city = province
        }
        location.value = {
          longitude: lng,
          latitude: lat,
          address: formattedAddress,
        }
      }
    })
  }
  // 绘制地点marker
  function drawMarker(longitude, latitude) {
    if (marker) {
      marker.setMap(null)
    }
    marker = new AMapObj.Marker({
      position: new AMapObj.LngLat(longitude, latitude),
      anchor: 'bottom-center',
    })
    map.value.add(marker)
  }
</script>

<style lang="less" scoped>
  .map-wrapper {
    position: relative;
    width: 100%;
    height: 400px;
    #mapcontainer {
      width: 100%;
      height: 100%;
    }
  }
</style>
