<template>
  <el-dialog
    v-model="visible"
    title="选择地址"
    width="80%"
    top="5vh"
    :close-on-click-modal="false"
    append-to-body
  >
    <iframe
      id="tencentMapPicker"
      :src="pickerUrl"
      width="100%"
      height="600px"
      frameborder="0"
      allow="geolocation"
      style="border: 0"
    ></iframe>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'

// ✅ 地图弹窗显隐
const visible = ref(false)

// ✅ 腾讯地图 locationPicker 地址，替换成你的 key & 应用名
const pickerUrl = `https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=2OZBZ-WUCE7-SLKXP-HJVOW-3P6RF-WVB7H&referer=VISITKEY`

// ✅ 定义暴露 open() 方法，父组件通过 ref 调用
const open = () => {
  visible.value = true
}
defineExpose({ open })

// ✅ 向父组件发回选中的地址和经纬度
const emit = defineEmits<{
  (e: 'update-location', payload: { lat: number; lng: number; address: string }): void
}>()

// ✅ 监听 locationPicker 的 postMessage
const handleMessage = (event: MessageEvent) => {
  const loc = event.data
  if (loc && loc.module === 'locationPicker') {
    const lat = loc.latlng.lat
    const lng = loc.latlng.lng
    const address = loc.poiaddress || loc.poiname || loc.address

    emit('update-location', { lat, lng, address })

    visible.value = false // 选完后自动关闭弹窗
  }
}

onMounted(() => {
  window.addEventListener('message', handleMessage)
})

onUnmounted(() => {
  window.removeEventListener('message', handleMessage)
})
</script>
