<template>
  <div class="overlay-page">
    <!-- ═══ 地图初始化状态 ═══ -->
    <div v-if="loading" class="map-status">⏳ 地图加载中...</div>
    <div v-else-if="error" class="map-status map-error">❌ {{ error }}</div>

    <!-- ═══ 图片加载状态 ═══ -->
    <div v-if="mapReady && imageLoading" class="map-status">🖼️ 图片加载中...</div>

    <!-- ═══ 地图容器 ═══ -->
    <div
      ref="containerRef"
      class="map-container"
      :class="{ 'map-hidden': loading || error }"
    />

    <!-- ═══ 底部控制栏 ═══ -->
    <div class="map-controls">
      <div class="controls-row">
        <span class="controls-title">🖼️ 图片叠加层</span>
        <div class="controls-actions">
          <!-- 显示/隐藏 -->
          <button
            :disabled="!imageLayer"
            @click="toggleVisible"
          >
            {{ layerVisible ? '👁️ 隐藏图片' : '👁️‍🗨️ 显示图片' }}
          </button>
          <!-- 透明度 -->
          <label class="opacity-label">
            透明度:
            <input
              type="range"
              min="0"
              max="100"
              :value="opacityPercent"
              :disabled="!imageLayer"
              @input="setOpacity"
            />
            <span class="opacity-value">{{ opacityPercent }}%</span>
          </label>
          <!-- 隐藏/显示地图标注 -->
          <button
            :disabled="!mapReady"
            @click="toggleLabels"
          >
            {{ labelsHidden ? '🏷️ 显示标注' : '🚫 隐藏标注' }}
          </button>
          <!-- 移除/重新叠加 -->
          <button
            v-if="imageLayer"
            class="btn-danger"
            @click="removeImageLayer"
          >
            🗑️ 移除叠加
          </button>
          <button
            v-else
            :disabled="!mapReady"
            @click="addImageLayer"
          >
            ➕ 叠加图片
          </button>
        </div>
      </div>

      <!-- ═══ 第二行：标记操作 ═══ -->
      <div class="controls-row">
        <span class="controls-title">📍 标记点</span>
        <div class="controls-actions">
          <!-- 添加标记模式 -->
          <button
            v-if="!markerMode"
            :disabled="!imageLayer"
            @click="enterMarkerMode"
          >
            📍 添加标记
          </button>
          <button
            v-else
            class="btn-finish"
            @click="exitMarkerMode"
          >
            🎯 点击地图放置标记...
          </button>
          <!-- 清除所有标记 -->
          <button
            v-if="markers.length > 0"
            class="btn-danger"
            :disabled="markerMode"
            @click="clearMarkers"
          >
            🗑️ 清除标记 ({{ markers.length }})
          </button>
          <!-- 删除最后添加的标记 -->
          <button
            v-if="markers.length > 0"
            class="btn-reset"
            :disabled="markerMode"
            @click="removeLastMarker"
          >
            ↩ 撤销上一个
          </button>
        </div>
      </div>

      <!-- ── 标记模式提示条 ── -->
      <div v-if="markerMode" class="controls-row draw-hint-row">
        <span class="draw-hint">
          🎯 <strong>点击地图</strong>放置标记 &nbsp;|&nbsp;
          已放置 <strong>{{ markers.length }}</strong> 个标记 &nbsp;|&nbsp;
          再次点击「🎯」按钮退出
        </span>
      </div>
      <div v-if="imageLayer" class="controls-row controls-info">
        <span class="info-text">
          图片: desktop.png &nbsp;|&nbsp;
          范围: [{{ boundsSW.join(', ') }}] → [{{ boundsNE.join(', ') }}]
        </span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
// ============================================================
// 图片叠加层演示页 — 将 desktop.png 叠加到高德地图上
// ============================================================
import { ref, computed, shallowRef, onMounted, onUnmounted, nextTick } from 'vue'
import { useAmap } from '@/composables/useAmap'
import desktopPng from '@/assets/desktop.png'

// ═══ 地图初始化 ═══
const { containerRef, mapInstance, loading, error, initMap } = useAmap({
  center: [116.397428, 39.90923], // 北京天安门
  zoom: 14,
})

const mapReady = ref(false)

async function bootstrapMap() {
  const map = await initMap()
  if (map) {
    mapReady.value = true
    nextTick(() => map.resize())
  }
}
onMounted(() => bootstrapMap())

// ═══ 图片叠加层 ═══
const imageLayer = shallowRef<AMap.ImageLayer | null>(null)
const layerVisible = ref(true)
const opacityPercent = ref(100)
const imageLoading = ref(false)
const labelsHidden = ref(false)

