<template>
    <div class="home_card_screen">
        <div class="map_card" v-loading="mapLoading">
            <div id="container"></div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import AMapLoader from "@amap/amap-jsapi-loader";
import hospitalIcon from '/src/assets/images/hospital.png';
// 接收父组件传入的参数
const props = defineProps({
    markerData: {
        type: Array,
        default: () => []
    },
    mapLoading: {
        type: Boolean,
        default: false
    }
});
// 定义点击事件处理函数
const emit = defineEmits(['titleClick']);
let map = null;
let infoWindow = null;
let markers = []; // 存储所有标记点的数组
let mapInstance = null;
let isMapLoaded = false; // 地图是否已加载完成
onMounted(() => {
    // keyUpSearch()
});
function keyUpSearch() {
    window._AMapSecurityConfig = {
        securityJsCode: "a4a40f5348abeff7774181b9cccb4977",
    };
    AMapLoader.load({
        key: "8095211c3bb0ec04d8bbbcd556fc7d0c", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.Scale", "AMap.Marker", "AMap.InfoWindow", "AMap.Icon"],
    }).then((AMap) => {
        mapInstance = AMap;
        map = new AMap.Map("container", {
            viewMode: "3D", // 是否为3D地图模式
            zoom: 11, // 初始化地图级别
            center: [116.397428, 39.90923], // 初始化地图中心点位置
        });
        var styleName = "amap://styles/blue";
        map.setMapStyle(styleName);

        map.on('complete', () => {
            isMapLoaded = true;
            // console.log('地图加载完成');
            // 创建信息窗口
            infoWindow = new AMap.InfoWindow({
                content: "",
                offset: new AMap.Pixel(0, -30),
            });
            // 添加标记点
            if (props.markerData && props.markerData.length > 0) {
                nextTick(() => {
                    addMarkers(AMap);
                });
            }
        });
    }).catch((e) => {
        console.log(e);
    });
}
// 监听 markerData 变化
watch(
    () => props.markerData,
    (newData, oldData) => {
        console.log('markerData 发生变化:', newData);
        // 确保地图已加载且有数据
        if (isMapLoaded && mapInstance && newData && newData.length > 0) {
            nextTick(() => {
                addMarkers(mapInstance);
            });
        } else if (newData && newData.length === 0) {
            clearMarkers();
        }
    },
    {
        deep: true, // 深度监听
        immediate: true // 立即执行
    }
);
// 添加标记点并绑定点击事件
function addMarkers(AMap) {
    // 清除之前的标记点
    clearMarkers();
    if (!props.markerData || props.markerData.length === 0) {
        console.log('没有标记点数据');
        return;
    }
    // 遍历数据数组，为每个数据项创建标记点
    props.markerData.forEach((item, index) => {
        if (item.longitude && item.latitude) {
            createMarker(AMap, item, index);
        }
    });
    // console.log(`共添加了 ${markers.length} 个标记点`);
    map.setFitView(null, false, [260, 150, 60, 150]);
}
// 创建单个标记点
function createMarker(AMap, item, index) {
    const marker = new AMap.Marker({
        position: [item.longitude, item.latitude],
        title: item.deptName,
        map: map,
        extData: item
    });

    // 创建更精美的自定义内容
    const markerContent = document.createElement('div');
    markerContent.style.cssText = `
        position: relative;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        user-select: none;
    `;
    // 创建图标容器
    const iconContainer = document.createElement('div');
    iconContainer.style.cssText = `
        position: relative;
        width: 40px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        border: 2px solid white;
        box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
    `;

    // 创建图片
    const img = document.createElement('img');
    img.src = hospitalIcon;
    // img.src = '/src/assets/images/hospital.png';
    img.style.cssText = `
        width: 22px;
        height: 22px;
        object-fit: contain;
    `;

    iconContainer.appendChild(img);

    // 创建文字标签
    const textLabel = document.createElement('div');
    textLabel.textContent = item.deptName;
    textLabel.style.cssText = `
        margin-top: 4px;
        font-size: 14px;
        font-weight: 600;
        color: #333;
        background: rgba(255, 255, 255, 0.95);
        padding: 2px 6px;
        border-radius: 12px;
        border: 1px solid #ddd;
        white-space: nowrap;
        max-width: 100px;
        overflow: hidden;
        text-overflow: ellipsis;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    `;

    markerContent.appendChild(iconContainer);
    markerContent.appendChild(textLabel);

    marker.setContent(markerContent);
    marker.setOffset(new AMap.Pixel(-20, -50));
    // 绑定点击事件 - 动态获取信息
    marker.on("click", async () => {
        // 设置全局点击处理函数
        emit('titleClick',item);
    });
    markers.push(marker);
}
// 清除所有标记点
function clearMarkers() {
    if (markers.length > 0) {
        markers.forEach(marker => {
            marker.setMap(null);
        });
        markers = [];
    }
}

