<template>
  <view class="map-warp">
    <!--#ifdef H5-->
    <web-view
      :src="`https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=${key}&referer=myapp`"
      @message="onMessage"
    />
    <!--#endif-->

    <!--#ifdef APP-PLUS-->
    <web-view
      :src="webSrc"
      @message="onMessage"
    />
    <!--#endif-->
  </view>
</template>

<script setup>
const emit = defineEmits(['onGetLocation'])
const key = import.meta.env.VITE_APP_MAP_KEY
const webSrc = ref(`/hybrid/html/map.html?key=${key}&data=`)
const coord = ref('')

onBeforeMount(() => {
  // #ifdef H5
  if (window.isListen) {
    // 防止多次注册addEventListener事件
    return
  }
  window.addEventListener('message', function (event) {
    const loc = event.data
    if (loc && loc.module === 'locationPicker') {
      uni.$emit('onGetLocation', loc)
    }
    window.isListen = true
    window.removeEventListener('message', function () {}, true)
  }, false)
  // #endif

  // #ifdef APP-PLUS
  uni.getLocation({
    type: 'gcj02',
    altitude: true,
    success: res => {
      // 在指定位置附近进行位置选择,coord用英文逗号分隔，纬度在前，经度在后
      coord.value = [res.latitude, res.longitude].join(',')
      webSrc.value = webSrc.value + coord.value
    }
  })
  // #endif
})

const onMessage = (res) => {
  emit('onGetLocation', res.detail.data[0])
}

</script>
