<script lang="ts" setup>
import L from 'leaflet';
import { Ref, inject, onMounted,onUnmounted, ref, watch } from 'vue';
import { mdiMapMarker } from '@quasar/extras/mdi-v7'

const props = defineProps({
    latlng: Array<Number>,
    title: String,
    opacity: Number
})

const map = inject<Ref<L.Map>>('map');
const mark = ref<L.Marker>()
const markInfo = ref()

watch(props, ({ title = '', latlng = [0, 0], opacity = 1 }) => {
    if (!mark.value) return
    mark.value.setLatLng(L.latLng(+latlng[0], +latlng[1]))
    mark.value.options.title = title
    mark.value.setOpacity(opacity)
    mark.value.getTooltip()?.setOpacity(opacity)
    mark.value.setTooltipContent(title)
})

onMounted(() => {
    const { latlng = [0, 0], title, opacity = 1 } = props;
    mark.value = L.marker(L.latLng(+latlng[0], +latlng[1]), {
        title, icon: L.divIcon({
            html: markInfo.value,
            className: 'markInfo',
            iconAnchor: L.point(12, 24)
        })
    }).bindTooltip(title || '', {
        permanent: !!title,
        offset: [15, -5],// 偏移
        direction: "right",// 放置位置
        opacity
    }).openTooltip()

    mark.value.setOpacity(opacity)
    map?.value && mark.value.addTo(map.value)
})


onUnmounted(()=>{
    mark.value?.remove()
})

function remove(call: () => void) {
    mark.value?.remove()
    call()
}

defineExpose({ mark, remove })
</script>
<template>
    <div ref="markInfo">
        <slot>
            <q-icon :name="mdiMapMarker" size="md"></q-icon>
        </slot>
    </div>
</template>
<style lang="scss">
.markInfo {
    background-color: transparent;
    color: #ae1e1e;
}
</style>