/** 底图默认显示的要素 */
const DEFAULT_FEATURES = ['bg', 'road', 'building', 'point']
/** 隐藏标注后的要素（去掉 point，PIO 标注和路名都不显示） */
const NO_LABEL_FEATURES = ['bg', 'road', 'building']

// 叠加范围：以北京市中心为参照，生成一个约 2km × 1.5km 的矩形区域
const boundsSW = computed(() => [116.385, 39.902])
const boundsNE = computed(() => [116.410, 39.917])

/** 将图片叠加到地图上 */
function addImageLayer() {
  const map = mapInstance.value
  if (!map) return

  if (imageLayer.value) return // 已有叠加层，避免重复创建

  imageLoading.value = true

  // 创建图片图层
  const layer = new AMap.ImageLayer({
    url: desktopPng,
    bounds: new AMap.Bounds(
      boundsSW.value as [number, number],
      boundsNE.value as [number, number],
    ),
    zooms: [3, 20],
    zIndex: 200,
    opacity: opacityPercent.value / 100,
  })

  // 监听图片加载完成
  layer.on('complete', () => {
    imageLoading.value = false
    console.log('[ImageOverlay] 图片加载完成')
  })

  layer.setMap(map)
  imageLayer.value = layer
}

/** 移除图片叠加层 */
function removeImageLayer() {
  if (imageLayer.value) {
    imageLayer.value.setMap(null)
    imageLayer.value.destroy()
    imageLayer.value = null
    imageLoading.value = false
  }
}

/** 切换可见性 */
function toggleVisible() {
  if (!imageLayer.value) return
  layerVisible.value = !layerVisible.value
  if (layerVisible.value) {
    imageLayer.value.show()
  } else {
    imageLayer.value.hide()
  }
}

/** 设置透明度 */
function setOpacity(e: Event) {
  const val = Number((e.target as HTMLInputElement).value)
  opacityPercent.value = val
  if (imageLayer.value) {
    imageLayer.value.setOpacity(val / 100)
  }
}

/** 切换地图标注显示/隐藏 */
function toggleLabels() {
  const map = mapInstance.value
  if (!map) return

  labelsHidden.value = !labelsHidden.value
  const features = labelsHidden.value ? NO_LABEL_FEATURES : DEFAULT_FEATURES
  map.setFeatures(features)
}

// ═══ 标记（Marker）═══
const markerMode = ref(false)
const markers = shallowRef<AMap.Marker[]>([])

/** 点击地图放置标记的回调（在进入/退出模式时绑定/解绑） */
function onMapClick(e: any) {
  const map = mapInstance.value
  if (!map || !markerMode.value) return

  // 从事件中提取经纬度
  const lngLat = e.lnglat || e.lngLat
  if (!lngLat) return

  const pos: [number, number] = [lngLat.lng, lngLat.lat]
  const idx = markers.value.length + 1

  // 创建带编号的标记
  const marker = new AMap.Marker({
    position: pos,
    content: `<div class="img-marker-dot">${idx}</div>`,
    offset: new AMap.Pixel(-13, -13),
    zIndex: 500, // 确保在 ImageLayer（zIndex=200）之上
    draggable: true,
  })

  // 拖拽结束时更新位置信息
  marker.on('dragend', function (this: AMap.Marker) {
    const p = this.getPosition()
    console.log(`[Marker ${idx}] 拖拽到: [${p.lng.toFixed(6)}, ${p.lat.toFixed(6)}]`)
  })

  marker.setMap(map)
  markers.value = [...markers.value, marker]

  console.log(`[Marker ${idx}] 放置于: [${pos[0].toFixed(6)}, ${pos[1].toFixed(6)}]`)
}

/** 进入标记模式 */
function enterMarkerMode() {
  const map = mapInstance.value
  if (!map) return

  markerMode.value = true
  map.setDefaultCursor('crosshair')
  map.on('click', onMapClick)
}

/** 退出标记模式 */
function exitMarkerMode() {
  const map = mapInstance.value
  if (!map) return

  markerMode.value = false
  map.setDefaultCursor('default')
  map.off('click', onMapClick)
}

/** 清除所有标记 */
function clearMarkers() {
  const map = mapInstance.value
  markers.value.forEach((m) => {
    m.setMap(null)
    m.destroy()
  })
  markers.value = []
  // 如果正在标记模式中，退出
  if (markerMode.value) {
    exitMarkerMode()
  }
}

