<template>
    <view>
        <map id="wxMapId" :longitude="mapData.location.lng" :latitude="mapData.location.lat" :markers="markers"
            style="width: 100%; height: 50vh;"></map>
    </view>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import config from '@/config'
const mapKey = config.mapKey;
const QQMapWX = require('/static/sdk/qqmap-wx-jssdk.min.js')

// 接收外部传入的地址
const props = defineProps({
    address: {
        type: String,
        required: true,
        default: ''
    }
});

// 地图上下文
const mapCtx = ref(null);
const markers = ref([]);

const mapData = ref({
    location: {
        lat: 0,
        lng: 0
    }
})
let qqmapsdk = null;

onMounted(() => {
    console.log('mapKey-------------->',mapKey,QQMapWX);
    
    mapCtx.value = wx.createMapContext('wxMapId');

    qqmapsdk = new QQMapWX({
        key: mapKey
    });

    console.log('props',props.address);
    
    // 如果地址已经传入，立即进行地址转经纬度
    if (props.address) {
        geocodeAddress(props.address);
    }
});

// 监听地址变化
watch(() => props.address, (newAddress) => {
    if (newAddress) {
        geocodeAddress(newAddress);
    }
});

// 地址转经纬度
const geocodeAddress = (address) => {
    console.log('地址', address);

    qqmapsdk.geocoder({
        address: props.address,
        success: function (res) {
            console.log('初始化地图上下文', res);
            mapData.value = res.result;
            markers.value = [{ 
                latitude: res.result.location.lat, 
                longitude: res.result.location.lng,
                id: 1,
                width: 20,
                height: 20,
                callout: {
                    content: props.address,
                    color: '#000000',
                    fontSize: 12,
                    borderRadius: 4,
                    padding: 5,
                    bgColor: '#ffffff',
                    display: 'ALWAYS'
                }
            }];
        },
        fail: function (error) {
            console.error(error);
        },
    })

};

</script>

<style lang="scss" scoped>
map {
    width: 100%;
    height: 40vh;
    /* 确保地图占满整个视图高度 */
}
</style>