<!-- src/components/MapContainer.vue -->
<template>
  <div id="map-container" class="w-full h-full"></div>
</template>

<script setup>
import { onMounted, defineProps } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'

const props = defineProps({
  lng: {
    type: Number,
    required: true
  },
  lat: {
    type: Number,
    required: true
  },
  zoom: {
    type: Number,
    default: 16
  },
  title: {
    type: String,
    default: '公司位置'
  },
  address: {
    type: String,
    default: ''
  }
})

onMounted(() => {
  // 安全密钥配置
  window._AMapSecurityConfig = {
    securityJsCode: "test123"
  }

  AMapLoader.load({
    key: "testkey",
    version: "2.0",
    plugins: ["AMap.InfoWindow"]
  }).then((AMap) => {
    // 初始化地图
    const map = new AMap.Map('map-container', {
      zoom: props.zoom,
      center: [props.lng, props.lat],
      viewMode: '3D'
    })

    // 添加标记
    const marker = new AMap.Marker({
      position: [props.lng, props.lat],
      title: props.title
    })
    map.add(marker)

    // 添加信息窗口
    const infoWindow = new AMap.InfoWindow({
      content: `<div class="p-2">
        <h4 class="font-bold">${props.title}</h4>
        <p class="text-sm">${props.address}</p>
      </div>`,
      offset: new AMap.Pixel(0, -30)
    })

    // 默认打开信息窗口
    infoWindow.open(map, [props.lng, props.lat])

    // 点击标记打开信息窗口
    marker.on('click', () => {
      infoWindow.open(map, [props.lng, props.lat])
    })
  }).catch(e => {
    console.error('地图加载失败', e)
  })
})
</script>

<style scoped>
#map-container {
  min-height: 300px;
}
</style>
