<script setup>
import {ref, onMounted} from 'vue'

window.GD_KEYS = [
  '348d477ba83826e46b32d3ff10fffe82',
  'ed2ea36f8564541569c370254845d93d',
  'c1da03827f956a215311c0f5229bddc3',
]

const map = ref(null)

const center = [118.762616, 32.068811]

/* 检测单个 key 能否真正初始化地图 */
const tryKey = (key) =>
  new Promise((AMapResolve, AMapReject) => {
    // 如果之前已经加载过，先清掉
    if (window.AMap) delete window.AMap
    const script = document.createElement('script')
    script.src = `https://webapi.amap.com/maps?v=2.0&key=${key}`
    script.async = true
    script.onload = () => {
      try {
        const mapInstance = new window.AMap.Map('map', {
          viewMode: '2D',
          zoom: 19,
          center: center,
          zoomEnable: false,
          dragEnable: false,
        })
        AMapResolve({AMap: window.AMap, mapInstance, key})
      } catch (e) {
        AMapReject(e)
      }
    }
    script.onerror = AMapReject
    document.head.appendChild(script)
  })

/* 顺序尝试，直到成功或全部失败 */
const initMap = async () => {
  for (const key of window.GD_KEYS) {
    try {
      const {mapInstance} = await tryKey(key)
      map.value = mapInstance
      console.log('✅ 成功使用')
      return
    } catch {
      console.warn('❌ key 无效:')
    }
  }
}

const mark = () => {
  var icon = new AMap.Icon({
    size: new AMap.Size(16, 16),
    image: './static/images/main/map.png',
    imageOffset: new AMap.Pixel(0, 0), // 设置偏移量
    imageSize: new AMap.Size(16, 16),
  })
  let marker = new AMap.Marker({
    position: center,
    offset: new AMap.Pixel(50, -100),
    icon: icon,
    label: {
      content: '燃谷科技（南京）有限公司',
      offset: new AMap.Pixel(-13, -20),
    },
  })

  map.value.add(marker)
}

const toGDMap = () => {
  let query = {
    query: '万谷硅巷',
    city: '320100',
    geoobj: '118.757114|32.066745|118.768038|32.071509',
    zoom: '17.5',
  }
  window.open(
    `https://ditu.amap.com/search?query=${query.query}&city=${query.city}&geoobj=${query.geoobj}&zoom=${query.zoom}`
  )
}

onMounted(async () => {
  await initMap()
  mark()
})
</script>

<template>
  <div id="map" class="page" @click="toGDMap"></div>
</template>
