<template>
    <!-- 拾取经纬度对话框 -->
    <el-dialog title="拾取经纬度" v-model="pickLatOpen" width="1250px" class="my_dialog" align-center
        :destroy-on-close="true" :close-on-click-modal="false" :before-close="handleColosePickDialog">
        <el-select class="filterSelect" v-model="localeKeyWord" filterable remote reserve-keyword
            :remote-method="getLocaleListList" :loading="selectLoading" @change="currentSelect" placeholder="请输入地点"
            remote-show-suffix clearable style="margin-bottom: 20px; width: 70%">
            <el-option v-for="item in localeList" :key="item.id" :label="item.name" :value="item" class="one-text">
                <span style="float: left">{{ item.name }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{
                    item.address
                    }}</span>
            </el-option>
        </el-select>
        <div v-if="pickLatLableValue" class="pickLatLabel">拾取的经纬度：{{ pickLatLableValue.lat }}, {{  pickLatLableValue.lng }}</div>
        <div id="mapContainer" class="pickMapContainer"></div>
        <!-- <template #footer>
                <div class="dialog-footer">
                    <el-button class="my-cancel-btn" @click="pickLatOpen = false">取 消</el-button>
                    <el-button class="my-confirm-btn" type="primary" @click="handleSubmitExportPPT">确 定</el-button>
                </div>
            </template> -->
    </el-dialog>
</template>
<script setup>
import { onMounted, defineEmits, ref } from 'vue'
import AMapLoader from "@amap/amap-jsapi-loader";  // 引入地图服务 


const { proxy } = getCurrentInstance()
const emit = defineEmits(['closePickLat']);
const { apiKey, secretKey } = window._CONFIG
// 拾取的经纬度
const pickLatLableValue = ref(null)
const pickLatOpen = ref(false)
// 拾取经纬度关键字
const selectLoading = ref(false)
const localeKeyWord = ref('')
const localeList = ref([])

// map实例
const mapInstance = ref(null)
const marker = ref(null)
const placeSearch = ref(null)

// 调用API获取地点
const getLocaleListList = (searchValue) => {
    selectLoading.value = true
    if (searchValue !== "") {
        placeSearch.value.search(searchValue, function (status, result) {
            // 查询成功时，result即对应匹配的POI信息 
            if (result.poiList.pois?.length) {
                localeList.value = result.poiList?.pois
            }
            selectLoading.value = false
        });
    }
}


// 地点选择
const currentSelect = (val) => { 
    localeKeyWord.value = val.name 
    pickLatLableValue.value = { lng: val.location.lng, lat: val.location.lat }
    addmark(val)
}
// 添加标记
const addmark = (val) => {
    if (marker.value) mapInstance.value.remove(marker.value);
    marker.value = new AMap.Marker({
        position: val.location,
        title: val.name
    });
    // 将点添加到地图 
    mapInstance.value.add(marker.value);
    mapInstance.value.setFitView();
}
// 初始化地图 
const loadMap = () => {
    pickLatOpen.value = true
    return new Promise((resolve, reject) => {
        // 设置安全密钥
        window._AMapSecurityConfig = {
            securityJsCode: secretKey
        };

        AMapLoader.load({
            key: apiKey,
            plugins: ["AMap.PlaceSearch"],
            AMapUI: {
                plugins: []
            }
        }).then(AMap => {
            mapInstance.value = new AMap.Map("mapContainer", {
                resizeEnable: true,
                zoom: 14,
                center: [116.397428, 39.90923],
                viewMode: "2D",
                buildingAnimation: true,
                expandZoomRange: true,
            });

            // 先添加基本控件 
            mapInstance.value.setZoom(14);

            placeSearch.value = new AMap.PlaceSearch({
                // city 指定搜索所在城市，支持传入格式有：城市名、citycode和adcode
                city: '全国'
            })

            mapInstance.value.on('click', (e) => {
                const clickPoint = { location: e.lnglat }
                pickLatLableValue.value = { lng: clickPoint.location.lng, lat: clickPoint.location.lat }
                addmark(clickPoint)
            })
            // 地图加载完成后隐藏Logo
            setTimeout(() => {
                hideAmapLogo();
            }, 1000);

            // 监听地图渲染完成事件
            mapInstance.value.on('render', hideAmapLogo);
            resolve();

        }).catch(e => {
            console.log(e, "高德地图加载失败");
            reject(e);
        });
    });
}
// 隐藏Logo的函数
const hideAmapLogo = () => {
    const logos = document.querySelectorAll('.amap-logo, .amap-copyright');
    logos.forEach(logo => {
        logo.style.display = 'none';
        logo.style.visibility = 'hidden';
        logo.style.opacity = '0';
    });
}

const handleColosePickDialog = () => {
    pickLatOpen.value = false
    emit('closePickLat', pickLatLableValue.value)
}

// 暴露方法\属性给父组件
defineExpose({
    loadMap
});
</script>

<style lang='scss'>
.pickMapContainer {
    width: 100%;
    height: calc(100vh - 316px);
    background: #3f8bff;
}

.pickLatLabel {
    width: 300px;
    position: absolute;
    right: 30px;
    top: 98px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    font-size: 16px;
    color: #87898E;
}
</style>