// 更新标记点数据（外部可以调用此方法更新标记点）
function updateMarkers(newData) {
    markerData.value = newData;
    if (map) {
        AMapLoader.load({
            key: "757901c9436e9d5b9f8cfbb5ab0e91c7",
            version: "2.0"
        }).then((AMap) => {
            addMarkers(AMap);
        });
    }
}
// 暴露方法
defineExpose({
    keyUpSearch
})
onUnmounted(() => {
    clearMarkers();
    map?.destroy();
});
</script>

<style lang="scss">
.home_card_screen {
    position: relative;
    width: 100%;
    height: 100%;
}

.map_card {
    width: 100%;
    height: 100%;
    flex: 1;
}

#container {
    position: relative;
    width: 100%;
    height: 100%;
}

// 疾控中心风格信息窗口样式
.epidemic-info-window {
    font-family: 'Microsoft YaHei', Arial, sans-serif;
    border: 1px solid #2196F3;
    border-radius: 8px;
    background: linear-gradient(135deg, #ffffff, #f8f9fa);
    box-shadow: 0 4px 12px rgba(33, 150, 243, 0.2);
    overflow: hidden;
    color: #333;
    max-width: 320px;
    min-width: 280px;
}

.info-header {
    padding: 12px 15px;
    background: linear-gradient(135deg, #2196F3, #1976D2);
    color: white;
    border-bottom: 1px solid #1565C0;
}

.info-header.error {
    background: linear-gradient(135deg, #f44336, #d32f2f);
}

.title-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 8px;
}

.title-icon {
    font-size: 16px;
}

.title-text {
    font-size: 15px;
    font-weight: bold;
    flex: 1;
}

.update-time {
    font-size: 11px;
    opacity: 0.9;
}

.info-content {
    padding: 15px 15px 0px 15px;
    background: white;
}

.section {
    margin-bottom: 15px;
}

.section-title {
    display: flex;
    align-items: center;
    gap: 6px;
    margin-bottom: 12px;
    padding-bottom: 6px;
    border-bottom: 1px solid #e0e0e0;
}

.section-icon {
    font-size: 14px;
}

.section-text {
    font-size: 14px;
    font-weight: bold;
    color: #1976D2;
}

.data-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 10px;
}

.data-item {
    padding: 8px;
    background: #f5f5f5;
    border: 1px solid #e0e0e0;
    border-radius: 6px;
    transition: all 0.2s ease;
    display: flex;
    align-items: center;
}

.data-item:hover {
    background: #e3f2fd;
    border-color: #2196F3;
    transform: translateY(-1px);
}

.data-label {
    font-size: 12px;
    color: #666;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.data-value {
    margin-left: 6px;
    font-size: 20px;
    font-weight: bold;
    color: #333;
}

.data-value.value-blue {
    color: #2196F3;
}

.data-value.value-green {
    color: #4CAF50;
}

.data-value.value-orange {
    color: #FF9800;
}

.data-value.value-red {
    color: #f44336;
}

.info-footer {
    padding: 10px 15px;
    background: #f8f9fa;
    border-top: 1px solid #e0e0e0;
    text-align: center;
}

.footer-text {
    font-size: 11px;
    color: #666;
}

// 加载动画
.loading-dots span {
    animation: blink 1.4s infinite;
    font-size: 20px;
    color: #2196F3;
}

.loading-dots span:nth-child(2) {
    animation-delay: 0.2s;
}

.loading-dots span:nth-child(3) {
    animation-delay: 0.4s;
}

@keyframes blink {

    0%,
    100% {
        opacity: 0.2;
    }

    50% {
        opacity: 1;
    }
}

// 错误信息
.error-message {
    text-align: center;
    padding: 15px;
}

.error-message div:first-child {
    color: #f44336;
    font-weight: bold;
    margin-bottom: 8px;
}

.error-detail {
    font-size: 12px;
    color: #666;
}

// 响应式设计
@media (max-width: 320px) {
    .epidemic-info-window {
        min-width: 260px;
        max-width: 280px;
    }

    .data-grid {
        gap: 8px;
    }

    .data-item {
        padding: 6px;
    }

    .data-label {
        font-size: 11px;
    }

    .data-value {
        font-size: 14px;
    }
}
</style>