<template>
  <el-dialog
    :visible.sync="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>
export default {
  data() {
    return {
      visible: false, // 地图弹窗显隐
      pickerUrl: `https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=P56BZ-BV2CB-FAAUP-JMWTD-6TAHT-CXFGU&referer=KAOSHI`, // 腾讯地图 locationPicker 地址
      meta: [
        {
          httpEquiv: 'Permissions-Policy',
          content: 'geolocation=(self)', // 设置权限策略
        },
      ],
    };
  },
  methods: {
    // 打开弹窗
    open() {
      this.visible = true;
    },
    // 监听 locationPicker 的 postMessage
    handleMessage(event) {
      console.log("监听")
      console.log(event.data)
      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;

        // 向父组件发回选中的地址和经纬度
        this.$emit('update-location', { lat, lng, address });

        this.visible = false; // 选完后自动关闭弹窗
      }
    },
  },
  mounted() {
    // 监听 postMessage
    window.addEventListener('message', this.handleMessage);
  },
  beforeDestroy() {
    // 卸载监听器
    window.removeEventListener('message', this.handleMessage);
  },
};
</script>
