<route lang="yaml">
meta:
   layout: map
</route>

<script setup lang="ts">
import { useOptions } from '@/composables/dateOpt'
import AMapLoader from '@amap/amap-jsapi-loader'
import '@amap/amap-jsapi-types'

const amapInstance = ref<null | typeof AMap>(null)
const map = ref<null | AMap.Map>(null)
const previousLayer = ref<null | AMap.ImageLayer>(null)

const apiKey = import.meta.env.VITE_AMAP_API_KEY

const { options } = useOptions()

watch(options, async () => {
  if (!map.value || !amapInstance.value) {
    return
  }
  if (options.castBeginDate === '' || options.castDayNo === -1) {
    return
  }
  updateMap()
})

function updateMap() {
  if (!map.value || !amapInstance.value) {
    return
  }

  const q = new URLSearchParams()
  q.set('day', options.castDayNo.toString())
  const path = options.mapping[options.castBeginDate]
  q.set('path', path)
  const base = import.meta.env.VITE_BACKEND_URL

  const url = `${base}/tc/render?${q}`

  const image = new amapInstance.value.ImageLayer({
    url,
    // @ts-expect-error AMap messed up their definition
    bounds: new AMap.Bounds([-180, -35], [180, 35]),
    // bounds: [-150, -35, 180, 35],
    zIndex: 9,
    opacity: 1,
    // zooms: [15, 20],
  })
  map.value.add(image)
  image.on('complete', () => {
    previousLayer.value?.hide()
    previousLayer.value = image
  })
}

onMounted(async () => {
  const _AMap: typeof AMap = await AMapLoader.load({
    key: apiKey,
    version: '2.0',
    plugins: [''],
  })
  amapInstance.value = _AMap

  map.value = new _AMap.Map('amap-container', {
    zoom: 4,
    center: [130, 17],
    zooms: [4, 20],
    // layers: [
    /* new AMap.TileLayer.Satellite() */
    // new AMap.TileLayer.RoadNet(),
    // ],
  })

  map.value.setBounds(new AMap.Bounds([-180, -35], [180, 35]))
  map.value.setLimitBounds(new AMap.Bounds([-180, -35], [180, 35]))
  map.value.setZoom(4)
})
</script>

<template>
  <div id="amap-container" class="m-0 h-full w-full p-0" />
</template>