/** 撤销最后一个标记 */
function removeLastMarker() {
  const last = markers.value[markers.value.length - 1]
  if (!last) return
  last.setMap(null)
  last.destroy()
  markers.value = markers.value.slice(0, -1)
}

// ═══ 生命周期清理 ═══
onUnmounted(() => {
  removeImageLayer()
  clearMarkers()
  // 恢复底图标注，避免影响其他页面
  if (mapInstance.value && labelsHidden.value) {
    mapInstance.value.setFeatures(DEFAULT_FEATURES)
  }
})
</script>

<style scoped>
/* ═══════════════════════════════════════════
   页面布局
   ═══════════════════════════════════════════ */
.overlay-page {
  flex: 1;
  position: relative;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
}

/* ── 状态浮层 ── */
.map-status {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 10;
  padding: 14px 24px;
  text-align: center;
  font-size: 14px;
  color: #666;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  pointer-events: none;
}

.map-error {
  color: #e74c3c;
  background: #fef2f2;
  border: 1px solid #fecaca;
}

/* ── 地图容器 ── */
.map-container {
  flex: 1;
  width: 100%;
  min-height: 0;
}

.map-hidden {
  visibility: hidden;
}

/* ═══════════════════════════════════════════
   底部控制栏
   ═══════════════════════════════════════════ */
.map-controls {
  display: flex;
  flex-direction: column;
  background: #fff;
  border-top: 1px solid #e8e8e8;
  box-shadow: 0 -2px 6px rgba(0, 0, 0, 0.04);
  flex-shrink: 0;
  z-index: 5;
}

.controls-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 16px;
  gap: 12px;
}

.controls-row + .controls-row {
  border-top: 1px solid #f0f0f0;
  padding-top: 6px;
  padding-bottom: 6px;
}

.controls-title {
  font-size: 15px;
  font-weight: 600;
  color: #333;
  white-space: nowrap;
}

.controls-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

/* ── 按钮 ── */
.controls-actions button {
  padding: 6px 14px;
  border: 1px solid #42b883;
  border-radius: 6px;
  background: #fff;
  color: #42b883;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.2s;
  white-space: nowrap;
}

.controls-actions button:hover:not(:disabled) {
  background: #42b883;
  color: #fff;
}

.controls-actions button:disabled {
  opacity: 0.35;
  cursor: not-allowed;
}

.btn-danger {
  border-color: #FF4D4F !important;
  color: #FF4D4F !important;
}

.btn-danger:hover:not(:disabled) {
  background: #FF4D4F !important;
  color: #fff !important;
}

/* ── 透明度滑条 ── */
.opacity-label {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  color: #555;
}

.opacity-label input[type='range'] {
  width: 100px;
  accent-color: #42b883;
}

.opacity-value {
  font-size: 12px;
  color: #888;
  width: 32px;
  text-align: right;
}

/* ── 信息条 ── */
.controls-info {
  background: #f8f9fa;
}

.info-text {
  font-size: 11px;
  color: #888;
  font-family: monospace;
}

/* ── 标记模式提示 ── */
.draw-hint-row {
  background: #f0faf5;
  border-top: 1px solid #d0ede0;
}

.draw-hint {
  font-size: 12px;
  color: #555;
  line-height: 1.6;
}

.draw-hint strong {
  color: #42b883;
}

/* ── 按钮变体 ── */
.btn-finish {
  border-color: #42b883 !important;
  background: #42b883 !important;
  color: #fff !important;
  font-weight: 600;
  animation: btn-finish-pulse 0.8s ease-in-out infinite alternate;
}

@keyframes btn-finish-pulse {
  from { box-shadow: 0 0 0 rgba(66, 184, 131, 0); }
  to   { box-shadow: 0 0 12px rgba(66, 184, 131, 0.5); }
}

.btn-reset {
  border-color: #95a5a6 !important;
  color: #95a5a6 !important;
}

.btn-reset:hover:not(:disabled) {
  background: #95a5a6 !important;
  color: #fff !important;
}
</style>

<!-- Marker 自定义样式（不能 scoped，AMap 直接注入 DOM） -->
<style>
.img-marker-dot {
  width: 26px;
  height: 26px;
  border-radius: 50%;
  background: linear-gradient(135deg, #FF6B6B, #FF4D4F);
  color: #fff;
  font-size: 12px;
  font-weight: 700;
  text-align: center;
  line-height: 26px;
  border: 2px solid #fff;
  box-shadow: 0 2px 8px rgba(255, 77, 79, 0.4);
  cursor: grab;
  user-select: none;
}
</style>
